~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
910 lines · 32.2 KB Raw History
//! OAuth access tokens on every method that takes a token, and what an OAuth
//! session's scope allows, as `spec/OAUTH-SCOPES.md` says.
//!
//! `METHODS` is the one table of what each method takes of a token and needs
//! of a scope. A call is checked against it in three places:
//!
//! - `look`, as an XRPC call arrives: for a method that reads a token, a
//!   `DPoP` call's token and proof (`oauth::access`), once the call is not
//!   refused for its HTTP method or a query's parameters. The call is then
//!   made with `Bearer::OAuth`, and its answer carries the nonce (`answered`).
//! - `admit`, before a method's input: the token a method that takes one
//!   optionally refuses, and what a method needs of a scope whatever its
//!   input (`updateHandle`'s handle, and no OAuth token on the app password
//!   methods).
//! - `records`, and `may` with a `Need::Blob`, once a write's input or an
//!   upload's media type says what the call needs.
//!
//! The permission engine is `Scope`, asked with a `Need`. A password
//! session, and an app password's, is allowed every need (whether an app
//! password's session may make a call is the method's to say); an OAuth
//! session what its scope allows, or `403 ScopeMissingError` naming the
//! scope that would allow it.
//!
//! Proxied calls (`spec/PROXY.md`): a call the server forwards, and the
//! methods it serves by asking another service, need `rpc` of the method
//! and the service it goes to (`Needs::Rpc`), asked where the method has
//! the service: `proxy::forward`, `proxy::scope`, `getServiceAuth`, and
//! `of_input` for `registerPush` and `unregisterPush`. A forwarded call's
//! token and proof are looked at once what is checked before them passes
//! (`proxy::forwards`).
//!
//! 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;
use axum::response::Response;
use pds_lexicon::Kind;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use serde_json::{Map, Value as Json};

#[cfg(test)]
mod tests;

/// What a method takes of a token.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Takes {
    /// None: its `Authorization` header, whatever its form, is not read.
    Nothing,
    /// `createAccount`: a `DPoP` call is `401 AuthenticationRequired`.
    CreateAccount,
    /// A token if one is given, checked after the parameters, which changes
    /// nothing of the answer.
    Optionally,
    /// An access token, and this of an OAuth session's scope.
    Needs(Needs),
    /// A refresh token, by the `Bearer` scheme alone.
    Refresh,
    /// 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,
}

