~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
447 lines · 17.0 KB Raw History
//! The account's own routes (`spec/OAUTH-ACCOUNT.md`, `spec/PASSKEYS.md`):
//! `GET /xrpc/_oauthSessions`, `POST /xrpc/_oauthRevokeSession`, `GET
//! /xrpc/_oauthDevices` and `POST /xrpc/_oauthRevokeDevice` for its OAuth
//! sessions and devices, and `GET /xrpc/_passkeyList`, `POST
//! /xrpc/_passkeyAdd` and `POST /xrpc/_passkeyRemove` for its passkeys
//! (`super::passkeys`), of no lexicon. Each is answered by `answer`, over
//! XRPC (`xrpc`) and as its MCP tool (`spec/COMMANDS.md`, "The account's
//! OAuth sessions" and "The account's passkeys"): the token
//! `getAccountInviteCodes` takes first, then the HTTP method, then
//! `_passkeyAdd`'s account's state, then a `POST`'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. A passkey is named by its credential ID.

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 own routes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Route {
    Sessions,
    RevokeSession,
    Devices,
    RevokeDevice,
    PasskeyList,
    PasskeyAdd,
    PasskeyRemove,
}

impl Route {
    /// Each, in the order `spec/COMMANDS.md` lists them.
    pub const ALL: [Route; 7] = [
        Route::Sessions,
        Route::RevokeSession,
        Route::Devices,
        Route::RevokeDevice,
        Route::PasskeyList,
        Route::PasskeyAdd,
        Route::PasskeyRemove,
    ];

    /// 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",
            Route::PasskeyList => "_passkeyList",
            Route::PasskeyAdd => "_passkeyAdd",
            Route::PasskeyRemove => "_passkeyRemove",
        }
    }

    /// Its group of commands.
    fn group(self) -> &'static str {
        match self {
            Route::PasskeyList | Route::PasskeyAdd | Route::PasskeyRemove => "passkey",
            _ => "oauth",
        }
    }

    /// 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",
            Route::PasskeyList => "passkey_list",
            Route::PasskeyAdd => "passkey_add",
            Route::PasskeyRemove => "passkey_remove",
        }
    }

    /// 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 change `POST`.
    pub fn method(self) -> Method {
        match self {
            Route::Sessions | Route::Devices | Route::PasskeyList => Method::GET,
            _ => Method::POST,
        }
    }

    /// The member of a `POST`'s body it takes, as its tool's argument.
    fn argument(self) -> &'static str {
        match self {
            Route::PasskeyAdd => "name",
            _ => "id",
        }
    }

    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."
            }
            Route::PasskeyList => {
                "The passkeys of your account, newest first: each with its id, name, when it was added and last signed in, and whether it is backed up. Needs your account's password session."
            }
            Route::PasskeyAdd => {
                "A link to open in a browser within 15 minutes, which adds a passkey of this name to your account: it then signs in on the OAuth sign-in page with no password. A new link ends the last. Needs your account's password session."
            }
            Route::PasskeyRemove => {
                "Remove one of your account's passkeys by its id, as passkey_list lists it: it no longer signs in. Needs your account's password session."
            }
        }
    }

    /// Their MCP tools, in order, as `spec/COMMANDS.md`, "The account's
    /// OAuth sessions" and "The account's passkeys", give 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 {
                let arg = r.argument();
                let mut property = json!({ "type": "string" });
                if r == Route::PasskeyAdd {
                    property["minLength"] = json!(1);
                    property["maxLength"] = json!(64);
                }
                (
                    json!({
                        "type": "object",
                        "properties": { arg: property },
                        "required": [arg],
                    }),
                    json!({ "readOnlyHint": false, "destructiveHint": r != Route::PasskeyAdd }),
                )
            };
            // Its command's name, as `revoke-session` of `oauth_revoke_session`.
            let command = r.tool()[r.group().len() + 1..].replace('_', "-");
            json!({
                "name": r.tool(),
                "title": pds_lexicon::title(r.group(), &command),
                "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
/// `_passkeyAdd`'s account's state (`spec/LIFECYCLE.md`, "Its own calls"),
/// then a `POST`'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
        ));
    }
    if route == Route::PasskeyAdd {
        crate::lifecycle::gate(svc, route.name(), &did)?;
    }
    let arg = if want == Method::POST {
        Some(argument_of(call, route)?)
    } else {
        None
    };
    limits::charge(svc, call, None, None)?;
    crate::ops::spawn(act(svc.clone(), route, did, arg))
        .await
        .unwrap_or_else(|_| internal())
}

/// A `POST`'s argument, from its body: at most `limits::MAX_BODY` bytes,
/// else `413`; then `application/json`, an object with `id` a string, or
/// `_passkeyAdd`'s `name` one of 1 to 64 characters, its other properties
/// ignored.
fn argument_of(call: &Call, route: Route) -> 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");
    };
    let name = route.argument();
    match b.get(name) {
        Some(Json::String(s)) if route != Route::PasskeyAdd => Ok(s.clone()),
        Some(Json::String(s)) => match s.chars().count() {
            0 => invalid("Input/name must not be shorter than 1 characters"),
            65.. => invalid("Input/name must not be longer than 64 characters"),
            _ => Ok(s.clone()),
        },
        Some(_) => invalid(format!("Input/{name} must be a string")),
        None => invalid(format!("Input must have the property \"{name}\"")),
    }
}

/// What a route does for account `did`, with its argument, answered once
/// what it shows, or the change it logged, is on disk.
async fn act(
    svc: Shared,
    route: Route,
    did: String,
    arg: Option<String>,
) -> Result<Json, XrpcError> {
    let id = arg.unwrap_or_default();
    let mut tx = Tx::new(&svc);
    let out = tx.change(|st, now| match route {
        Route::Sessions => (
            vec![],
            Ok(json!({ "sessions": sessions(&svc, st, &did, now) })),
        ),
        Route::Devices => (
            vec![],
            Ok(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(),
            Ok(json!({})),
        ),
        Route::RevokeDevice => (
            device_named(&svc, st, &did, &id)
                .map(|device| json!({ "t": "oauthSignOut", "device": device, "did": did }))
                .into_iter()
                .collect(),
            Ok(json!({})),
        ),
        Route::PasskeyList | Route::PasskeyAdd | Route::PasskeyRemove => {
            super::passkeys::act(&svc, st, route, &did, &id)
        }
    });
    if tx.done().await { 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()),
    }
}