~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
541 lines · 17.8 KB Raw History
//! A discoverable client's ID and document, checked as
//! `spec/OAUTH-CLIENTS.md` says under "Client IDs" and "What it must say":
//! each field's type, then the checks in the page's order, the first that
//! fails refusing the document.

use super::super::{RESPONSE_TYPES, client, scope};
use super::{Failure, assertion};
use serde_json::{Map, Value as Json};
use std::net::{Ipv4Addr, Ipv6Addr};
use url::{Host, Url};

const META: &str = "invalid_client_metadata";
/// A document failing a numbered check: `invalid_client_metadata`, or for
/// some redirect URIs `invalid_redirect_uri`.
const REFUSED: Failure = Failure::Check(META);
const REDIRECT: Failure = Failure::Check("invalid_redirect_uri");

const GRANT_TYPES: &[&str] = &[
    "authorization_code",
    "implicit",
    "refresh_token",
    "password",
    "client_credentials",
    "urn:ietf:params:oauth:grant-type:jwt-bearer",
    "urn:ietf:params:oauth:grant-type:saml2-bearer",
];
const AUTH_METHODS: &[&str] = &[
    "client_secret_basic",
    "client_secret_jwt",
    "client_secret_post",
    "none",
    "private_key_jwt",
    "self_signed_tls_client_auth",
    "tls_client_auth",
];

/// A domain name no client on the internet can own: fewer than two labels,
/// or a last label of `test`, `local`, `localhost`, `invalid` or `example`.
pub(super) fn local_name(host: &str) -> bool {
    let labels: Vec<&str> = host.split('.').collect();
    let last = labels.last().copied().unwrap_or_default();
    labels.len() < 2
        || ["test", "local", "localhost", "invalid", "example"]
            .iter()
            .any(|l| last.eq_ignore_ascii_case(l))
}

/// A host name as an https client ID or redirect URI may have: not
/// `localhost`, at least two labels, not ending in `.local`.
fn domain_ok(d: &str) -> bool {
    let labels: Vec<&str> = d.split('.').collect();
    !d.eq_ignore_ascii_case("localhost")
        && labels.len() >= 2
        && labels.iter().all(|l| !l.is_empty())
        && !d.to_ascii_lowercase().ends_with(".local")
}

/// A discoverable client's ID, parsed, or the error that refuses it.
pub(super) fn client_id(id: &str) -> Result<Url, &'static str> {
    let after = id.strip_prefix("https://").ok_or(META)?;
    if id.contains('#') {
        return Err(META);
    }
    let u = Url::parse(id).map_err(|_| META)?;
    if !u.username().is_empty() || u.password().is_some() {
        return Err(META);
    }
    let authority = &after[..after.find(['/', '?', '\\']).unwrap_or(after.len())];
    let rest = &after[authority.len()..];
    let raw_path = &rest[..rest.find('?').unwrap_or(rest.len())];
    if raw_path != u.path() || u.path() == "/" || u.path().ends_with('/') {
        return Err(META);
    }
    let Some(Host::Domain(host)) = u.host() else {
        return Err(META);
    };
    if !domain_ok(host) || authority.contains(':') || u.port().is_some() {
        return Err(META);
    }
    if local_name(host) {
        return Err("invalid_client_id");
    }
    Ok(u)
}

/// A redirect URI's form.
pub(super) enum Form {
    Https(Url),
    Loopback(Url),
    /// Its scheme.
    PrivateUse(String),
}

/// An https URL whose host is not `localhost`, `127.0.0.1` or `[::1]`, and,
/// if a domain name, has at least two labels and does not end in `.local`.
fn https_url(uri: &str) -> Option<Url> {
    if !uri.starts_with("https://") {
        return None;
    }
    let u = Url::parse(uri).ok()?;
    let ok = match u.host()? {
        Host::Domain(d) => domain_ok(d),
        Host::Ipv4(a) => a != Ipv4Addr::LOCALHOST,
        Host::Ipv6(a) => a != Ipv6Addr::LOCALHOST,
    };
    ok.then_some(u)
}

pub(super) fn form(uri: &str) -> Option<Form> {
    if let Some(u) = https_url(uri) {
        return Some(Form::Https(u));
    }
    if uri.starts_with("http://") {
        return Url::parse(uri)
            .ok()
            .filter(client::loopback)
            .map(Form::Loopback);
    }
    // A private-use URI: `<label>.<label>…:/path`, its scheme backwards not a local name.
    let (scheme, rest) = uri.split_once(':')?;
    let labels: Vec<&str> = scheme.split('.').collect();
    let label = |l: &&str| {
        l.bytes().next().is_some_and(|b| b.is_ascii_alphabetic())
            && l.bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'+')
    };
    let backwards: Vec<&str> = labels.iter().rev().copied().collect();
    let ok = labels.len() >= 2
        && labels.iter().all(label)
        && rest.starts_with('/')
        && !rest.starts_with("//")
        && Url::parse(uri).is_ok()
        && !local_name(&backwards.join("."));
    ok.then(|| Form::PrivateUse(scheme.to_string()))
}

