~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
315 lines · 9.3 KB Raw History
//! Scope strings (RFC 6749 §3.3) and the scopes the server keeps of them:
//! atproto's own, the permissions of `atproto/permission.md` that parse,
//! and the `include:` scopes that parse (`super::sets`), as `spec/OAUTH.md`
//! says.

use pds_repo::data::{valid_did, valid_nsid, valid_rkey};
use std::collections::HashMap;

/// The scopes the server knows besides permissions.
const KNOWN: &[&str] = &[
    "atproto",
    "transition:email",
    "transition:generic",
    "transition:chat.bsky",
];

/// Whether `s` is a scope string: tokens of printable ASCII but `"` and `\`,
/// separated by single spaces.
pub(crate) fn valid(s: &str) -> bool {
    !s.is_empty()
        && s.split(' ').all(|t| {
            !t.is_empty()
                && t.bytes()
                    .all(|b| b == 0x21 || (0x23..=0x5b).contains(&b) || (0x5d..=0x7e).contains(&b))
        })
}

/// A scope string's tokens.
pub(crate) fn tokens(s: &str) -> Vec<&str> {
    s.split(' ').filter(|t| !t.is_empty()).collect()
}

/// Of a request's scope tokens, those the server keeps: each once, in the
/// order first given.
pub(crate) fn kept(tokens: &[&str]) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for t in tokens {
        if (KNOWN.contains(t) || permission(t) || super::sets::include(t).is_some())
            && !out.iter().any(|o| o == t)
        {
            out.push(t.to_string());
        }
    }
    out
}

/// A parameter a resource takes: its name, whether it takes more than one
/// value, whether it is required, and the values it allows.
pub(crate) struct Param {
    pub name: &'static str,
    pub many: bool,
    pub required: bool,
    pub allows: fn(&str) -> bool,
}

fn nsid_or_any(v: &str) -> bool {
    v == "*" || valid_nsid(v)
}

fn audience(v: &str) -> bool {
    v == "*"
        || v.split_once('#')
            .is_some_and(|(did, service)| valid_did(did) && !service.is_empty())
}

fn mime(v: &str) -> bool {
    let token = |t: &str| {
        !t.is_empty()
            && t.bytes()
                .all(|b| b.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&b))
    };
    match v.split_once('/') {
        Some(("*", "*")) => true,
        Some((t, "*")) => token(t),
        Some((t, s)) => token(t) && token(s),
        None => false,
    }
}

/// The parameters each resource takes, the positional one first.
pub(crate) fn params(resource: &str) -> Option<&'static [Param]> {
    const REPO: &[Param] = &[
        Param {
            name: "collection",
            many: true,
            required: true,
            allows: nsid_or_any,
        },
        Param {
            name: "action",
            many: true,
            required: false,
            allows: |v| ["create", "update", "delete"].contains(&v),
        },
    ];
    const RPC: &[Param] = &[
        Param {
            name: "lxm",
            many: true,
            required: true,
            allows: nsid_or_any,
        },
        Param {
            name: "aud",
            many: false,
            required: true,
            allows: audience,
        },
    ];
    const BLOB: &[Param] = &[Param {
        name: "accept",
        many: true,
        required: true,
        allows: mime,
    }];
    const ACCOUNT: &[Param] = &[
        Param {
            name: "attr",
            many: false,
            required: true,
            allows: |v| ["email", "repo", "status"].contains(&v),
        },
        Param {
            name: "action",
            many: false,
            required: false,
            allows: |v| ["read", "manage"].contains(&v),
        },
    ];
    const IDENTITY: &[Param] = &[Param {
        name: "attr",
        many: false,
        required: true,
        allows: |v| ["handle", "*"].contains(&v),
    }];
    // `spec/OAUTH-SCOPES.md`, "Spaces".
    const SPACE: &[Param] = &[
        Param {
            name: "spaceType",
            many: false,
            required: true,
            allows: nsid_or_any,
        },
        Param {
            name: "authority",
            many: false,
            required: false,
            allows: |v| v == "*" || v == "self" || valid_did(v),
        },
        Param {
            name: "skey",
            many: false,
            required: false,
            allows: |v| v == "*" || valid_rkey(v),
        },
        Param {
            name: "collection",
            many: true,
            required: false,
            allows: nsid_or_any,
        },
        Param {
            name: "action",
            many: true,
            required: false,
            allows: |v| ["read_self", "read", "create", "update", "delete"].contains(&v),
        },
        Param {
            name: "manage",
            many: true,
            required: false,
            allows: |v| ["create", "update", "delete"].contains(&v),
        },
    ];
    Some(match resource {
        "repo" => REPO,
        "rpc" => RPC,
        "blob" => BLOB,
        "account" => ACCOUNT,
        "identity" => IDENTITY,
        "space" => SPACE,
        _ => return None,
    })
}