/// What a method that needs a token needs of an OAuth session's scope.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Needs {
    /// Nothing more than its token.
    Nothing,
    /// An attribute of the account's identity: `identity:<attr>`, `*` the
    /// whole of it.
    Identity(&'static str),
    /// `blob` of the upload's media type.
    Blob,
    /// `repo` of the collections and actions its input names (`records`).
    Records,
    /// A password session or an app password's: never an OAuth token, `403 Forbidden`.
    Password,
    /// Never an OAuth token, `403 Forbidden` with this message.
    Never(&'static str),
    /// Managing this attribute of the account (`account:<attr>?action=manage`).
    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.
const METHODS: &[(&str, Takes)] = &[
    ("com.atproto.server.describeServer", Takes::Nothing),
    ("com.atproto.server.createSession", Takes::Nothing),
    ("com.atproto.identity.resolveHandle", Takes::Nothing),
    ("com.atproto.repo.getRecord", Takes::Nothing),
    ("com.atproto.repo.listRecords", Takes::Nothing),
    ("com.atproto.repo.describeRepo", Takes::Nothing),
    ("com.atproto.sync.listRepos", Takes::Nothing),
    ("com.atproto.sync.getRepoStatus", Takes::Nothing),
    ("com.atproto.server.createAccount", Takes::CreateAccount),
    ("com.atproto.sync.getRepo", Takes::Optionally),
    ("com.atproto.sync.getLatestCommit", Takes::Optionally),
    ("com.atproto.sync.getRecord", Takes::Optionally),
    ("com.atproto.sync.getBlocks", Takes::Optionally),
    ("com.atproto.sync.listBlobs", Takes::Optionally),
    ("com.atproto.sync.getBlob", Takes::Optionally),
    // It answers the email only if the scope allows reading it (`reads_email`).
    (
        "com.atproto.server.getSession",
        Takes::Needs(Needs::Nothing),
    ),
    (
        "com.atproto.identity.getRecommendedDidCredentials",
        Takes::Needs(Needs::Nothing),
    ),
    (
        "com.atproto.identity.updateHandle",
        Takes::Needs(Needs::Identity("handle")),
    ),
    ("com.atproto.repo.uploadBlob", Takes::Needs(Needs::Blob)),
    (
        "com.atproto.repo.createRecord",
        Takes::Needs(Needs::Records),
    ),
    ("com.atproto.repo.putRecord", Takes::Needs(Needs::Records)),
    (
        "com.atproto.repo.deleteRecord",
        Takes::Needs(Needs::Records),
    ),
    ("com.atproto.repo.applyWrites", Takes::Needs(Needs::Records)),
    (
        "com.atproto.server.createAppPassword",
        Takes::Needs(Needs::Password),
    ),
    (
        "com.atproto.server.listAppPasswords",
        Takes::Needs(Needs::Password),
    ),
    (
        "com.atproto.server.revokeAppPassword",
        Takes::Needs(Needs::Password),
    ),
    ("com.atproto.server.refreshSession", Takes::Refresh),
    ("com.atproto.server.deleteSession", Takes::Refresh),
    // The admin's `Basic` auth alone (`invites::admin`).
    ("com.atproto.server.createInviteCode", Takes::Nothing),
    ("com.atproto.server.createInviteCodes", Takes::Nothing),
    (
        "com.atproto.server.getAccountInviteCodes",
        Takes::Needs(Needs::Password),
    ),
    // spec/EMAIL.md: confirming the email needs it managed; changing it is the
    // account manager's alone; a password reset takes no token.
    (
        "com.atproto.server.requestEmailConfirmation",
        Takes::Needs(Needs::Manage("email")),
    ),
    (
        "com.atproto.server.confirmEmail",
        Takes::Needs(Needs::Manage("email")),
    ),
    (
        "com.atproto.server.requestEmailUpdate",
        Takes::Needs(Needs::Never(EMAIL_UPDATE)),
    ),
    (
        "com.atproto.server.updateEmail",
        Takes::Needs(Needs::Never(EMAIL_UPDATE)),
    ),
    ("com.atproto.server.requestPasswordReset", Takes::Nothing),
    ("com.atproto.server.resetPassword", Takes::Nothing),
    // spec/LIFECYCLE.md.
    (
        "com.atproto.server.checkAccountStatus",
        Takes::Needs(Needs::Nothing),
    ),
    (
        "com.atproto.server.deactivateAccount",
        Takes::Needs(Needs::Manage("status")),
    ),
    (
        "com.atproto.server.activateAccount",
        Takes::Needs(Needs::Never(REACTIVATION)),
    ),
    (
        "com.atproto.server.requestAccountDelete",
        Takes::Needs(Needs::Password),
    ),
    ("com.atproto.server.deleteAccount", Takes::Nothing),
    // The admin's `Basic` auth alone (`lifecycle::admin`).
    ("com.atproto.admin.updateSubjectStatus", Takes::Nothing),
    ("com.atproto.admin.getSubjectStatus", Takes::Nothing),
    // spec/MIGRATION.md.
    (
        "com.atproto.repo.importRepo",
        Takes::Needs(Needs::Manage("repo")),
    ),
    (
        "com.atproto.repo.listMissingBlobs",
        Takes::Needs(Needs::Nothing),
    ),
    (
        "com.atproto.identity.submitPlcOperation",
        Takes::Needs(Needs::Identity("*")),
    ),
    (
        "com.atproto.identity.requestPlcOperationSignature",
        Takes::Needs(Needs::Identity("*")),
    ),
    (
        "com.atproto.identity.signPlcOperation",
        Takes::Needs(Needs::Identity("*")),
    ),
    (
        "com.atproto.server.getServiceAuth",
        Takes::Needs(Needs::Rpc),
    ),
    ("app.bsky.actor.getPreferences", Takes::Needs(Needs::Rpc)),
    ("app.bsky.actor.putPreferences", Takes::Needs(Needs::Rpc)),
    ("app.bsky.actor.getProfile", Takes::Needs(Needs::Rpc)),
    ("app.bsky.actor.getProfiles", Takes::Needs(Needs::Rpc)),
    ("app.bsky.feed.getTimeline", Takes::Needs(Needs::Rpc)),
    ("app.bsky.feed.getAuthorFeed", Takes::Needs(Needs::Rpc)),
    ("app.bsky.feed.getActorLikes", Takes::Needs(Needs::Rpc)),
    ("app.bsky.feed.getPostThread", Takes::Needs(Needs::Rpc)),
    ("app.bsky.feed.getFeed", Takes::Needs(Needs::Rpc)),
    (
        "app.bsky.notification.registerPush",
        Takes::Needs(Needs::Rpc),
    ),
    (
        "app.bsky.notification.unregisterPush",
        Takes::Needs(Needs::Rpc),
    ),
    ("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::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::Needs(Needs::Space)),
];

/// `requestEmailUpdate`'s and `updateEmail`'s refusal of an OAuth token.
const EMAIL_UPDATE: &str =
    "Use the account manager interface to update email address associated with an account";
/// `activateAccount`'s refusal of an OAuth token.
const REACTIVATION: &str = "Account reactivation is not available with OAuth credentials. Sign in to your account management page to reactivate.";

/// What a method takes of a token; one not in `METHODS` none.
pub(crate) fn takes(nsid: &str) -> Takes {
    METHODS
        .iter()
        .find(|(n, _)| *n == nsid)
        .map_or(Takes::Nothing, |(_, t)| *t)
}

/// An OAuth session, as a call's token and proof showed it.
#[derive(Clone, Debug)]
pub(crate) struct Grant {
    pub did: String,
    pub scope: Scope,
}

/// Whether the `Authorization` header's first word is the `DPoP` scheme, in any case.
fn dpop_scheme(headers: &HeaderMap) -> bool {
    let h = headers
        .get(axum::http::header::AUTHORIZATION)
        .map(|v| v.as_bytes())
        .unwrap_or_default();
    h.split(|&b| b == b' ')
        .next()
        .is_some_and(|w| w.eq_ignore_ascii_case(b"dpop"))
}

/// A call as it arrives over XRPC. For a method that reads a token, a call
/// with the `DPoP` scheme has its token and proof checked, unless it is
/// refused before: for its HTTP method, or a query for its parameters; a
/// call the server forwards, for what `proxy::forwards` checks.
/// `Ok(Some)`: they passed, and the call is made with `Bearer::OAuth` of the
/// grant and its answer `answered`. `Ok(None)`: the call is answered as it
/// is, with no nonce. `Err`: the answer.
pub(crate) async fn look(
    svc: &crate::Shared,
    call: &Call<'_>,
    headers: &HeaderMap,
) -> Result<Option<Grant>, Box<Response>> {
    // `createAccount` answers a `DPoP` header that is not two words as any
    // header of a bad form, before it refuses OAuth credentials and before
    // its input.
    if matches!(call.bearer, Bearer::Malformed)
        && takes(call.nsid) == Takes::CreateAccount
        && dpop_scheme(headers)
    {
        return Err(Box::new(respond(crate::invalid_token(), None)));
    }
    let Bearer::DPoP(token) = call.bearer else {
        return Ok(None);
    };
    // `uploadBlob` is served by a route of its own, and has no handler.
    let served = match crate::proxy::served(svc, call.nsid) {
        Ok(None) if call.nsid == "com.atproto.repo.uploadBlob" => Ok(Some(call.nsid)),
        s => s,
    };
    match served {
        Ok(Some(nsid)) => match reads_token(nsid, call) {
            Ok(true) => {}
            Ok(false) => return Ok(None),
            Err(e) => return Err(Box::new(respond(Err(e), None))),
        },
        // A path the server does not serve pays its point first, before
        // anything is fetched for it (its `atproto-proxy` target) and its
        // token is looked at (`spec/LIMITS.md`, "When"); `answer` then does
        // not charge it again.
        Ok(None) => {
            if let Err(e) = crate::limits::charge(svc, call, None, None) {
                return Err(Box::new(respond(Err(e), call.charged.get())));
            }
            if !crate::proxy::forwards(svc, call).await {
                return Ok(None);
            }
        }
        Err(_) => return Ok(None),
    }
    match crate::oauth::access(
        svc,
        call.method,
        &format!("/xrpc/{}", call.nsid),
        headers,
        token,
    )
    .await
    {
        Ok(Ok(a)) => {
            crate::ops::verified(&a.did);
            Ok(Some(Grant {
                did: a.did,
                scope: Scope::of(&a.scope),
            }))
        }
        Ok(Err((error, why))) => {
            let mut r = respond(err(401, error, why.as_str()), call.charged.get());
            crate::oauth::dpop_headers(svc, &mut r, Some((error, &why)));
            Err(Box::new(r))
        }
        Err(e) => Err(Box::new(respond(Err(e), None))),
    }
}

/// Of a served method, whether a call with an OAuth access token has the
/// token looked at: not for its HTTP method, a query's parameters that do
/// not parse, or a method that reads no OAuth token, which answers it as it
/// answers any; `createAccount` refuses it.
fn reads_token(nsid: &str, call: &Call) -> Result<bool, XrpcError> {
    let Ok(m) = crate::method_named(nsid, call.method) else {
        return Ok(false);
    };
    match takes(nsid) {
        Takes::Nothing | Takes::Refresh | Takes::Space => Ok(false),
        Takes::CreateAccount => err(
            401,
            "AuthenticationRequired",
            "OAuth credentials are not supported for this endpoint",
        ),
        Takes::Optionally | Takes::Needs(_) => Ok(m.kind != Kind::Query
            || m.parse_params(call.params.iter().map(|(k, v)| (k.as_str(), v.as_str())))
                .is_ok()),
    }
}

/// A tool call at the MCP endpoint with an MCP session's access token that
/// works (`spec/OAUTH-MCP.md`, "Tokens at the MCP endpoint"), as `look`
/// takes an OAuth access token over XRPC: `Ok(Some)`, the call is made with
/// `Bearer::OAuth` of the grant; `Ok(None)`, its method reads no OAuth
/// token, and is called as with one it has not looked at; `Err`, its
/// method's refusal of one.
pub(crate) fn look_mcp(
    svc: &Service,
    call: &Call<'_>,
    access: crate::oauth::Access,
) -> Result<Option<Grant>, XrpcError> {
    let Ok(Some(nsid)) = crate::proxy::served(svc, call.nsid) else {
        return Ok(None);
    };
    if !reads_token(nsid, call)? {
        return Ok(None);
    }
    crate::ops::verified(&access.did);
    Ok(Some(Grant {
        did: access.did,
        scope: Scope::of(&access.scope),
    }))
}

/// The answer to a call `look` passed, with its nonce.
pub(crate) fn answered(svc: &Service, grant: Option<&Grant>, mut r: Response) -> Response {
    if grant.is_some() {
        crate::oauth::dpop_headers(svc, &mut r, None);
    }
    r
}

/// What a call needs before its input: of a method that needs a token, what
/// it needs of an OAuth scope whatever its input. For a query, after its
/// parameters. A method that takes a token optionally has its token checked
/// by the lifecycle's gate, which reads who reads the repository
/// (`lifecycle::gate_query`).
pub(crate) fn admit(call: &Call) -> Result<(), XrpcError> {
    match (takes(call.nsid), call.bearer) {
        (Takes::Needs(Needs::Password), Bearer::OAuth(_)) => err(
            403,
            "Forbidden",
            "OAuth credentials are not supported for this endpoint",
        ),
        (Takes::Needs(Needs::Never(why)), Bearer::OAuth(_)) => err(403, "Forbidden", why),
        (Takes::Needs(Needs::Identity(attr)), b) => may(b, &Need::Identity(attr)),
        (Takes::Needs(Needs::Manage(attr)), b) => may(b, &Need::Account { attr, manage: true }),
        _ => Ok(()),
    }
}

/// Whether a call's session may make what it asks.
pub(crate) fn may(bearer: Bearer, need: &Need) -> Result<(), XrpcError> {
    match bearer {
        Bearer::OAuth(g) => g.scope.may(need),
        _ => Ok(()),
    }
}

/// 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 {
        Bearer::OAuth(g) => g.scope.allows(&Need::Account {
            attr: "email",
            manage: false,
        }),
        _ => true,
    }
}

/// What a repository write needs of a scope, once its input and `repo` are
/// checked: for each collection, in the order first named, `create` of
/// those its creates name, then `update` of its updates', then `delete` of
/// its deletes'. `putRecord` creates, then updates, whether or not the
/// record exists.
pub(crate) fn records(
    bearer: Bearer,
    nsid: &str,
    input: &Map<String, Json>,
) -> Result<(), XrpcError> {
    let Bearer::OAuth(g) = bearer else {
        return Ok(());
    };
    record_needs(nsid, input)
        .iter()
        .try_for_each(|n| g.scope.may(n))
}

/// The scopes a repository write's input needs that a session of `granted`
/// does not allow, each once, in the order `records` asks them: what a
/// step-up asks for all at once (`spec/OAUTH-MCP.md`).
pub(crate) fn missing_for_records(
    nsid: &str,
    input: &Map<String, Json>,
    granted: &[String],
) -> Vec<String> {
    let scope = Scope::of(granted);
    let mut out: Vec<String> = Vec::new();
    for n in record_needs(nsid, input)
        .iter()
        .filter(|n| !scope.allows(n))
    {
        let s = n.scope();
        if !out.contains(&s) {
            out.push(s);
        }
    }
    out
}

/// What a procedure that takes a token needs of a scope once its input is
/// checked, as the reference asks it in the method: `registerPush` and
/// `unregisterPush`, `rpc` of the method to the notification service its
/// `serviceDid` names, as `<serviceDid>#bsky_notif`.
pub(crate) fn of_input(
    bearer: Bearer,
    nsid: &str,
    input: &Map<String, Json>,
) -> Result<(), XrpcError> {
    let Bearer::OAuth(g) = bearer else {
        return Ok(());
    };
    match nsid {
        "app.bsky.notification.registerPush" | "app.bsky.notification.unregisterPush" => {
            let aud = format!(
                "{}#bsky_notif",
                input
                    .get("serviceDid")
                    .and_then(Json::as_str)
                    .unwrap_or_default()
            );
            g.scope.may(&Need::Rpc {
                lxm: nsid,
                aud: &aud,
            })
        }
        _ => Ok(()),
    }
}

fn record_needs<'a>(nsid: &str, input: &'a Map<String, Json>) -> Vec<Need<'a>> {
    fn text<'a>(m: &'a Map<String, Json>, k: &str) -> &'a str {
        m.get(k).and_then(Json::as_str).unwrap_or_default()
    }
    let repo = |collection, action| Need::Repo { collection, action };
    let collection = text(input, "collection");
    match nsid {
        "com.atproto.repo.createRecord" => vec![repo(collection, Action::Create)],
        "com.atproto.repo.putRecord" => vec![
            repo(collection, Action::Create),
            repo(collection, Action::Update),
        ],
        "com.atproto.repo.deleteRecord" => vec![repo(collection, Action::Delete)],
        "com.atproto.repo.applyWrites" => {
            let writes: Vec<&Map<String, Json>> = input
                .get("writes")
                .and_then(Json::as_array)
                .into_iter()
                .flatten()
                .filter_map(Json::as_object)
                .collect();
            let mut needs = Vec::new();
            for action in [Action::Create, Action::Update, Action::Delete] {
                for w in writes.iter().filter(|w| {
                    text(w, "$type").strip_prefix("com.atproto.repo.applyWrites#")
                        == Some(action.name())
                }) {
                    let need = repo(text(w, "collection"), action);
                    if !needs.contains(&need) {
                        needs.push(need);
                    }
                }
            }
            needs
        }
        _ => Vec::new(),
    }
}

