~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
230 lines · 8.1 KB Raw History
//! The clients the server takes: loopback clients, whose `client_id` is
//! their metadata (`atproto/oauth.md`, "Localhost Client Development"), and
//! the redirect URIs they may name, as `spec/OAUTH.md` says under "Clients".
//! Discoverable clients, whose `client_id` is an `https://` URL, are loaded
//! by `super::clients` into the same `Client`.

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

/// The redirect URIs of a loopback client that names none.
const DEFAULT_REDIRECTS: &[&str] = &["http://127.0.0.1/", "http://[::1]/"];

/// A client, by its `client_id`.
pub(crate) struct Client {
    pub id: String,
    /// Its scope string.
    pub scope: String,
    /// In the order given.
    pub redirect_uris: Vec<String>,
    /// Whether its grant types include `refresh_token`.
    pub refresh: bool,
    /// A confidential client's keys (`private_key_jwt`); None for a public client.
    pub keys: Option<Vec<Map<String, Json>>>,
    /// A discoverable client's document, as the authorization page shows it.
    pub document: Option<Json>,
}

/// An `http:` URL on `127.0.0.1` or `[::1]`.
pub(super) fn loopback(u: &Url) -> bool {
    u.scheme() == "http"
        && match u.host() {
            Some(Host::Ipv4(a)) => a == Ipv4Addr::LOCALHOST,
            Some(Host::Ipv6(a)) => a == Ipv6Addr::LOCALHOST,
            _ => false,
        }
}

/// The client a `client_id` names, or the error that refuses it.
pub(crate) fn client(id: &str) -> Result<Client, &'static str> {
    const META: &str = "invalid_client_metadata";
    let rest = id.strip_prefix("http://localhost").ok_or(META)?;
    let rest = rest.strip_prefix('/').unwrap_or(rest);
    let query = if rest.is_empty() {
        ""
    } else {
        rest.strip_prefix('?').ok_or(META)?
    };
    if query.contains('#') {
        return Err(META);
    }
    let mut scope = None;
    let mut redirect_uris = Vec::new();
    for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
        match &*k {
            "scope" if scope.is_none() => {
                let tokens = scope::tokens(&v);
                let distinct = tokens
                    .iter()
                    .enumerate()
                    .all(|(i, t)| !tokens[..i].contains(t));
                if !scope::valid(&v) || !tokens.contains(&"atproto") || !distinct {
                    return Err(META);
                }
                scope = Some(v.into_owned());
            }
            "redirect_uri" => {
                let u = Url::parse(&v).map_err(|_| META)?;
                if !loopback(&u) {
                    return Err(META);
                }
                if !u.username().is_empty() || u.password().is_some() {
                    return Err("invalid_redirect_uri");
                }
                redirect_uris.push(v.into_owned());
            }
            _ => return Err(META),
        }
    }
    if redirect_uris.is_empty() {
        redirect_uris = DEFAULT_REDIRECTS.iter().map(|u| u.to_string()).collect();
    }
    Ok(Client {
        id: id.to_string(),
        scope: scope.unwrap_or_else(|| "atproto".into()),
        redirect_uris,
        refresh: true,
        keys: None,
        document: None,
    })
}

impl Client {
    /// Its metadata, as the authorization page shows it.
    pub fn metadata(&self) -> Json {
        if let Some(d) = &self.document {
            return d.clone();
        }
        json!({
            "client_id": self.id, "scope": self.scope, "redirect_uris": self.redirect_uris,
            "response_types": ["code"], "grant_types": ["authorization_code", "refresh_token"],
            "token_endpoint_auth_method": "none", "application_type": "native",
            "subject_type": "public", "authorization_signed_response_alg": "RS256",
            "dpop_bound_access_tokens": true,
        })
    }

    /// The redirect URI a request gets: the one given, if it is one of the
    /// client's, or the client's only one if none is given.
    pub fn redirect_uri(&self, given: Option<&str>) -> Option<String> {
        match given {
            None => match &self.redirect_uris[..] {
                [only] => Some(only.clone()),
                _ => None,
            },
            Some(g) => self
                .redirect_uris
                .iter()
                .any(|mine| matches(mine, g))
                .then(|| g.to_string()),
        }
    }
}