/// Whether `s` is an email address: something, `@`, and a domain name.
fn email(s: &str) -> bool {
    s.split_once('@').is_some_and(|(local, domain)| {
        !local.is_empty()
            && !s.contains(char::is_whitespace)
            && !domain.contains('@')
            && domain.split('.').count() >= 2
            && domain.split('.').all(|l| !l.is_empty())
    })
}

/// A document the server took: what the server uses of it, and what the page shows.
#[derive(Debug)]
pub(super) struct Taken {
    pub scope: String,
    pub redirect_uris: Vec<String>,
    pub refresh: bool,
    pub confidential: bool,
    /// The client keys of its `jwks`, if it has one.
    pub jwks: Option<Vec<Map<String, Json>>>,
    pub jwks_uri: Option<Url>,
    /// The document as taken: the known fields, with their defaults.
    pub shown: Json,
}

/// Check the document fetched for client `id` (parsed as `url`): a field
/// not of its type, or no `redirect_uris`, makes it unusable; a numbered
/// check failing refuses it with that check's error.
pub(super) fn check(id: &str, url: &Url, doc: &Map<String, Json>) -> Result<Taken, Failure> {
    // Each field of its type; the page shows those known, with defaults.
    let mut shown = Map::new();
    let mut field = |k: &str,
                     valid: &dyn Fn(&Json) -> bool,
                     default: Option<Json>|
     -> Result<Option<Json>, Failure> {
        match doc.get(k) {
            Some(v) if valid(v) => {
                shown.insert(k.to_string(), v.clone());
                Ok(Some(v.clone()))
            }
            Some(_) => Err(Failure::Unusable),
            None => {
                if let Some(d) = &default {
                    shown.insert(k.to_string(), d.clone());
                }
                Ok(default)
            }
        }
    };
    let string = |v: &Json| v.is_string();
    let boolean = |v: &Json| v.is_boolean();
    let one_of = |values: &'static [&'static str]| {
        move |v: &Json| v.as_str().is_some_and(|s| values.contains(&s))
    };
    let list_of = |values: &'static [&'static str]| {
        move |v: &Json| {
            v.as_array().is_some_and(|a| {
                !a.is_empty()
                    && a.iter()
                        .all(|s| s.as_str().is_some_and(|s| values.contains(&s)))
            })
        }
    };
    let https = |v: &Json| v.as_str().and_then(https_url).is_some();
    let strings = |v: &Json| {
        v.as_array().map(|a| {
            a.iter()
                .map(|s| s.as_str().map(str::to_string))
                .collect::<Option<Vec<String>>>()
        })
    };
    let text = |v: Option<Json>| v.and_then(|v| v.as_str().map(str::to_string));

    let client_id = text(field(
        "client_id",
        &|v| v.as_str().is_some_and(|s| !s.is_empty()),
        None,
    )?);
    let redirects = field(
        "redirect_uris",
        &|v| {
            strings(v)
                .flatten()
                .is_some_and(|r| !r.is_empty() && r.iter().all(|u| form(u).is_some()))
        },
        None,
    )?;
    let redirect_uris = redirects
        .as_ref()
        .and_then(|v| strings(v).flatten())
        .ok_or(Failure::Unusable)?;
    let response_types = field(
        "response_types",
        &list_of(RESPONSE_TYPES),
        Some(Json::from(["code"].as_slice())),
    )?
    .and_then(|v| strings(&v).flatten())
    .unwrap_or_default();
    let grant_types = field(
        "grant_types",
        &list_of(GRANT_TYPES),
        Some(Json::from(["authorization_code"].as_slice())),
    )?
    .and_then(|v| strings(&v).flatten())
    .unwrap_or_default();
    let scope_string = text(field(
        "scope",
        &|v| v.as_str().is_some_and(scope::valid),
        None,
    )?);
    let auth = text(field(
        "token_endpoint_auth_method",
        &one_of(AUTH_METHODS),
        Some("client_secret_basic".into()),
    )?)
    .unwrap_or_default();
    let signing_alg = text(field("token_endpoint_auth_signing_alg", &string, None)?);
    let jwks = field(
        "jwks",
        &|v| v.get("keys").is_some_and(Json::is_array) && v.is_object(),
        None,
    )?;
    let jwks_uri = text(field("jwks_uri", &https, None)?).and_then(|u| https_url(&u));
    let application_type = text(field(
        "application_type",
        &one_of(&["web", "native"]),
        Some("web".into()),
    )?)
    .unwrap_or_default();
    let subject_type = text(field(
        "subject_type",
        &one_of(&["public", "pairwise"]),
        Some("public".into()),
    )?)
    .unwrap_or_default();
    field("client_name", &string, None)?;
    let client_uri = text(field("client_uri", &https, None)?).and_then(|u| https_url(&u));
    for k in ["logo_uri", "tos_uri", "policy_uri"] {
        field(k, &https, None)?;
    }
    field(
        "contacts",
        &|v| {
            strings(v)
                .flatten()
                .is_some_and(|c| c.iter().all(|e| email(e)))
        },
        None,
    )?;
    let dpop_bound = field("dpop_bound_access_tokens", &boolean, None)?;
    field(
        "authorization_signed_response_alg",
        &string,
        Some("RS256".into()),
    )?;
    for k in [
        "request_object_signing_alg",
        "authorization_encrypted_response_alg",
    ] {
        field(k, &string, None)?;
    }
    field("require_auth_time", &boolean, None)?;
    let tls_bound = field("tls_client_certificate_bound_access_tokens", &boolean, None)?;
    let enc = field(
        "authorization_encrypted_response_enc",
        &one_of(&["A128CBC-HS256"]),
        None,
    )?;
    let details = field(
        "authorization_details_types",
        &|v| strings(v).flatten().is_some(),
        None,
    )?;
    let max_age = field("default_max_age", &|v| v.is_number(), None)?;
    let mut oidc = max_age.is_some();
    for k in [
        "userinfo_signed_response_alg",
        "userinfo_encrypted_response_alg",
        "id_token_signed_response_alg",
    ] {
        oidc |= field(k, &string, None)?.is_some();
    }
    let keys = jwks
        .as_ref()
        .map(|j| assertion::client_keys(j["keys"].as_array().map_or(&[], Vec::as_slice)));
    if let Some(k) = &keys {
        shown.insert(
            "jwks".into(),
            serde_json::json!({ "keys": k.iter().map(assertion::shown).collect::<Vec<_>>() }),
        );
    }
    let forms: Vec<(String, Form)> = redirect_uris
        .iter()
        .filter_map(|u| form(u).map(|f| (u.clone(), f)))
        .collect();

    // The checks, in the page's order.
    // 1-3.
    if jwks.is_some() && jwks_uri.is_some() {
        return Err(REFUSED);
    }
    if oidc {
        return Err(REFUSED);
    }
    if client_uri
        .as_ref()
        .is_some_and(|u| matches!(u.host(), Some(Host::Domain(h)) if local_name(h)))
    {
        return Err(REFUSED);
    }
    // 4. A scope, with atproto, no token twice.
    let scope_string = scope_string.ok_or(REFUSED)?;
    let tokens = scope::tokens(&scope_string);
    if !tokens.contains(&"atproto")
        || tokens
            .iter()
            .enumerate()
            .any(|(i, t)| tokens[..i].contains(t))
    {
        return Err(REFUSED);
    }
    // 5. Grant types.
    let grants: Vec<&str> = grant_types.iter().map(String::as_str).collect();
    if grants.iter().enumerate().any(|(i, g)| {
        grants[..i].contains(g) || !["authorization_code", "refresh_token"].contains(g)
    }) {
        return Err(REFUSED);
    }
    // 6-7.
    if client_id.as_deref().is_some_and(|c| c != id) || subject_type != "public" {
        return Err(REFUSED);
    }
    // 8. Its authentication.
    let confidential = match auth.as_str() {
        "none" if signing_alg.is_none() => false,
        "private_key_jwt"
            if (jwks.is_some() || jwks_uri.is_some())
                && keys.as_ref().is_none_or(|k| !k.is_empty())
                && signing_alg.as_deref().is_some_and(|a| a != "none") =>
        {
            true
        }
        _ => return Err(REFUSED),
    };
    // 9-12.
    if enc.is_some() || tls_bound == Some(Json::Bool(true)) || dpop_bound != Some(Json::Bool(true))
    {
        return Err(REFUSED);
    }
    if !response_types.iter().any(|t| t == "code") || !grants.contains(&"authorization_code") {
        return Err(REFUSED);
    }
    if details
        .as_ref()
        .is_some_and(|d| d.as_array().is_some_and(|a| !a.is_empty()))
    {
        return Err(REFUSED);
    }
    // 13. Native clients are public.
    let native = application_type == "native";
    if native && confidential {
        return Err(REFUSED);
    }
    // 14. Each redirect URI.
    for (_, f) in &forms {
        let refused = match f {
            Form::Https(u) | Form::Loopback(u)
                if !u.username().is_empty() || u.password().is_some() =>
            {
                true
            }
            Form::Loopback(_) | Form::PrivateUse(_) => !native,
            Form::Https(u) => matches!(u.host(), Some(Host::Domain(h)) if local_name(h)),
        };
        if refused {
            return Err(REDIRECT);
        }
    }
    // 15-16.
    if client_id.is_none() {
        return Err(REFUSED);
    }
    if let Some(c) = &client_uri {
        let path = url.path();
        let parent = c.path() == path || (c.path().ends_with('/') && path.starts_with(c.path()));
        if c.origin() != url.origin() || !parent {
            return Err(REFUSED);
        }
    }
    // 17. A native client's redirect URIs are its own.
    let host = url.host_str().unwrap_or_default();
    let backwards: Vec<&str> = host.split('.').rev().collect();
    for (_, f) in &forms {
        let refused = match f {
            Form::PrivateUse(s) => *s != backwards.join("."),
            Form::Https(u) => native && u.origin() != url.origin(),
            Form::Loopback(_) => false,
        };
        if refused {
            return Err(REDIRECT);
        }
    }
    Ok(Taken {
        scope: scope_string,
        redirect_uris,
        refresh: grants.contains(&"refresh_token"),
        confidential,
        jwks: keys,
        jwks_uri,
        shown: Json::Object(shown),
    })
}

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

    #[test]
    fn client_ids() {
        assert!(client_id("https://app.example-client.net/c.json").is_ok());
        assert!(client_id("https://app.example-client.net/a/c.json?x=1&y").is_ok());
        for (id, why) in [
            ("http://app.example-client.net/c.json", META),
            ("HTTPS://app.example-client.net/c.json", META),
            ("https://app.example-client.net/", META),
            ("https://app.example-client.net", META),
            ("https://app.example-client.net?x=1", META),
            ("https://app.example-client.net/dir/", META),
            ("https://app.example-client.net/c.json#x", META),
            ("https://app.example-client.net/c.json#", META),
            ("https://u:p@app.example-client.net/c.json", META),
            ("https://app.example-client.net:8443/c.json", META),
            ("https://app.example-client.net:443/c.json", META),
            ("https://1.2.3.4/c.json", META),
            ("https://[2606:4700::1]/c.json", META),
            ("https://localhost/c.json", META),
            ("https://harness/c.json", META),
            ("https://app.harness.local/c.json", META),
            ("https://app.example-client.net/a/../c.json", META),
            ("https://app.example-client.net/./c.json", META),
            ("https://app.example-client.net/c json", META),
            ("https://app.harness.test/c.json", "invalid_client_id"),
            ("https://app.harness.EXAMPLE/c.json", "invalid_client_id"),
            ("https://app.harness.invalid/c.json", "invalid_client_id"),
            ("https://app.harness.localhost/c.json", "invalid_client_id"),
        ] {
            assert_eq!(client_id(id).err(), Some(why), "{id}");
        }
    }

    #[test]
    fn local_names() {
        for n in [
            "harness",
            "a.test",
            "a.LOCAL",
            "a.localhost",
            "a.invalid",
            "a.example",
        ] {
            assert!(local_name(n), "{n}");
        }
        for n in ["example.com", "app.example.net", "test.net"] {
            assert!(!local_name(n), "{n}");
        }
    }

    #[test]
    fn redirect_forms() {
        for (u, want) in [
            ("https://app.example-client.net/cb", "https"),
            ("https://1.2.3.4/cb", "https"),
            ("https://app.example-client.net:8443/cb", "https"),
            ("https://u:p@app.example-client.net/cb", "https"),
            ("http://127.0.0.1/cb", "loopback"),
            ("http://[::1]:8080/cb", "loopback"),
            ("net.example-client.app:/cb", "private"),
            ("com.example.app:/cb", "private"),
        ] {
            let got = match form(u) {
                Some(Form::Https(_)) => "https",
                Some(Form::Loopback(_)) => "loopback",
                Some(Form::PrivateUse(_)) => "private",
                None => "none",
            };
            assert_eq!(got, want, "{u}");
        }
        for u in [
            "https://localhost/cb",
            "https://127.0.0.1/cb",
            "https://[::1]/cb",
            "https://harness/cb",
            "https://a.harness.local/cb",
            "http://app.example-client.net/cb",
            "http://localhost/cb",
            "nope",
            "harnessapp:/cb",
            "net.example.app://cb",
            "test.harness:/cb",
            "net.example.app:cb",
        ] {
            assert!(form(u).is_none(), "{u}");
        }
    }
}