~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
200 lines · 7.3 KB Raw History
//! Fetching a client's document or JWKS, as `spec/OAUTH-CLIENTS.md` says
//! under "The document": one `GET`, no redirect followed, `200`, JSON of at
//! most 512 KiB, within 10 seconds, over https; or, for an origin
//! `PDS_OAUTH_CLIENT_FETCH` lists, from the base URL it names instead ("The
//! development fetch"). Every fetch goes out through `outbound`, from public
//! unicast addresses only unless `PDS_DISABLE_SSRF_PROTECTION` says otherwise.

use crate::outbound::Outbound;
use serde_json::{Map, Value as Json};
use std::time::Duration;
use url::{Host, Url};

/// The largest answer taken.
const MAX_BODY: usize = 512 * 1024;
/// How long an answer may take, whole.
const TIMEOUT: Duration = Duration::from_secs(10);
/// The variable that names the development fetch.
const VAR: &str = "PDS_OAUTH_CLIENT_FETCH";

/// The development fetch: each origin, `https://<host>`, and the base URL
/// its documents are fetched from instead.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct ClientFetch(Vec<(String, String)>);

impl ClientFetch {
    /// `PDS_OAUTH_CLIENT_FETCH`, if set: Err if it does not parse. Set to
    /// nothing, it is as unset, as the server's other optional variables are.
    pub fn from_env() -> Result<Option<ClientFetch>, String> {
        match std::env::var(VAR) {
            Ok(v) if !v.trim().is_empty() => ClientFetch::parse(&v)
                .map(Some)
                .map_err(|e| format!("{VAR}: {e}")),
            _ => Ok(None),
        }
    }

    /// A comma-separated list of `<origin>=<base URL>`.
    pub fn parse(s: &str) -> Result<ClientFetch, String> {
        let mut out = Vec::new();
        for item in s.split(',').map(str::trim) {
            let (origin, base) = item
                .split_once('=')
                .ok_or_else(|| format!("{item:?} is not <origin>=<base URL>"))?;
            let o = Url::parse(origin).map_err(|e| format!("{origin:?}: {e}"))?;
            let host = match o.host() {
                Some(Host::Domain(h)) => h.to_string(),
                _ => {
                    return Err(format!(
                        "{origin:?} is not an https origin with a host name"
                    ));
                }
            };
            if o.scheme() != "https" || origin != format!("https://{host}") {
                return Err(format!(
                    "{origin:?} is not https://<host>, with no port or path"
                ));
            }
            let b = Url::parse(base).map_err(|e| format!("{base:?}: {e}"))?;
            let plain = b.username().is_empty()
                && b.password().is_none()
                && b.query().is_none()
                && b.fragment().is_none();
            if !["http", "https"].contains(&b.scheme())
                || b.host().is_none()
                || !plain
                || base.ends_with('/')
                || base.contains(['?', '#'])
            {
                return Err(format!(
                    "{base:?} is not an http or https URL with a host, an optional port and path, and no trailing /"
                ));
            }
            out.push((origin.to_string(), base.to_string()));
        }
        Ok(ClientFetch(out))
    }

    /// Where `url` is fetched from instead, if its origin is listed.
    fn target(&self, url: &Url) -> Option<String> {
        let origin = url.origin().ascii_serialization();
        let (_, base) = self.0.iter().find(|(o, _)| *o == origin)?;
        let query = url.query().map(|q| format!("?{q}")).unwrap_or_default();
        Some(format!("{base}{}{query}", url.path()))
    }
}

/// What is fetched: a document must say it is JSON, a JWKS may say nothing.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Kind {
    Document,
    Jwks,
}

/// How clients' documents and JWKS are fetched: through `Outbound`, as every
/// request to another service is, with the development fetch's mapping.
pub(super) struct Fetcher {
    dev: Option<ClientFetch>,
    timeout: Duration,
}

impl Fetcher {
    pub fn new(dev: Option<ClientFetch>) -> Fetcher {
        Fetcher::with_timeout(dev, TIMEOUT)
    }

    pub fn with_timeout(dev: Option<ClientFetch>, timeout: Duration) -> Fetcher {
        Fetcher { dev, timeout }
    }

    /// The JSON object at `url`, if it is answered as `spec/OAUTH-CLIENTS.md`
    /// takes it; else why not. An origin the development fetch lists is
    /// fetched from its base URL instead; any other only over https. Either
    /// goes out through `outbound`, and its SSRF protection.
    pub async fn get(
        &self,
        outbound: &Outbound,
        url: &Url,
        kind: Kind,
    ) -> Result<Map<String, Json>, String> {
        let target = match self.dev.as_ref().and_then(|d| d.target(url)) {
            Some(mapped) => mapped,
            None if url.scheme() != "https" => return Err(format!("{url} is not https")),
            None => url.to_string(),
        };
        let got = outbound
            .fetch_limited(
                crate::ops::Target::Client,
                outbound
                    .client()
                    .get(&target)
                    .header("accept", "application/json"),
                MAX_BODY,
                self.timeout,
            )
            .await?;
        if got.status != 200 {
            return Err(format!("{url} answered {}", got.status));
        }
        let essence = got.headers.get("content-type").map(|v| {
            v.to_str()
                .unwrap_or_default()
                .split(';')
                .next()
                .unwrap_or_default()
                .trim()
                .to_ascii_lowercase()
        });
        let json = essence
            .as_deref()
            .map_or(kind == Kind::Jwks, |e| e == "application/json");
        if !json {
            return Err(format!("{url} is not answered as application/json"));
        }
        match serde_json::from_slice(&got.body) {
            Ok(Json::Object(m)) => Ok(m),
            _ => Err(format!("{url} is not a JSON object")),
        }
    }
}

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

    #[test]
    fn the_development_fetch() {
        let f = ClientFetch::parse("https://app.example-client.net=http://127.0.0.1:4100/server/app,https://b.example-client.net=https://x.net").unwrap();
        let u = Url::parse("https://app.example-client.net/c.json?x=1").unwrap();
        assert_eq!(
            f.target(&u).as_deref(),
            Some("http://127.0.0.1:4100/server/app/c.json?x=1")
        );
        assert_eq!(
            f.target(&Url::parse("https://b.example-client.net/j").unwrap())
                .as_deref(),
            Some("https://x.net/j")
        );
        assert_eq!(
            f.target(&Url::parse("https://other.example-client.net/c.json").unwrap()),
            None
        );
        for bad in [
            "",
            "https://a.net",
            "https://a.net=",
            "http://a.net=http://127.0.0.1",
            "https://a.net/=http://127.0.0.1",
            "https://a.net:443=http://127.0.0.1",
            "https://a.net/p=http://127.0.0.1",
            "https://1.2.3.4=http://127.0.0.1",
            "https://a.net=ftp://127.0.0.1",
            "https://a.net=http://127.0.0.1/",
            "https://a.net=http://127.0.0.1/p?q",
            "https://a.net=http://u@127.0.0.1",
            "https://a.net=http://127.0.0.1,",
        ] {
            assert!(ClientFetch::parse(bad).is_err(), "{bad}");
        }
    }
}