// ---- The permission engine ----------------------------------------------------

/// A repository write's action.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Action {
    Create,
    Update,
    Delete,
}

impl Action {
    fn name(self) -> &'static str {
        match self {
            Action::Create => "create",
            Action::Update => "update",
            Action::Delete => "delete",
        }
    }
}

/// What a call asks of a scope (`atproto/permission.md`'s resources).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Need<'a> {
    /// A write of `action` to `collection`.
    Repo { collection: &'a str, action: Action },
    /// An upload of this media type, as given.
    Blob(&'a str),
    /// An attribute of the account's identity: `handle`.
    Identity(&'a str),
    /// Reading, or with `manage` managing, an attribute of the account: `email`, `repo` or `status`.
    Account { attr: &'a str, manage: bool },
    /// 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.
const NAMED: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'_')
    .remove(b'.')
    .remove(b'!')
    .remove(b'~')
    .remove(b'*')
    .remove(b'\'')
    .remove(b'(')
    .remove(b')')
    .remove(b':')
    .remove(b'/')
    .remove(b'+')
    .remove(b',')
    .remove(b'@')
    .remove(b'%');

impl Need<'_> {
    /// The scope that would allow it, as a refusal names it.
    pub fn scope(&self) -> String {
        let encode = |s: &str| utf8_percent_encode(s, NAMED).to_string();
        match *self {
            Need::Repo { collection, action } => {
                format!("repo:{collection}?action={}", action.name())
            }
            Need::Blob(m) => format!("blob:{}", encode(&m.to_lowercase())),
            Need::Identity(attr) => format!("identity:{attr}"),
            Need::Account { attr, manage } => format!(
                "account:{attr}?action={}",
                if manage { "manage" } else { "read" }
            ),
            // 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(),
        }
    }
}

/// A permission of a scope, its parameters as given, percent-decoded.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Permission {
    /// Every action if `actions` is empty.
    Repo {
        collections: Vec<String>,
        actions: Vec<String>,
    },
    Rpc {
        lxm: Vec<String>,
        aud: String,
    },
    Blob {
        accept: Vec<String>,
    },
    Account {
        attr: String,
        manage: bool,
    },
    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)),
            None => (head, None),
        };
        let first = match resource {
            "repo" => "collection",
            "rpc" => "lxm",
            "blob" => "accept",
            "account" | "identity" => "attr",
            _ => return None,
        };
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(p) = positional {
            params.push((
                first.to_string(),
                percent_decode_str(p).decode_utf8().ok()?.into_owned(),
            ));
        }
        params.extend(
            url::form_urlencoded::parse(query.as_bytes())
                .map(|(k, v)| (k.into_owned(), v.into_owned())),
        );
        let all = |name: &str| {
            params
                .iter()
                .filter(|(k, _)| k == name)
                .map(|(_, v)| v.clone())
                .collect::<Vec<_>>()
        };
        let one = |name: &str| {
            params
                .iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.clone())
        };
        Some(match resource {
            "repo" => Permission::Repo {
                collections: all("collection"),
                actions: all("action"),
            },
            "rpc" => Permission::Rpc {
                lxm: all("lxm"),
                aud: one("aud")?,
            },
            "blob" => Permission::Blob {
                accept: all("accept"),
            },
            "account" => Permission::Account {
                attr: one("attr")?,
                manage: one("action").as_deref() == Some("manage"),
            },
            _ => Permission::Identity { attr: one("attr")? },
        })
    }

    fn allows(&self, need: &Need) -> bool {
        match (self, *need) {
            (
                Permission::Repo {
                    collections,
                    actions,
                },
                Need::Repo { collection, action },
            ) => {
                (actions.is_empty() || actions.iter().any(|a| a == action.name()))
                    && collections.iter().any(|c| c == "*" || c == collection)
            }
            (Permission::Blob { accept }, Need::Blob(m)) => {
                media_type(m) && accept.iter().any(|a| accepts(a, m))
            }
            (Permission::Identity { attr }, Need::Identity(want)) => attr == "*" || attr == want,
            (
                Permission::Account { attr, manage },
                Need::Account {
                    attr: want,
                    manage: managing,
                },
            ) => attr == want && (*manage || !managing),
            (
                Permission::Rpc { lxm, aud },
                Need::Rpc {
                    lxm: method,
                    aud: service,
                },
            ) => lxm.iter().any(|l| l == "*" || l == method) && (aud == "*" || aud == service),
            (Permission::Space(p), Need::Space(n)) => p.allows(&n),
            _ => false,
        }
    }
}

