~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
237 lines · 7.9 KB Raw History
//! Discoverable clients, whose `client_id` is an `https://` URL, as
//! `spec/OAUTH-CLIENTS.md` says: their documents and JWKS, fetched
//! (`fetch`), checked (`document`) and kept 10 minutes; confidential
//! clients' authentication with `private_key_jwt` (`assertion`); silent
//! sign-in (`silent`); and MCP clients, whose documents are fetched and kept
//! alike but held to MCP's rules (`mcp`, `spec/OAUTH-MCP.md`).
//!
//! Documents and JWKS are kept in memory only, each cache behind its own
//! lock, never held across a fetch: a restart forgets them. What must
//! survive (the key a request and session are bound to, the clients each
//! account approved, spent assertions) is in what OAuth logs.

mod assertion;
mod document;
mod fetch;
mod mcp;
pub(super) mod silent;
#[cfg(test)]
mod tests;

pub(super) use assertion::authenticate;
pub(crate) use fetch::ClientFetch;
pub(super) use mcp::redirect_uri as mcp_redirect_uri;

use super::client::{self, Client};
use crate::Service;
use serde_json::{Map, Value as Json};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};

const META: &str = "invalid_client_metadata";
/// How long a document or JWKS is kept from when it was fetched.
const KEEP: u64 = 10 * 60;
/// How many of each are kept at most: the oldest goes first.
const KEPT_MAX: usize = 1024;
/// How long a confidential client's session lasts from when it started,
/// and from its last token answer.
pub(super) const CONFIDENTIAL_LIFE: u64 = 730 * 24 * 60 * 60;
pub(super) const CONFIDENTIAL_IDLE: u64 = 90 * 24 * 60 * 60;

/// Why a client cannot be loaded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Failure {
    /// Its `client_id` is refused, with this error.
    Id(&'static str),
    /// Its document or JWKS could not be had, or is not of the form the
    /// field table and the redirect URI forms give.
    Unusable,
    /// Its document fails a numbered check, with this error.
    Check(&'static str),
}

impl Failure {
    /// The error wherever a client is loaded but at `consent`.
    pub fn error(self) -> &'static str {
        match self {
            Failure::Id(e) | Failure::Check(e) => e,
            Failure::Unusable => META,
        }
    }

    /// The error `consent` ends its request with.
    pub fn at_consent(self) -> &'static str {
        match self {
            Failure::Unusable => "server_error",
            Failure::Id(_) | Failure::Check(_) => "invalid_request",
        }
    }
}

/// What is kept by URL, with when it was fetched.
struct Cache<T>(Mutex<HashMap<String, (u64, T)>>);

impl<T: Clone> Cache<T> {
    fn new() -> Self {
        Cache(Mutex::new(HashMap::new()))
    }

    fn get(&self, url: &str, now: u64) -> Option<T> {
        let kept = self.0.lock().unwrap_or_else(PoisonError::into_inner);
        kept.get(url)
            .filter(|(at, _)| now < at + KEEP)
            .map(|(_, v)| v.clone())
    }

    fn put(&self, url: &str, now: u64, value: T) {
        let mut kept = self.0.lock().unwrap_or_else(PoisonError::into_inner);
        kept.retain(|_, (at, _)| now < *at + KEEP);
        if kept.len() >= KEPT_MAX
            && let Some(oldest) = kept
                .iter()
                .min_by_key(|(_, (at, _))| *at)
                .map(|(k, _)| k.clone())
        {
            kept.remove(&oldest);
        }
        kept.insert(url.to_string(), (now, value));
    }
}

/// The documents and JWKS kept, and how they are fetched.
pub(crate) struct Clients {
    fetcher: fetch::Fetcher,
    documents: Cache<Arc<document::Taken>>,
    jwks: Cache<Arc<Vec<Map<String, Json>>>>,
    /// MCP clients' documents, taken by MCP's rules.
    mcp_documents: Cache<Arc<mcp::Taken>>,
}

impl Clients {
    pub fn new(dev: Option<ClientFetch>) -> Clients {
        Clients {
            fetcher: fetch::Fetcher::new(dev),
            documents: Cache::new(),
            jwks: Cache::new(),
            mcp_documents: Cache::new(),
        }
    }
}

