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

An account lists and ends its OAuth sessions and devices

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:oauth/account-sessions
compat/README.md+1−0
@@ -54,6 +54,7 @@ in its gates.
| `oauthDeviceCookies` (device cookies, renewed at sign-in, 30 s of grace) | oauth | Monolith's own: the reference's page API | |
| `oauthSilentSignIn` (a remembered device sent back at once) | oauth-clients | Monolith's own: the reference's page API | |
| `oauthDepartures`, `oauthClientDepartures` (spec/OAUTH.md's and spec/OAUTH-CLIENTS.md's departures, held to the spec) | oauth, oauth-clients | Monolith's own | |
| `oauthAccountAuth`, `oauthAccountSessions`, `oauthAccountDevices`, and with `--commands` `oauthAccountCommands` (spec/OAUTH-ACCOUNT.md's routes, which the reference does not serve) | oauth-account | Monolith's own | |
| `createSession`, `getSession`, `describeServer`, `refreshSession`, `deleteSession`, `wrongTokens`, `appPasswords`, `sessionRace` | accounts, session, sessions | core | sessions |
| `createAccount`, `createAccountRefused`, `accountRace` | accounts | core | accounts |
| `createRecord`, `putRecord`, `deleteRecord`, `applyWrites`, `getRecord`, `listRecords`, `describeRepo`, `createWithTid`, `concurrent`, `oddRequests`, `crossWrites` | records, odd, accounts | core | records |
crates/pds-cli/src/lib.rs+151−40
@@ -1,7 +1,8 @@
//! The CLI: each method the server serves as a command, `pds <group> <command>
//! [flags]`, calling the server at `PDS_URL` over XRPC (`spec/COMMANDS.md`);
//! and the admin's reads, `pds admin logs` and `pds admin stats`, which no
//! lexicon makes, calling `/xrpc/_logs` and `/xrpc/_stats` (`READS`).
//! and the routes no lexicon makes a command of (`OWN`): the admin's reads,
//! `pds admin logs` and `pds admin stats`, calling `/xrpc/_logs` and
//! `/xrpc/_stats`, and the account's OAuth routes, the group `oauth`.
//!
//! Exit statuses: 0 for the method's answer, 1 for an error it answers, 2 for
//! a usage error (no call made), 3 for a server that cannot be reached.
@@ -57,7 +58,7 @@ fn command(args: &[String]) -> Result<u8, Stop> {
print!("{}", top_help());
return Ok(0);
}
if !pds_lexicon::groups().contains(&group.as_str()) {
if !groups().contains(&group.as_str()) {
return usage(format!("no group {group}; `pds --help` lists them"));
}
let Some(name) = args.get(1) else {
@@ -70,13 +71,13 @@ fn command(args: &[String]) -> Result<u8, Stop> {
print!("{}", group_help(group));
return Ok(0);
}
if let Some(r) = READS.iter().find(|r| group == ADMIN && r.command == name) {
if let Some(r) = OWN.iter().find(|r| r.group == group && r.command == name) {
let flags: Vec<&Arg> = r.args.iter().collect();
let Some(args) = parse_flags(ADMIN, r.command, &flags, &args[2..])? else {
print!("{}", help(ADMIN, r.command, Some(r.description), &flags));
let Some(args) = parse_flags(r.group, r.command, &flags, &args[2..])? else {
print!("{}", help(r.group, r.command, Some(r.description), &flags));
return Ok(0);
};
return call_read(r, args);
return call_own(r, args);
}
let Some(m) = pds_lexicon::by_command(group, name) else {
return usage(format!(
@@ -94,65 +95,132 @@ fn command(args: &[String]) -> Result<u8, Stop> {
/// `com.atproto.admin`'s methods.
const ADMIN: &str = "admin";
/// One of the admin's reads (`spec/COMMANDS.md`, "The admin's reads"): a
/// command of no lexicon's, its route, its description and its flags.
struct AdminRead {
/// The group of the account's OAuth routes, after every other group.
const OAUTH: &str = "oauth";
/// Every group, in the order listed: the lexicons', then `oauth`.
fn groups() -> Vec<&'static str> {
let mut groups = pds_lexicon::groups();
groups.push(OAUTH);
groups
}
/// A command of no lexicon's (`spec/COMMANDS.md`, "The admin's reads" and
/// "The account's OAuth sessions"): its group and name, its route, whether
/// it is a `POST` of its flags as JSON rather than a `GET` with them as the
/// query, its description and its flags.
struct Own {
group: &'static str,
command: &'static str,
route: &'static str,
post: bool,
description: &'static str,
args: Vec<Arg>,
}
static READS: LazyLock<[AdminRead; 2]> = LazyLock::new(|| {
let arg = |name: &str, ty: Type, description: &str, schema: Json| Arg {
static OWN: LazyLock<[Own; 6]> = LazyLock::new(|| {
let arg = |name: &str, ty: Type, required: bool, description: &str, schema: Json| Arg {
name: name.into(),
ty,
required: false,
required,
description: Some(description.into()),
def: schema.clone(),
schema,
};
let string = || json!({ "type": "string" });
let get = |group, command, route, description| Own {
group,
command,
route,
post: false,
description,
args: vec![],
};
let revoke = |command, route, description, id: &str| Own {
group: OAUTH,
command,
route,
post: true,
description,
args: vec![arg("id", Type::String, true, id, string())],
};
[
AdminRead {
command: "logs",
route: "_logs",
description: "As the admin, the lines the server logged and kept in PDS_LOG_DIR, oldest first: the last of those of a trace, a message, a route, a level and above, or a time. Needs the admin's Basic auth.",
Own {
args: vec![
arg("trace", Type::String, "Lines of this trace id.", string()),
arg("msg", Type::String, "Lines of this msg.", string()),
arg(
"trace",
Type::String,
false,
"Lines of this trace id.",
string(),
),
arg("msg", Type::String, false, "Lines of this msg.", string()),
arg(
"method",
Type::String,
false,
"Lines of this route, as com.atproto.repo.createRecord or /oauth/token.",
string(),
),
arg(
"level",
Type::String,
false,
"Lines at this level or above: debug, info, warn or error.",
json!({ "type": "string", "enum": ["debug", "info", "warn", "error"] }),
),
arg(
"minMs",
Type::Integer,
false,
"Lines with an ms of this many milliseconds or more.",
json!({ "type": "integer", "minimum": 0 }),
),
arg(
"limit",
Type::Integer,
false,
"How many, the last of those matched: 1 to 500, 100 if not given.",
json!({ "type": "integer", "minimum": 1, "maximum": 500 }),
),
],
..get(
ADMIN,
"logs",
"_logs",
"As the admin, the lines the server logged and kept in PDS_LOG_DIR, oldest first: the last of those of a trace, a message, a route, a level and above, or a time. Needs the admin's Basic auth.",
)
},
AdminRead {
command: "stats",
route: "_stats",
description: "As the admin, what the server counted since it started: its requests by route and status with their mean times, the requests it made, its syncs, its accounts and its firehose. Needs the admin's Basic auth.",
args: vec![],
},
get(
ADMIN,
"stats",
"_stats",
"As the admin, what the server counted since it started: its requests by route and status with their mean times, the requests it made, its syncs, its accounts and its firehose. Needs the admin's Basic auth.",
),
get(
OAUTH,
"sessions",
"_oauthSessions",
"The OAuth sessions of your account, the apps you signed in to, newest first: each with its id, client, issuer (atproto or mcp), scope, and when it started, was last refreshed and ends. Needs your account's password session.",
),
revoke(
"revoke-session",
"_oauthRevokeSession",
"End one of your account's OAuth sessions by its id, as oauth_sessions lists it: the app is signed out at once. Needs your account's password session.",
"The session's id, as `pds oauth sessions` lists it.",
),
get(
OAUTH,
"devices",
"_oauthDevices",
"The browsers your account is signed in on through the OAuth sign-in page, newest sign-in first: each with its id, when it signed in, and its user agent and IP address. Needs your account's password session.",
),
revoke(
"revoke-device",
"_oauthRevokeDevice",
"Sign your account out of one browser by its id, as oauth_devices lists it. Its apps' sessions stay: end those with oauth_revoke_session. Needs your account's password session.",
"The browser's id, as `pds oauth devices` lists it.",
),
]
});
@@ -166,7 +234,7 @@ fn top_help() -> String {
pds <group> <command> --help list a command's flags\n\n\
Groups:\n",
);
for g in pds_lexicon::groups() {
for g in groups() {
out.push_str(&format!(" {g}\n"));
for (name, description) in listed(g) {
out.push_str(&format!(" {name:<20} {description}\n"));
@@ -175,18 +243,18 @@ fn top_help() -> String {
out
}
/// A group's commands, each with its description: its methods', then, in
/// `admin`, the admin's reads.
/// A group's commands, each with its description: its methods', then its
/// commands of no lexicon's (`OWN`).
fn listed(group: &str) -> Vec<(String, &'static str)> {
let methods = pds_lexicon::methods()
.iter()
.filter(|m| m.group == group)
.filter_map(|m| Some((m.command()?, m.description.as_deref().unwrap_or(""))));
let reads = READS
let own = OWN
.iter()
.filter(|_| group == ADMIN)
.filter(|r| r.group == group)
.map(|r| (r.command.to_string(), r.description));
methods.chain(reads).collect()
methods.chain(own).collect()
}
fn group_help(group: &str) -> String {
@@ -596,12 +664,22 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> {
Ok(0)
}
/// Call one of the admin's reads: its JSON answer, printed as the server
/// sent it, one line (`_logs`' lines each as the server wrote it); or its
/// error, printed as a method's.
fn call_read(r: &AdminRead, args: Map<String, Json>) -> Result<u8, Stop> {
/// Call one of the commands of no lexicon's: its JSON answer, printed as
/// the server sent it, one line (`_logs`' lines each as the server wrote
/// it); or its error, printed as a method's.
fn call_own(r: &Own, args: Map<String, Json>) -> Result<u8, Stop> {
let server = Server::from_env()?;
let res = server.get(&format!("{}/xrpc/{}", server.url, r.route), &args)?;
let url = format!("{}/xrpc/{}", server.url, r.route);
let res = if r.post {
let req = server
.http
.post(&url)
.header("content-type", JSON)
.body(Json::Object(args).to_string());
server.with_auth(req)?
} else {
server.get(&url, &args)?
};
let status = res.status().as_u16();
let text = res
.text()
@@ -792,7 +870,7 @@ mod tests {
assert!(names.len() > 2);
let help = group_help(ADMIN);
assert!(help.contains("As the admin, what the server counted since it started"));
let logs = &READS[0];
let logs = &OWN[0];
let flags: Vec<&Arg> = logs.args.iter().collect();
let text = help_of(logs);
for f in [
@@ -818,11 +896,44 @@ mod tests {
] {
assert!(matches!(parse(bad), Err(Stop::Usage(_))), "{bad:?}");
}
assert!(help_of(&READS[1]).contains("It takes no flags."));
assert!(help_of(&OWN[1]).contains("It takes no flags."));
}
/// The account's OAuth routes are the group `oauth`, listed after every
/// other, its commands in the spec's order; a revocation needs `--id`,
/// a list takes no flag.
#[test]
fn oauth_commands() {
assert_eq!(groups().last(), Some(&OAUTH));
assert!(!pds_lexicon::groups().contains(&OAUTH));
let names: Vec<String> = listed(OAUTH).into_iter().map(|(n, _)| n).collect();
assert_eq!(
names,
["sessions", "revoke-session", "devices", "revoke-device"]
);
assert!(top_help().trim_end().ends_with(OWN[5].description));
for r in OWN.iter().filter(|r| r.group == OAUTH) {
let flags: Vec<&Arg> = r.args.iter().collect();
let parse = |argv: &[&str]| {
let argv: Vec<String> = argv.iter().map(|a| a.to_string()).collect();
parse_flags(OAUTH, r.command, &flags, &argv)
};
if r.post {
assert!(help_of(r).contains("--id"));
assert!(matches!(parse(&[]), Err(Stop::Usage(_))));
assert_eq!(
parse(&["--id", "x"]).ok().flatten().map(Json::Object),
Some(json!({ "id": "x" }))
);
} else {
assert!(help_of(r).contains("It takes no flags."));
assert!(matches!(parse(&["--id", "x"]), Err(Stop::Usage(_))));
}
}
}
fn help_of(r: &AdminRead) -> String {
fn help_of(r: &Own) -> String {
let flags: Vec<&Arg> = r.args.iter().collect();
help(ADMIN, r.command, Some(r.description), &flags)
help(r.group, r.command, Some(r.description), &flags)
}
}
crates/pds-server/src/oauth/account.rsnew+377−0
@@ -0,0 +1,377 @@
//! The account's own OAuth sessions and devices (`spec/OAUTH-ACCOUNT.md`):
//! `GET /xrpc/_oauthSessions`, `POST /xrpc/_oauthRevokeSession`, `GET
//! /xrpc/_oauthDevices` and `POST /xrpc/_oauthRevokeDevice`, of no lexicon.
//! Each is answered by `answer`, over XRPC (`xrpc`) and as its MCP tool
//! (`spec/COMMANDS.md`, "The account's OAuth sessions"): the token
//! `getAccountInviteCodes` takes first, then the HTTP method, then a
//! revocation's body, then a point of `global`.
//!
//! A session and a device are named by a public id: the first 16 bytes of a
//! MAC, under OAuth's secret, of the session's or the device's own id, with
//! a label of each's own, in lower case hexadecimal, so that a CLI `--id`
//! never starts with `-`. It stays the same for as long as they last, as the
//! secret does, and is none of the tokens and cookies the server seals, nor
//! the device's id or a session's code, so it is taken as none of them; nor
//! can either be found from it.
use super::{LOGIN_LIFE, State, Tx};
use crate::sessions::Bearer;
use crate::{Call, Service, Shared, XrpcError, err, internal, invalid, limits, sessions};
use axum::body::Body;
use axum::extract::{Extension, State as AxState};
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
use axum::response::Response;
use serde_json::{Value as Json, json};
use std::sync::OnceLock;
/// The labels the public ids of sessions and of devices are MACs for.
pub(super) const SESSION_ID: &str = "session id";
pub(super) const DEVICE_ID: &str = "device id";
/// One of the account's OAuth routes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Route {
Sessions,
RevokeSession,
Devices,
RevokeDevice,
}
impl Route {
/// Each, in the order `spec/COMMANDS.md` lists them.
pub const ALL: [Route; 4] = [
Route::Sessions,
Route::RevokeSession,
Route::Devices,
Route::RevokeDevice,
];
/// Its route, as its path names it after `/xrpc/`, and its request's
/// line and metrics label it.
pub fn name(self) -> &'static str {
match self {
Route::Sessions => "_oauthSessions",
Route::RevokeSession => "_oauthRevokeSession",
Route::Devices => "_oauthDevices",
Route::RevokeDevice => "_oauthRevokeDevice",
}
}
/// Its MCP tool's name.
fn tool(self) -> &'static str {
match self {
Route::Sessions => "oauth_sessions",
Route::RevokeSession => "oauth_revoke_session",
Route::Devices => "oauth_devices",
Route::RevokeDevice => "oauth_revoke_device",
}
}
/// The route whose MCP tool has this name.
pub fn of_tool(name: &str) -> Option<Route> {
Route::ALL.into_iter().find(|r| r.tool() == name)
}
/// The HTTP method it takes: a list `GET`, a revocation `POST`.
pub fn method(self) -> Method {
match self {
Route::Sessions | Route::Devices => Method::GET,
Route::RevokeSession | Route::RevokeDevice => Method::POST,
}
}
fn description(self) -> &'static str {
match self {
Route::Sessions => {
"The OAuth sessions of your account, the apps you signed in to, newest first: each with its id, client, issuer (atproto or mcp), scope, and when it started, was last refreshed and ends. Needs your account's password session."
}
Route::RevokeSession => {
"End one of your account's OAuth sessions by its id, as oauth_sessions lists it: the app is signed out at once. Needs your account's password session."
}
Route::Devices => {
"The browsers your account is signed in on through the OAuth sign-in page, newest sign-in first: each with its id, when it signed in, and its user agent and IP address. Needs your account's password session."
}
Route::RevokeDevice => {
"Sign your account out of one browser by its id, as oauth_devices lists it. Its apps' sessions stay: end those with oauth_revoke_session. Needs your account's password session."
}
}
}
/// Their MCP tools, in order, as `spec/COMMANDS.md`, "The account's
/// OAuth sessions", gives them.
pub fn tools() -> impl Iterator<Item = Json> {
Route::ALL.into_iter().map(|r| {
let (schema, annotations) = if r.method() == Method::GET {
(
json!({ "type": "object", "properties": {}, "required": [] }),
json!({ "readOnlyHint": true }),
)
} else {
(
json!({
"type": "object",
"properties": { "id": { "type": "string" } },
"required": ["id"],
}),
json!({ "readOnlyHint": false, "destructiveHint": true }),
)
};
json!({
"name": r.tool(),
"description": r.description(),
"inputSchema": schema,
"annotations": annotations,
})
})
}
}
/// The refusal of an OAuth access token, whatever its scope, as
/// `listAppPasswords` refuses one.
fn forbidden<T>() -> Result<T, XrpcError> {
err(
403,
"Forbidden",
"OAuth credentials are not supported for this endpoint",
)
}
/// Answer a call of a route: its token, then its HTTP method, then a
/// revocation's body, then its point of `global`, then what it does. A call
/// whose OAuth access token passed is `Bearer::OAuth`, and refused.
pub(crate) async fn answer(svc: &Shared, route: Route, call: &Call<'_>) -> Result<Json, XrpcError> {
if let Bearer::OAuth(_) = call.bearer {
return forbidden();
}
let did = sessions::full_access_token(svc, call.bearer)?.did;
let want = route.method();
if *call.method != want {
return invalid(format!(
"Incorrect HTTP method ({}) expected {want}",
call.method
));
}
let id = if want == Method::POST {
Some(id_of(call)?)
} else {
None
};
limits::charge(svc, call, None, None)?;
crate::ops::spawn(act(svc.clone(), route, did, id))
.await
.unwrap_or_else(|_| internal())
}
/// A revocation's `id`, from its body: at most `limits::MAX_BODY` bytes,
/// else `413`; then `application/json`, an object with `id` a string, its
/// other properties ignored.
fn id_of(call: &Call) -> Result<String, XrpcError> {
if call.body.len() > limits::MAX_BODY {
return limits::too_large();
}
let essence = call
.headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|v| {
v.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
});
if essence.as_deref() != Some("application/json") {
return invalid("Content-Type must be application/json");
}
let Ok(Json::Object(b)) = serde_json::from_slice::<Json>(call.body) else {
return invalid("Invalid request body");
};
match b.get("id") {
Some(Json::String(id)) => Ok(id.clone()),
Some(_) => invalid("Input/id must be a string"),
None => invalid("Input must have the property \"id\""),
}
}
/// What a route does for account `did`, answered once what it shows, or
/// the end it logged, is on disk.
async fn act(
svc: Shared,
route: Route,
did: String,
id: Option<String>,
) -> Result<Json, XrpcError> {
let id = id.unwrap_or_default();
let mut tx = Tx::new(&svc);
let out = tx.change(|st, now| match route {
Route::Sessions => (vec![], json!({ "sessions": sessions(&svc, st, &did, now) })),
Route::Devices => (vec![], json!({ "devices": devices(&svc, st, &did, now) })),
Route::RevokeSession => (
session_named(&svc, st, &did, &id, now)
.map(|sid| json!({ "t": "oauthEndSession", "sid": sid }))
.into_iter()
.collect(),
json!({}),
),
Route::RevokeDevice => (
device_named(&svc, st, &did, &id)
.map(|device| json!({ "t": "oauthSignOut", "device": device, "did": did }))
.into_iter()
.collect(),
json!({}),
),
});
if tx.done().await { Ok(out) } else { internal() }
}
/// The public id of a session or device, its id `id`, for `label`.
pub(super) fn public_id(svc: &Service, label: &str, id: &str) -> String {
hex::encode(&svc.oauth.mac(label, id.as_bytes())[..16])
}
/// Seconds since the epoch as a datetime, in UTC to the millisecond.
fn datetime(secs: u64) -> String {
pds_repo::data::datetime_string(i64::try_from(secs.saturating_mul(1000)).unwrap_or(i64::MAX))
}
/// `entries`, each with its time and public id, the latest first, then by id.
fn latest_first(mut entries: Vec<(u64, String, Json)>) -> Vec<Json> {
entries.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
entries.into_iter().map(|(_, _, j)| j).collect()
}
/// The sessions of `did` not ended and not past their end at `now`, by id.
fn sessions_of<'s>(
st: &'s State,
did: &'s str,
now: u64,
) -> impl Iterator<Item = (&'s String, &'s super::Session)> {
st.sessions
.iter()
.filter(move |(_, s)| s.did == did && s.end() > now)
}
/// `_oauthSessions`' list.
fn sessions(svc: &Service, st: &State, did: &str, now: u64) -> Vec<Json> {
latest_first(
sessions_of(st, did, now)
.map(|(sid, s)| {
let id = public_id(svc, SESSION_ID, sid);
let j = json!({
"id": id,
"clientId": s.client_id,
"issuer": if s.mcp { "mcp" } else { "atproto" },
"scope": s.granted.join(" "),
"createdAt": datetime(s.started),
"updatedAt": datetime(s.refreshed),
"expiresAt": datetime(s.end()),
});
(s.started, id, j)
})
.collect(),
)
}
/// The session of `did` whose public id is `id`, if it has one.
fn session_named(svc: &Service, st: &State, did: &str, id: &str, now: u64) -> Option<String> {
sessions_of(st, did, now)
.find(|(sid, _)| public_id(svc, SESSION_ID, sid) == id)
.map(|(sid, _)| sid.clone())
}
/// `_oauthDevices`' list.
fn devices(svc: &Service, st: &State, did: &str, now: u64) -> Vec<Json> {
latest_first(
st.devices
.iter()
.filter_map(|(device, signed)| {
let at = signed.iter().find(|(d, _)| d == did)?.1;
let id = public_id(svc, DEVICE_ID, device);
let mut j = json!({
"id": id,
"signedInAt": datetime(at),
"loginRequired": now.saturating_sub(at) > LOGIN_LIFE,
});
if let Some(w) = st.whence.get(&(device.clone(), did.to_string())) {
w.fill(&mut j);
}
Some((at, id, j))
})
.collect(),
)
}
/// The device `did` is signed in on whose public id is `id`, if there is one.
fn device_named(svc: &Service, st: &State, did: &str, id: &str) -> Option<String> {
st.devices
.iter()
.find(|(device, signed)| {
signed.iter().any(|(d, _)| d == did) && public_id(svc, DEVICE_ID, device) == id
})
.map(|(device, _)| device.clone())
}
/// A route over XRPC. Its query, and a list's body, are ignored. An OAuth
/// access token, sent as `DPoP`, is checked with its proof as on any method
/// that needs a token, and once it passes, refused, with the nonce.
pub(crate) async fn xrpc(
AxState(svc): AxState<Shared>,
method: Method,
headers: HeaderMap,
peer: Option<Extension<limits::Peer>>,
body: Body,
route: Route,
) -> Response {
// Read one byte past the cap, as it comes, chunked or not: `id_of` refuses more.
let Some(body) = limits::read_body(body, limits::MAX_BODY).await else {
return crate::respond(invalid("The body could not be read"), None);
};
let authorization = crate::authorization(&headers);
let call = Call {
nsid: route.name(),
method: &method,
params: &[],
body: &body,
bearer: Bearer::of(authorization.as_deref()),
headers: &headers,
client: limits::client(
&svc.config.trusted_proxies,
&headers,
peer.map(|Extension(p)| p.0),
),
charged: OnceLock::new(),
http: None,
};
if let Bearer::DPoP(token) = call.bearer {
let path = format!("/xrpc/{}", route.name());
return match super::access(&svc, &method, &path, &headers, token).await {
Err(e) => crate::respond(Err(e), None),
Ok(Err((error, why))) => {
let mut r = crate::respond(err(401, error, why.as_str()), None);
super::dpop_headers(&svc, &mut r, Some((error, &why)));
r
}
Ok(Ok(a)) => {
crate::ops::verified(&a.did);
let mut r = crate::respond(forbidden(), None);
super::dpop_headers(&svc, &mut r, None);
r
}
};
}
match answer(&svc, route, &call).await {
Ok(j) => {
let mut r = Response::new(Body::from(j.to_string()));
*r.status_mut() = StatusCode::OK;
r.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf-8"),
);
if let Some(c) = call.charged.get() {
c.apply(r.headers_mut());
}
r
}
Err(e) => crate::respond(Err(e), call.charged.get()),
}
}
crates/pds-server/src/oauth/page.rs+28−10
@@ -7,8 +7,8 @@
//! the page's `csrf-token` cookie back as their `x-csrf-token` header.
use super::{
EPHEMERAL_LIFE, REQUEST_LIFE, REQUEST_URI, Request, State, Tx, assets, client, clients, finish,
json_response, new_id, scope, set,
EPHEMERAL_LIFE, REQUEST_LIFE, REQUEST_URI, Request, State, Tx, Whence, assets, client, clients,
finish, json_response, new_id, scope, set,
};
use crate::email::Purpose::AuthFactor;
use crate::{Account, Service, Shared};
@@ -696,11 +696,23 @@ pub(super) async fn api(
&headers,
peer.map(|Extension(p)| p.0),
);
let whence = Whence::of(&headers, &client);
finish(async move {
let mut tx = Tx::new(&svc);
let mut device = device(&svc, &mut tx, &headers);
let answer = match endpoint.as_str() {
"sign-in" => sign_in(&svc, &mut tx, &mut device, &request_id, &client, &b).await,
"sign-in" => {
sign_in(
&svc,
&mut tx,
&mut device,
&request_id,
&client,
&whence,
&b,
)
.await
}
"consent" => consent(&svc, &mut tx, &headers, &device.id, &request_id, &b).await,
"reject" => reject(&svc, &mut tx, &request_id),
_ => sign_out(&mut tx, &device.id, &b).map_err(Refusal::from),
@@ -781,13 +793,15 @@ impl From<crate::XrpcError> for Refusal {
/// `sign-in`: the login limits paid, the account's own password, not an app
/// password, then the code its email factor asks for, as `createSession`
/// checks them (`spec/OAUTH.md`, "The API").
/// checks them (`spec/OAUTH.md`, "The API"). A sign-in remembered is kept
/// with where it came from (`whence`).
async fn sign_in(
svc: &Shared,
tx: &mut Tx<'_>,
device: &mut Device,
request_id: &str,
client: &str,
whence: &Whence,
b: &Map<String, Json>,
) -> Result<Json, Refusal> {
let id = text(b, "identifier");
@@ -846,7 +860,7 @@ async fn sign_in(
match code {
Some(_) => {
let used = crate::email::use_entry(&did, AuthFactor);
let remembered = sign_in_here(tx, device, &did, remember, Some(&used));
let remembered = sign_in_here(tx, device, &did, remember, whence, Some(&used));
if !tx.failed {
crate::email::apply(svc, &did, &mut m, &[used]);
}
@@ -856,7 +870,7 @@ async fn sign_in(
Some(crate::email::make(svc, &did, &mut m, AuthFactor)?),
false,
),
None => (None, sign_in_here(tx, device, &did, remember, None)),
None => (None, sign_in_here(tx, device, &did, remember, whence, None)),
}
};
if let Some(mail) = mail {
@@ -882,14 +896,16 @@ async fn sign_in(
/// Sign `did` in on `device`, with a code it used up (`used`), in one frame:
/// remembered, or with `remember` left out when it is signed in here
/// already, it is signed in here from now; otherwise it is not, or no
/// longer. Either way the device is given new cookies, and those it had
/// are old (`spec/OAUTH.md`, "Devices"). Answers whether it is remembered.
/// already, it is signed in here from now, from `whence`; otherwise it is
/// not, or no longer. Either way the device is given new cookies, and those
/// it had are old (`spec/OAUTH.md`, "Devices"). Answers whether it is
/// remembered.
fn sign_in_here(
tx: &mut Tx<'_>,
device: &mut Device,
did: &str,
remember: Option<bool>,
whence: &Whence,
used: Option<&Json>,
) -> bool {
let (id, key) = (device.id.as_str(), new_id(16));
@@ -897,7 +913,9 @@ fn sign_in_here(
let signed = st.signed_in(id).iter().any(|(d, _)| d == did);
let remembered = remember.unwrap_or(signed);
let entry = if remembered {
Some(json!({ "t": "oauthSignIn", "device": id, "did": did, "at": now }))
let mut e = json!({ "t": "oauthSignIn", "device": id, "did": did, "at": now });
whence.fill(&mut e);
Some(e)
} else {
signed.then(|| json!({ "t": "oauthSignOut", "device": id, "did": did }))
};
crates/pds-server/src/oauth/tests.rs+525−0
525 lines changed: not loaded until asked for.
crates/pds-server/src/lib.rs+19−0
@@ -22,6 +22,8 @@
//! registrations and deletion notices); the firehose is `events`, the MCP
//! endpoint `mcp`, the PLC directory `plc`, requests to URLs others name,
//! with SSRF protection, `outbound`, OAuth's authorization server `oauth`,
//! with the account's own routes for its OAuth sessions and devices in
//! `oauth::account`,
//! OAuth access tokens on every method and what their scopes allow
//! `scopes`, the single-use values OAuth spends `replay`, single-use values
//! the spaces spend `single_use`, what keeps the server up when anyone may
@@ -86,6 +88,7 @@ use axum::{
response::{IntoResponse, Response},
routing::{any, get},
};
use oauth::account::{self, Route as Own};
use pds_lexicon::Kind;
use pds_repo::{Refused, Repo};
use pds_store::Wal;
@@ -874,6 +877,22 @@ fn router(svc: Shared) -> Router {
.route("/xrpc/_health", any(ops::health))
.route("/xrpc/_logs", any(ops::logs))
.route("/xrpc/_stats", any(ops::stats))
.route(
"/xrpc/_oauthSessions",
any(|s, m, h, p, b| account::xrpc(s, m, h, p, b, Own::Sessions)),
)
.route(
"/xrpc/_oauthRevokeSession",
any(|s, m, h, p, b| account::xrpc(s, m, h, p, b, Own::RevokeSession)),
)
.route(
"/xrpc/_oauthDevices",
any(|s, m, h, p, b| account::xrpc(s, m, h, p, b, Own::Devices)),
)
.route(
"/xrpc/_oauthRevokeDevice",
any(|s, m, h, p, b| account::xrpc(s, m, h, p, b, Own::RevokeDevice)),
)
.route("/xrpc/com.atproto.repo.uploadBlob", any(blobs::upload))
.route("/xrpc/{*method}", any(handle))
.route("/mcp", any(mcp::endpoint))
crates/pds-server/src/mcp.rs+147−19
@@ -6,8 +6,12 @@
//! as 2025-11-25 or 2025-06-18, statelessly too, with no session. Each
//! method with a JSON answer, or none, is a tool, called through the same
//! handling as XRPC; after them, the admin's reads, `admin_logs` and
//! `admin_stats`, answered as `/xrpc/_logs` and `/xrpc/_stats` (`ops::read`).
//! `admin_stats`, answered as `/xrpc/_logs` and `/xrpc/_stats` (`ops::read`),
//! and then the account's OAuth routes, `oauth_sessions`,
//! `oauth_revoke_session`, `oauth_devices` and `oauth_revoke_device`,
//! answered as `/xrpc/_oauthSessions` and the others (`oauth::account`).
use crate::oauth::account::{self, Route as Own};
use crate::oauth::mcp::Token as McpToken;
use crate::sessions::Bearer;
use crate::{Auth, Call, Resp, Shared, XrpcError, answer, authorization, limits, ops, scopes};
@@ -572,7 +576,8 @@ fn discover() -> Json {
})
}
/// Every tool, the same in either era: each method's, then the admin's reads'.
/// Every tool, the same in either era: each method's, then the admin's
/// reads', then the account's OAuth routes'.
fn tools() -> Vec<Json> {
pds_lexicon::methods()
.iter()
@@ -588,6 +593,7 @@ fn tools() -> Vec<Json> {
Some(tool)
})
.chain(ops::Read::tools())
.chain(Own::tools())
.collect()
}
@@ -617,6 +623,13 @@ fn query_params(args: &Map<String, Json>) -> Vec<(String, String)> {
params
}
/// What a tool calls.
enum Tool {
Method(&'static Lexicon),
Read(ops::Read),
Own(Own),
}
/// Call a tool's method, with its arguments as the query's parameters or the
/// procedure's input, and the request's `Authorization` header, from `client`:
/// its answer, and whether it is an error the method answered. An MCP
@@ -632,19 +645,24 @@ async fn call_tool(
client: String,
) -> Result<(Json, bool), RpcError> {
let bearer = Bearer::of(authorization.as_deref());
// A method's tool, or one of the admin's reads'.
let tool: Result<&'static Lexicon, ops::Read> =
match (pds_lexicon::by_tool(name), ops::Read::of_tool(name)) {
(Some(m), _) => Ok(m),
(None, Some(read)) => Err(read),
(None, None) => {
return Err(rpc_err(
StatusCode::OK,
INVALID_PARAMS,
format!("Unknown tool: {name}"),
));
}
};
// A method's tool, one of the admin's reads', or one of the account's
// OAuth routes'.
let tool = match (
pds_lexicon::by_tool(name),
ops::Read::of_tool(name),
Own::of_tool(name),
) {
(Some(m), _, _) => Tool::Method(m),
(None, Some(read), _) => Tool::Read(read),
(None, None, Some(own)) => Tool::Own(own),
(None, None, None) => {
return Err(rpc_err(
StatusCode::OK,
INVALID_PARAMS,
format!("Unknown tool: {name}"),
));
}
};
let mut args = match arguments {
None | Some(Json::Null) => Map::new(),
Some(Json::Object(a)) => a.clone(),
@@ -670,11 +688,11 @@ async fn call_tool(
},
_ => None,
};
// The admin's reads, as XRPC answers them; a token, of an MCP session or
// not, is no admin.
let m = match tool {
Ok(m) => m,
Err(read) => {
Tool::Method(m) => m,
// The admin's reads, as XRPC answers them; a token, of an MCP session or
// not, is no admin.
Tool::Read(read) => {
let params = query_params(&args);
let call = Call {
nsid: read.route(),
@@ -692,6 +710,43 @@ async fn call_tool(
Err(e) => (json!({ "error": e.name, "message": e.message }), true),
});
}
// The account's OAuth routes, as XRPC answers them, a revocation's
// arguments its JSON body: an MCP session's token is refused as an
// OAuth access token is, and no token is the challenge.
Tool::Own(own) => {
let grant = mcp.map(|(_, a)| scopes::Grant {
did: a.did,
scope: scopes::Scope::of(&a.scope),
});
let method = own.method();
let body = if method == Method::POST {
Json::Object(args).to_string()
} else {
String::new()
};
let headers = HeaderMap::from_iter([(
header::CONTENT_TYPE,
HeaderValue::from_static(pds_lexicon::JSON),
)]);
let call = Call {
nsid: own.name(),
method: &method,
params: &[],
body: body.as_bytes(),
bearer: grant.as_ref().map_or(bearer, Bearer::OAuth),
headers: &headers,
client,
charged: OnceLock::new(),
http: None,
};
return match account::answer(st, own, &call).await {
Ok(j) => Ok((j, false)),
Err(e) if authorization.is_none() && e.status == 401 && e.name == "AuthMissing" => {
Err(challenge(st, None, &e.message))
}
Err(e) => Ok((json!({ "error": e.name, "message": e.message }), true)),
};
}
};
// The token's scope, for a step-up if the call is refused for it.
let granted = mcp.as_ref().map(|(_, a)| a.scope.clone());
@@ -871,6 +926,79 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// The account's OAuth routes are tools after the admin's reads, in
/// order, answered as their routes answer: with no token, the challenge
/// that has a client sign in.
#[tokio::test]
async fn oauth_tools() {
use crate::testing::*;
let all = tools();
let last: Vec<&Json> = all[all.len() - 6..].iter().map(|t| &t["name"]).collect();
assert_eq!(
last,
[
"admin_logs",
"admin_stats",
"oauth_sessions",
"oauth_revoke_session",
"oauth_devices",
"oauth_revoke_device"
]
);
let revoke = &all[all.len() - 1];
assert_eq!(
(&revoke["inputSchema"], &revoke["annotations"]),
(
&json!({ "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] }),
&json!({ "readOnlyHint": false, "destructiveHint": true })
)
);
let plc = plc().await;
let dir = scratch("mcp-oauth");
let s = open(&dir, &plc);
create(&s, "alice").await;
let token = format!("Bearer {}", session(&s, "alice").await);
let tool = |name: &'static str, args: Option<Json>, auth: Option<&str>| {
let (s, auth) = (s.clone(), auth.map(str::to_string));
async move { call_tool(&s, name, args.as_ref(), auth, "127.0.0.1".into()).await }
};
let answered = |r: Result<(Json, bool), RpcError>| match r {
Ok(r) => r,
Err(e) => panic!("{}", e.message),
};
assert_eq!(
answered(tool("oauth_sessions", None, Some(&token)).await),
(json!({ "sessions": [] }), false)
);
assert_eq!(
answered(
tool(
"oauth_revoke_device",
Some(json!({ "id": "x" })),
Some(&token)
)
.await
),
(json!({}), false)
);
let (refused, is_error) = answered(tool("oauth_revoke_session", None, Some(&token)).await);
assert_eq!(
(is_error, &refused["error"]),
(true, &json!("InvalidRequest"))
);
let (refused, is_error) =
answered(tool("oauth_devices", None, Some("Basic YWRtaW46eA==")).await);
assert_eq!(
(is_error, &refused["error"]),
(true, &json!("InvalidToken"))
);
let Err(e) = tool("oauth_sessions", None, None).await else {
panic!("no challenge");
};
assert_eq!(e.status, StatusCode::UNAUTHORIZED);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn header_values() {
assert_eq!(
crates/pds-server/src/oauth.rs+63−2
@@ -2,8 +2,10 @@
//! `spec/OAUTH.md` says: its metadata, loopback clients, pushed
//! authorization requests, the authorization page and its API (`page`),
//! the pages' build, embedded and served (`assets`),
//! the token and revocation endpoints, DPoP (`dpop`), and the check every
//! XRPC call with an OAuth access token makes of it (`access`).
//! the token and revocation endpoints, DPoP (`dpop`), the check every
//! XRPC call with an OAuth access token makes of it (`access`), and the
//! account's own routes listing and ending its sessions and devices
//! (`account`).
//!
//! What it keeps, its requests, codes, sessions and the accounts signed in
//! on each device, is one `State` behind one lock: it is not any one
@@ -23,6 +25,7 @@
//! and below the free-space floor (`low`) nothing that would keep anything
//! is taken.
pub(crate) mod account;
mod assets;
mod client;
mod clients;
@@ -370,6 +373,52 @@ impl Session {
}
}
/// Where an account signed in on a device from, as the sign-in's API call
/// came (`spec/OAUTH-ACCOUNT.md`, "_oauthDevices"): its `User-Agent`, its
/// first 256 characters, and its client address, each if it had one, or
/// none for a sign-in kept before they were.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Whence {
user_agent: Option<String>,
address: Option<String>,
}
impl Whence {
/// Of a request with these headers, from client address `client`
/// (`crate::limits::client`, empty for none).
fn of(headers: &HeaderMap, client: &str) -> Whence {
Whence {
user_agent: headers.get(header::USER_AGENT).map(|v| {
String::from_utf8_lossy(v.as_bytes())
.chars()
.take(256)
.collect()
}),
address: Some(client.to_string()).filter(|c| !c.is_empty()),
}
}
/// An `oauthSignIn` entry's, as kept: each field left out if it is not there.
fn kept(e: &Json) -> Whence {
let text = |k: &str| e[k].as_str().map(str::to_string);
Whence {
user_agent: text("userAgent"),
address: text("ipAddress"),
}
}
/// Its fields, into an `oauthSignIn` entry, or a device as
/// `_oauthDevices` answers it, which name them alike.
fn fill(&self, e: &mut Json) {
if let Some(a) = &self.user_agent {
e["userAgent"] = json!(a);
}
if let Some(a) = &self.address {
e["ipAddress"] = json!(a);
}
}
}
/// Everything OAuth keeps.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct State {
@@ -381,6 +430,9 @@ pub(crate) struct State {
by_code: HashMap<String, String>,
/// The accounts signed in on each device, with when.
devices: HashMap<String, Vec<(String, u64)>>,
/// Where each account signed in on each device signed in from, by
/// device and account, for those signed in from somewhere kept.
whence: HashMap<(String, String), Whence>,
/// Each device's cookies' key since a sign-in last gave it new ones,
/// and when: cookies of another key are old (`spec/OAUTH.md`, "Devices").
device_keys: HashMap<String, (String, u64)>,
@@ -562,6 +614,12 @@ impl State {
}
Some("oauthSignIn") => {
let (device, did, at) = (text("device")?, account("did")?, number("at")?);
let (whence, key) = (Whence::kept(e), (device.clone(), did.clone()));
if whence == Whence::default() {
self.whence.remove(&key);
} else {
self.whence.insert(key, whence);
}
let signed = self.devices.entry(device).or_default();
signed.retain(|(d, _)| *d != did);
signed.push((did, at));
@@ -579,6 +637,7 @@ impl State {
if signed.is_empty() {
self.devices.remove(&device);
}
self.whence.remove(&(device, did));
}
Some("oauthDeviceKey") => {
let (device, key, at) = (text("device")?, text("key")?, number("at")?);
@@ -588,6 +647,7 @@ impl State {
let device = text("device")?;
self.devices.remove(&device);
self.device_keys.remove(&device);
self.whence.retain(|(d, _), _| *d != device);
}
Some("oauthForgetClients") => {
self.approved.remove(&text("did")?);
@@ -659,6 +719,7 @@ impl State {
signed.retain(|(d, _)| d != did);
!signed.is_empty()
});
self.whence.retain(|(_, d), _| d != did);
self.approved.remove(did);
}
crates/pds-server/src/ops.rs+4−2
@@ -693,11 +693,13 @@ const ROUTES: &[&str] = &[
const ASSETS: &str = "/oauth/assets/{name}";
/// A request's route, as its log line and metrics label it: the NSID of a
/// method served, `_health`, `_logs` or `_stats`, a path served outside
/// `/xrpc/`, or `_unknown`.
/// method served, `_health`, `_logs` or `_stats`, the account's OAuth
/// routes as `_oauthSessions`, a path served outside `/xrpc/`, or
/// `_unknown`.
fn route_of(path: &str) -> &'static str {
if let Some(own) = ["_health", "_logs", "_stats"]
.into_iter()
.chain(crate::oauth::account::Route::ALL.map(|r| r.name()))
.find(|r| path.strip_prefix("/xrpc/") == Some(*r))
{
return own;
docs/guide/calling.md+16−0
@@ -51,6 +51,22 @@ admin's reads of the log and the metrics, which have no lexicon
([COMMANDS.md](../../spec/COMMANDS.md#the-admins-reads),
[Operating](operating.md#reading-the-log-and-stats)).
An account's OAuth sessions, the apps it signed in to, and the browsers it
is signed in on, are listed and ended with its own password session, not
an app password or an OAuth token
([OAUTH-ACCOUNT.md](../../spec/OAUTH-ACCOUNT.md)), as the reference's
account pages do:
```sh
pds oauth sessions # each session's id, client, scope
pds oauth revoke-session --id <id> # sign that app out
pds oauth devices # each browser's id, user agent, IP
pds oauth revoke-device --id <id> # sign the account out of it
```
The same are the MCP tools `oauth_sessions`, `oauth_revoke_session`,
`oauth_devices` and `oauth_revoke_device`.
A few commands send or write bytes rather than JSON
([COMMANDS.md](../../spec/COMMANDS.md#answers)): `sync get-repo` and
`sync get-blob` write the CAR file or blob to standard output,
docs-site/astro.config.mjs+1−1
@@ -25,7 +25,7 @@ const AREAS = [
['Accounts and sessions', ['ACCOUNTS', 'SESSIONS', 'EMAIL', 'LIFECYCLE', 'MIGRATION']],
['Repository and sync', ['REPO', 'VALIDATION', 'SYNC', 'FEDERATION', 'IDENTITY', 'BLOBS', 'PROXY']],
['Spaces', ['SPACES', 'SPACES-REPO', 'SPACES-CREDENTIALS', 'SPACES-POLICIES', 'SPACES-EXPORT', 'SPACES-SYNC']],
['OAuth', ['OAUTH', 'OAUTH-SCOPES', 'OAUTH-CLIENTS', 'OAUTH-PAGES', 'OAUTH-PERMISSION-SETS', 'OAUTH-MCP']],
['OAuth', ['OAUTH', 'OAUTH-SCOPES', 'OAUTH-CLIENTS', 'OAUTH-PAGES', 'OAUTH-PERMISSION-SETS', 'OAUTH-MCP', 'OAUTH-ACCOUNT']],
['Running on the internet', ['DURABILITY', 'STORE', 'LIMITS', 'OPERATIONS']],
['Calling and comparing', ['COMMANDS', 'COMPAT']],
]
harness/checks/commands.mjs+80−19
harness/checks/crashes.mjs+3−0
harness/checks/lifecycle.mjs+14−0
harness/checks/limits.mjs+17−0
harness/checks/oauth-account.mjsnew+703−0
703 lines changed: not loaded until asked for.
harness/checks/oauth-mcp.mjs+18−0
harness/checks/operations.mjs+8−1
harness/lib/observe.mjs+4−3
harness/lib/via.mjs+66−10
harness/compare.mjs+3−1
spec/COMMANDS.md+51−8
spec/LIFECYCLE.md+2−0
spec/LIMITS.md+1−1
spec/OAUTH-ACCOUNT.mdnew+195−0
spec/OAUTH.md+4−2
spec/OPERATIONS.md+4−2
spec/PDS.md+5−3
README.md+4−2