/// Whether `m` is a media type a `blob` permission may allow: a type and a
/// subtype, one `/` between them, with no space and no `*`.
fn media_type(m: &str) -> bool {
    m.split_once('/')
        .is_some_and(|(t, s)| !t.is_empty() && !s.is_empty() && !s.contains('/'))
        && !m.contains([' ', '*'])
}

/// Whether a `blob` permission's `accept` value takes the media type `m`.
fn accepts(accept: &str, m: &str) -> bool {
    accept == "*/*"
        || accept == m
        || accept
            .strip_suffix("/*")
            .is_some_and(|t| m.strip_prefix(t).is_some_and(|rest| rest.starts_with('/')))
}

/// An OAuth session's scope, and what it allows.
#[derive(Clone, Debug, Default)]
pub(crate) struct Scope {
    /// Its tokens, separated by spaces.
    text: String,
    generic: bool,
    email: bool,
    chat: bool,
    permissions: Vec<Permission>,
}

impl Scope {
    /// The scope of these tokens. `atproto` alone allows nothing more than
    /// a token; `include:` and anything else not a permission, nothing.
    pub fn of(tokens: &[String]) -> Scope {
        let has = |t: &str| tokens.iter().any(|k| k == t);
        Scope {
            text: tokens.join(" "),
            generic: has("transition:generic"),
            email: has("transition:email"),
            chat: has("transition:chat.bsky"),
            permissions: tokens.iter().filter_map(|t| Permission::of(t)).collect(),
        }
    }