/// The client a `client_id` names, as the server checks it wherever it
/// takes one: a loopback client, or a discoverable one, its document and
/// JWKS fetched or kept; or the error that refuses it.
pub(super) async fn load(svc: &Service, id: &str) -> Result<Client, &'static str> {
    load_why(svc, id).await.map_err(Failure::error)
}

/// `load`, saying why it fails.
pub(super) async fn load_why(svc: &Service, id: &str) -> Result<Client, Failure> {
    if !discoverable(id) {
        return client::client(id).map_err(Failure::Id);
    }
    let url = document::client_id(id).map_err(Failure::Id)?;
    let clients = &svc.oauth.clients;
    let taken = match clients.documents.get(id, svc.sessions.now()) {
        Some(t) => t,
        None => {
            let doc = clients
                .fetcher
                .get(&svc.outbound, &url, fetch::Kind::Document)
                .await
                .map_err(|_| Failure::Unusable)?;
            let t = Arc::new(document::check(id, &url, &doc)?);
            clients.documents.put(id, svc.sessions.now(), t.clone());
            t
        }
    };
    // A `jwks_uri` is fetched (or kept) whenever its client is loaded.
    let fetched = match &taken.jwks_uri {
        Some(u) => Some(jwks(svc, u).await?),
        None => None,
    };
    let keys = taken.confidential.then(|| {
        fetched
            .map(|k| k.to_vec())
            .or_else(|| taken.jwks.clone())
            .unwrap_or_default()
    });
    Ok(Client {
        id: id.to_string(),
        scope: taken.scope.clone(),
        redirect_uris: taken.redirect_uris.clone(),
        refresh: taken.refresh,
        keys,
        document: Some(taken.shown.clone()),
    })
}

/// An MCP client (`spec/OAUTH-MCP.md`, "Clients"): its document fetched or
/// kept as any discoverable client's, then held to MCP's rules. A
/// `client_id` that is not an https one as `spec/OAUTH-CLIENTS.md` has it
/// is `invalid_client`.
pub(super) async fn load_mcp(svc: &Service, id: &str) -> Result<Client, Failure> {
    const INVALID: Failure = Failure::Id("invalid_client");
    if !discoverable(id) {
        return Err(INVALID);
    }
    let url = document::client_id(id).map_err(|_| INVALID)?;
    let clients = &svc.oauth.clients;
    let taken = match clients.mcp_documents.get(id, svc.sessions.now()) {
        Some(t) => t,
        None => {
            let doc = clients
                .fetcher
                .get(&svc.outbound, &url, fetch::Kind::Document)
                .await
                .map_err(|_| Failure::Unusable)?;
            let t = Arc::new(mcp::check(id, &doc)?);
            clients.mcp_documents.put(id, svc.sessions.now(), t.clone());
            t
        }
    };
    Ok(Client {
        id: id.to_string(),
        scope: String::new(),
        redirect_uris: taken.redirect_uris.clone(),
        refresh: taken.refresh,
        keys: None,
        document: Some(taken.shown.clone()),
    })
}

/// The client of a request, loaded as its issuer loads it: the MCP
/// issuer's (`mcp`) by `load_mcp`, the atproto one's by `load_why`.
pub(super) async fn load_for(svc: &Service, id: &str, mcp: bool) -> Result<Client, Failure> {
    if mcp {
        load_mcp(svc, id).await
    } else {
        load_why(svc, id).await
    }
}

/// The client keys of the JWKS at `url`, fetched or kept.
async fn jwks(svc: &Service, url: &url::Url) -> Result<Arc<Vec<Map<String, Json>>>, Failure> {
    let clients = &svc.oauth.clients;
    if let Some(k) = clients.jwks.get(url.as_str(), svc.sessions.now()) {
        return Ok(k);
    }
    let set = clients
        .fetcher
        .get(&svc.outbound, url, fetch::Kind::Jwks)
        .await
        .map_err(|_| Failure::Unusable)?;
    let Some(Json::Array(keys)) = set.get("keys") else {
        return Err(Failure::Unusable);
    };
    let keys = Arc::new(assertion::client_keys(keys));
    clients
        .jwks
        .put(url.as_str(), svc.sessions.now(), keys.clone());
    Ok(keys)
}

/// Whether a `client_id` is a discoverable client's.
pub(super) fn discoverable(id: &str) -> bool {
    id.starts_with("https://")
}