/// Whether `s` is a permission that parses: a resource the server knows,
/// each parameter one it takes, in one place, with a value it allows, and
/// every required one there.
pub(crate) fn permission(s: &str) -> bool {
    let (head, query) = match s.split_once('?') {
        Some((h, q)) => (h, Some(q)),
        None => (s, None),
    };
    let (resource, positional) = match head.split_once(':') {
        Some((r, p)) => (r, Some(p)),
        None => (head, None),
    };
    let Some(takes) = params(resource) else {
        return false;
    };
    let mut given: HashMap<&str, Vec<String>> = HashMap::new();
    if let Some(p) = positional {
        let Ok(p) = percent_encoding::percent_decode_str(p).decode_utf8() else {
            return false;
        };
        given.entry(takes[0].name).or_default().push(p.into_owned());
    }
    for (k, v) in url::form_urlencoded::parse(query.unwrap_or_default().as_bytes()) {
        let Some(param) = takes.iter().find(|p| p.name == k) else {
            return false;
        };
        if positional.is_some() && param.name == takes[0].name {
            return false;
        }
        given.entry(param.name).or_default().push(v.into_owned());
    }
    for p in takes {
        let right = match given.get(p.name) {
            None => !p.required,
            Some(vs) => (p.many || vs.len() == 1) && vs.iter().all(|v| (p.allows)(v)),
        };
        if !right {
            return false;
        }
    }
    let every = |k: &str| given.get(k).is_some_and(|vs| vs.iter().all(|v| v == "*"));
    !(resource == "rpc" && every("lxm") && every("aud"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scope_strings() {
        assert!(valid("atproto") && valid("atproto transition:generic") && valid("a!#[]~"));
        for bad in [
            "",
            " atproto",
            "atproto ",
            "atproto  x",
            "a\"b",
            "a\\b",
            "a\tb",
            "é",
        ] {
            assert!(!valid(bad), "{bad:?}");
        }
    }

    #[test]
    fn permissions_that_parse() {
        for ok in [
            "repo:*",
            "repo:com.example.foo?action=create",
            "repo?collection=a.b.c&collection=d.e.f&action=create&action=delete",
            "rpc:app.bsky.feed.getTimeline?aud=*",
            "rpc:*?aud=did:web:api.bsky.app%23bsky_appview",
            "blob:image/*",
            "blob:*/*",
            "blob?accept=image/png&accept=video/*",
            "account:email?action=manage",
            "account:repo",
            "identity:*",
            "identity:handle",
            "space:com.example.forum",
            "space:*?authority=*&action=read",
            "space?spaceType=com.example.forum&manage=create",
            "space:com.example.forum?authority=did:plc:abc&skey=main&collection=com.example.post&action=create",
            "space:com.example.forum?authority=self&skey=*&collection=*&action=read_self&manage=update&manage=delete",
        ] {
            assert!(permission(ok), "{ok}");
        }
        for bad in [
            "repo",
            "repo:com.example.*",
            "repo:a.b.c?collection=d.e.f",
            "repo:*?action=read",
            "repo:*?other=1",
            "rpc:app.bsky.feed.getTimeline",
            "rpc:*?aud=*",
            "rpc:a.b.c?aud=did:web:x",
            "rpc:a.b.c?aud=*&aud=*",
            "blob:*/png",
            "blob:image",
            "account:*",
            "account:email?action=read&action=manage",
            "identity:other",
            "transition:other",
            "foo:bar",
            "space",
            "space:forum",
            "space:com.example.forum?authority=me",
            "space:com.example.forum?action=write",
            "space:com.example.forum?manage=read",
            "space:com.example.forum?spaceType=com.example.forum",
            "space:com.example.forum?authority=*&authority=self",
            "space:com.example.forum?skey=a/b",
            "space:com.example.forum?collection=com.example.*",
            "space:com.example.forum?other=1",
        ] {
            assert!(!permission(bad), "{bad}");
        }
        assert_eq!(
            kept(&[
                "atproto",
                "foo:bar",
                "repo:*",
                "atproto",
                "transition:email"
            ]),
            ["atproto", "repo:*", "transition:email"]
        );
    }
}