    pub fn text(&self) -> &str {
        &self.text
    }

    /// Whether it allows `need`. `transition:generic` allows every `repo` and
    /// `blob` need, and calls of any method but `chat.bsky`'s (`*` too; the
    /// prefix in any case); `transition:chat.bsky` alone allows calls of
    /// `chat.bsky`'s, to any service; `transition:email` allows reading the
    /// email.
    pub fn allows(&self, need: &Need) -> bool {
        let transitional = match *need {
            Need::Repo { .. } | Need::Blob(_) => self.generic,
            Need::Account { attr, manage } => self.email && attr == "email" && !manage,
            Need::Rpc { lxm, .. }
                if lxm
                    .get(..10)
                    .is_some_and(|p| p.eq_ignore_ascii_case("chat.bsky.")) =>
            {
                self.chat
            }
            Need::Rpc { .. } => self.generic,
            Need::Identity(_) | Need::Space(_) => false,
        };
        transitional || self.permissions.iter().any(|p| p.allows(need))
    }

    /// `need`, or the refusal naming the scope that would allow it.
    pub fn may(&self, need: &Need) -> Result<(), XrpcError> {
        if self.allows(need) {
            return Ok(());
        }
        err(
            403,
            "ScopeMissingError",
            format!("Missing required scope \"{}\"", need.scope()),
        )
    }
}