/// Whether a redirect URI given matches one of the client's: equal, or both
/// loopback, the client's with no port, and equal but for the port (RFC 8252 §7.3).
fn matches(mine: &str, given: &str) -> bool {
    if mine == given {
        return true;
    }
    let (Ok(m), Ok(mut g)) = (Url::parse(mine), Url::parse(given)) else {
        return false;
    };
    loopback(&m)
        && loopback(&g)
        && m.port().is_none()
        && g.set_port(None).is_ok()
        && m.as_str() == g.as_str()
}

/// Whether a redirect URI is of a form a request may name: an `https:` URL,
/// an `http:` one on `127.0.0.1` or `[::1]`, or a private-use scheme's.
pub(crate) fn redirect_form(uri: &str) -> bool {
    let Ok(u) = Url::parse(uri) else { return false };
    match u.scheme() {
        "https" => true,
        "http" => loopback(&u),
        scheme => {
            let rest = &uri[scheme.len() + 1..];
            scheme.contains('.') && rest.starts_with('/') && !rest.starts_with("//")
        }
    }
}

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

    #[test]
    fn loopback_clients() {
        let c = client("http://localhost").unwrap();
        assert_eq!(
            (c.scope.as_str(), c.redirect_uris.clone()),
            (
                "atproto",
                vec!["http://127.0.0.1/".to_string(), "http://[::1]/".to_string()]
            )
        );
        let c = client("http://localhost/?scope=atproto+transition:generic&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2Fcb&redirect_uri=http://[::1]/x").unwrap();
        assert_eq!(c.scope, "atproto transition:generic");
        assert_eq!(
            c.redirect_uris,
            ["http://127.0.0.1:8080/cb", "http://[::1]/x"]
        );
        assert_eq!(c.metadata()["redirect_uris"], json!(c.redirect_uris));
        for bad in [
            "https://localhost",
            "http://localhost:80",
            "http://localhost/path",
            "http://localhost#x",
            "http://localhost?other=1",
            "http://localhost?scope=transition:generic",
            "http://localhost?scope=atproto&scope=atproto",
            "http://localhost?scope=atproto+atproto",
            "http://localhost?scope=",
            "http://localhost?redirect_uri=http://localhost/",
            "http://localhost?redirect_uri=https://127.0.0.1/",
            "https://example.com/client-metadata.json",
            "http://localhostx",
        ] {
            assert_eq!(client(bad).err(), Some("invalid_client_metadata"), "{bad}");
        }
        assert_eq!(
            client("http://localhost?redirect_uri=http://u:p@127.0.0.1/").err(),
            Some("invalid_redirect_uri")
        );
    }

    #[test]
    fn redirect_uris() {
        let c = client("http://localhost?redirect_uri=http://127.0.0.1/cb").unwrap();
        assert_eq!(c.redirect_uri(None).as_deref(), Some("http://127.0.0.1/cb"));
        assert_eq!(
            c.redirect_uri(Some("http://127.0.0.1:5000/cb")).as_deref(),
            Some("http://127.0.0.1:5000/cb")
        );
        assert_eq!(c.redirect_uri(Some("http://127.0.0.1/other")), None);
        assert_eq!(client("http://localhost").unwrap().redirect_uri(None), None);
        let ported = client("http://localhost?redirect_uri=http://127.0.0.1:1/cb").unwrap();
        assert_eq!(ported.redirect_uri(Some("http://127.0.0.1:2/cb")), None);
        for ok in [
            "https://example.com/cb",
            "http://127.0.0.1:1/",
            "http://[::1]/",
            "com.example.app:/cb",
        ] {
            assert!(redirect_form(ok), "{ok}");
        }
        for bad in [
            "http://localhost/",
            "http://example.com/",
            "app:/cb",
            "com.example.app://cb",
            "not a url",
        ] {
            assert!(!redirect_form(bad), "{bad}");
        }
    }
}