~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
1111 lines · 44.8 KB Raw History
//! Sign-in's HTTP surface (`hud_core::oauth`), mounted with sign-in on:
//! the MCP endpoint's protected resource metadata and HUD's authorization
//! server metadata (`/.well-known/…`, readable from any origin); the
//! authorization endpoint and its sign-in page (`/oauth/authorize`), which
//! HUD's own app naming its account as a login hint goes past, straight on
//! to the account's server; the account's server's redirect back
//! (`/oauth/callback`), on to the MCP client or, for the workspace's
//! sign-in, to the workspace with its session's cookie, the session it
//! was in, if any, kept among the browser's others
//! (`crate::workspace::signed_in`); the token, revocation and registration
//! endpoints; and HUD's atproto client metadata and public key.
//!
//! The sign-in page is HTML of the server's own, no script: a handle
//! field, the client's name as plain text, and a line for what went wrong.
//! Its CSP lets it load nothing and post only to itself, then on to an
//! https server; no site may frame it.

use axum::Router;
use axum::body::Bytes;
use axum::extract::{RawQuery, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use hud_core::Hud;
use hud_core::oauth::Auth;
use hud_core::oauth::client::{Callback, SignIn};
use hud_core::oauth::issuer::{Authorized, NotAuthorized, Pending, Refused, body_params, params};
use serde_json::{Value as Json, json};
use std::sync::Arc;

/// The most of a request body read.
const MAX_BODY: usize = 16 * 1024;
/// The sign-in page's Content-Security-Policy.
const PAGE_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' https:; frame-ancestors 'none'";
/// The sign-in page's, with `HUD_ALLOW_PRIVATE`: its form goes on to an
/// account's server over plain http too, as a local PDS is reached.
const PAGE_CSP_PRIVATE: &str = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' https: http:; frame-ancestors 'none'";

/// Sign-in's routes, over the server's state.
pub fn routes() -> Router<Arc<Hud>> {
    Router::new()
        .route(
            "/.well-known/oauth-protected-resource",
            get(protected_resource),
        )
        .route(
            "/.well-known/oauth-protected-resource/mcp",
            get(protected_resource),
        )
        .route(
            "/.well-known/oauth-authorization-server",
            get(authorization_server),
        )
        .route("/oauth/authorize", get(authorize).post(sign_in))
        .route("/oauth/callback", get(callback))
        .route(
            "/oauth/token",
            axum::routing::post(token).options(preflight),
        )
        .route(
            "/oauth/revoke",
            axum::routing::post(revoke).options(preflight),
        )
        .route(
            "/oauth/register",
            axum::routing::post(register).options(preflight),
        )
        .route("/oauth/client-metadata.json", get(client_metadata))
        .route("/oauth/app-client.json", get(app_client_metadata))
        .route("/oauth/jwks.json", get(jwks))
}

/// A metadata document of sign-in's state; the routes are mounted only
/// with it on.
fn auth_document(hud: &Hud, doc: impl FnOnce(&Auth) -> Json) -> Result<Response, StatusCode> {
    hud.oauth
        .as_ref()
        .map(|a| document(doc(a)))
        .ok_or(StatusCode::NOT_FOUND)
}

/// A JSON answer any origin may read, never kept by a cache.
fn json_answer(status: StatusCode, body: &Json) -> Response {
    (
        status,
        [
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"),
            (header::CACHE_CONTROL, "no-store"),
            (header::PRAGMA, "no-cache"),
        ],
        body.to_string(),
    )
        .into_response()
}

/// A metadata document: public, kept a while.
fn document(body: Json) -> Response {
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"),
            (header::CACHE_CONTROL, "public, max-age=300"),
        ],
        body.to_string(),
    )
        .into_response()
}

fn refused(r: Refused) -> Response {
    json_answer(
        StatusCode::from_u16(r.status).unwrap_or(StatusCode::BAD_REQUEST),
        &r.to_json(),
    )
}

/// A browser's preflight of a POST to the token, revocation or
/// registration endpoint.
async fn preflight() -> Response {
    (
        StatusCode::NO_CONTENT,
        [
            (header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"),
            (header::ACCESS_CONTROL_ALLOW_METHODS, "POST"),
            (
                header::ACCESS_CONTROL_ALLOW_HEADERS,
                "content-type, authorization",
            ),
            (header::ACCESS_CONTROL_MAX_AGE, "86400"),
        ],
    )
        .into_response()
}

async fn protected_resource(State(hud): State<Arc<Hud>>) -> Result<Response, StatusCode> {
    auth_document(&hud, Auth::protected_resource)
}

async fn authorization_server(State(hud): State<Arc<Hud>>) -> Result<Response, StatusCode> {
    auth_document(&hud, Auth::authorization_server)
}

async fn client_metadata(State(hud): State<Arc<Hud>>) -> Result<Response, StatusCode> {
    auth_document(&hud, Auth::client_metadata)
}

async fn app_client_metadata(State(hud): State<Arc<Hud>>) -> Result<Response, StatusCode> {
    auth_document(&hud, Auth::app_client_metadata)
}

async fn jwks(State(hud): State<Arc<Hud>>) -> Result<Response, StatusCode> {
    auth_document(&hud, Auth::jwks)
}

/// A query string's pairs.
pub(crate) fn pairs(query: Option<&str>) -> Vec<(String, String)> {
    url::form_urlencoded::parse(query.unwrap_or_default().as_bytes())
        .map(|(k, v)| (k.into_owned(), v.into_owned()))
        .collect()
}

/// A redirect the browser follows with a GET.
pub(crate) fn see_other(to: &str) -> Response {
    (
        StatusCode::SEE_OTHER,
        [
            (header::LOCATION, to),
            (header::CACHE_CONTROL, "no-store"),
            (header::REFERRER_POLICY, "no-referrer"),
        ],
    )
        .into_response()
}

/// `GET /oauth/authorize`: the request checked, then its sign-in page; or,
/// for a client that names the account itself (HUD's own app, an app's
/// web client drawing its own sign-in screen), on to the account's server
/// (back to the client, saying why, where that fails).
async fn authorize(State(hud): State<Arc<Hud>>, RawQuery(query): RawQuery) -> Response {
    match hud.begin_sign_in(&pairs(query.as_deref())).await {
        Ok(Authorized::Server(to)) => see_other(&to),
        Ok(Authorized::Page(pending)) => {
            sign_in_page(hud.config.allow_private, StatusCode::OK, &pending, None)
        }
        Err(NotAuthorized::Redirect(to)) => see_other(&to),
        Err(NotAuthorized::Page(why)) => error_page(StatusCode::BAD_REQUEST, &why),
    }
}

/// `POST /oauth/authorize`: the sign-in page's form, sent on to the
/// account's server, or with `create`, "Create one", to the sign-up PDS's
/// server; else the page again, saying why.
async fn sign_in(State(hud): State<Arc<Hud>>, headers: HeaderMap, body: Bytes) -> Response {
    let expired = || {
        error_page(
            StatusCode::BAD_REQUEST,
            "This sign-in has expired or was already used; start again from your app.",
        )
    };
    if body.len() > MAX_BODY {
        return error_page(StatusCode::PAYLOAD_TOO_LARGE, "The form is too large.");
    }
    let content_type = headers
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok());
    let Ok(form) = body_params(content_type, &body).and_then(|p| {
        params(&p).map_err(|why| Refused {
            status: 400,
            error: "invalid_request",
            description: why,
        })
    }) else {
        return expired();
    };
    let id = form.get("request").map(String::as_str).unwrap_or_default();
    let handle = form.get("handle").map(String::as_str).unwrap_or_default();
    let went = if form.get("create").is_some_and(|c| c == "1") {
        hud.sign_up(id).await
    } else {
        hud.sign_in(id, handle).await
    };
    match went {
        Ok(to) => see_other(&to),
        Err(SignIn::Expired) => expired(),
        Err(SignIn::Failed(pending, why)) => sign_in_page(
            hud.config.allow_private,
            StatusCode::BAD_REQUEST,
            &pending,
            Some(&why),
        ),
    }
}

/// `GET /oauth/callback`: the account's server's answer, sent on to the
/// MCP client; or, for the workspace's sign-in, to the workspace, its
/// session's cookie set and the one it replaces kept among the browser's
/// others.
async fn callback(
    State(hud): State<Arc<Hud>>,
    headers: HeaderMap,
    RawQuery(query): RawQuery,
) -> Response {
    match hud.callback(&pairs(query.as_deref())).await {
        Ok(Callback::Client(to)) => see_other(&to),
        Ok(Callback::Web(cookie)) => {
            let mut r = see_other("/workspace");
            crate::workspace::signed_in(&hud, &headers, &cookie, &mut r).await;
            r
        }
        Ok(Callback::WebRefused(why)) => web_error_page(StatusCode::BAD_REQUEST, &why),
        Err(why) => error_page(StatusCode::BAD_REQUEST, &why),
    }
}

/// A form or JSON body's pairs, within `MAX_BODY`.
fn body_pairs(headers: &HeaderMap, body: &[u8]) -> Result<Vec<(String, String)>, Refused> {
    if body.len() > MAX_BODY {
        return Err(Refused {
            status: 413,
            error: "invalid_request",
            description: "The body is too large".into(),
        });
    }
    let content_type = headers
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok());
    body_params(content_type, body)
}

/// `POST /oauth/token`.
async fn token(State(hud): State<Arc<Hud>>, headers: HeaderMap, body: Bytes) -> Response {
    let answer = match body_pairs(&headers, &body) {
        Ok(p) => hud.token(&p).await,
        Err(r) => Err(r),
    };
    match answer {
        Ok(tokens) => json_answer(StatusCode::OK, &tokens),
        Err(r) => refused(r),
    }
}

/// `POST /oauth/revoke`.
async fn revoke(State(hud): State<Arc<Hud>>, headers: HeaderMap, body: Bytes) -> Response {
    let answer = match body_pairs(&headers, &body) {
        Ok(p) => hud.revoke(&p).await,
        Err(r) => Err(r),
    };
    match answer {
        Ok(()) => json_answer(StatusCode::OK, &json!({})),
        Err(r) => refused(r),
    }
}

/// `POST /oauth/register`.
async fn register(State(hud): State<Arc<Hud>>, body: Bytes) -> Response {
    if body.len() > MAX_BODY {
        return refused(Refused {
            status: 413,
            error: "invalid_client_metadata",
            description: "The body is too large".into(),
        });
    }
    match hud.register(&body) {
        Ok(client) => json_answer(StatusCode::CREATED, &client),
        Err(r) => refused(r),
    }
}

/// Text as HTML.
pub(crate) fn esc(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            c => out.push(c),
        }
    }
    out
}

/// A page of the server's own, `body` its HTML.
fn page(status: StatusCode, title: &str, body: &str) -> Response {
    let html = format!(
        r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>
  :root {{ color-scheme: light dark; font-family: system-ui, sans-serif; }}
  body {{ margin: 0; min-height: 100vh; display: grid; place-items: center; background: Canvas; color: CanvasText; }}
  main {{ width: min(26rem, calc(100vw - 2rem)); padding: 2rem 0; }}
  h1 {{ font-size: 1.35rem; margin: 0 0 1rem; }}
  p, li {{ line-height: 1.45; }}
  ul {{ padding-left: 1.2rem; }}
  .client {{ font-weight: 600; }}
  .error {{ color: #c62828; border-left: 3px solid #c62828; padding-left: .6rem; }}
  label {{ display: block; font-weight: 600; margin: 1.2rem 0 .4rem; }}
  input {{ width: 100%; box-sizing: border-box; font: inherit; padding: .6rem .7rem; border: 1px solid GrayText; border-radius: .4rem; background: Field; color: FieldText; }}
  button {{ margin-top: 1rem; width: 100%; font: inherit; font-weight: 600; padding: .65rem; border: 0; border-radius: .4rem; background: #1565c0; color: white; cursor: pointer; }}
  .note {{ font-size: .85rem; opacity: .75; }}
  .create {{ margin: .9rem 0 0; text-align: center; font-size: .9rem; }}
  .create button {{ display: inline; width: auto; margin: 0; padding: 0; background: none; color: LinkText; font-weight: 600; text-decoration: underline; }}
  a {{ color: LinkText; }}
</style>
</head>
<body><main>
{body}
</main></body>
</html>
"#,
        title = esc(title),
    );
    (
        status,
        [
            (header::CONTENT_TYPE, "text/html; charset=utf-8"),
            (header::CONTENT_SECURITY_POLICY, PAGE_CSP),
            (header::CACHE_CONTROL, "no-store"),
            (header::REFERRER_POLICY, "no-referrer"),
            (header::X_FRAME_OPTIONS, "DENY"),
        ],
        html,
    )
        .into_response()
}

/// The sign-in page of an MCP client's request waiting, naming the client,
/// with what went wrong, if anything. With `allow_private`
/// (`HUD_ALLOW_PRIVATE`), its form may go on to a PDS on plain http, as a
/// local one is.
fn sign_in_page(
    allow_private: bool,
    status: StatusCode,
    p: &Pending,
    error: Option<&str>,
) -> Response {
    let error = error
        .map(|e| format!(r#"<p class="error" role="alert">{}</p>"#, esc(e)))
        .unwrap_or_default();
    let intro = format!(
        r#"<p><span class="client">{}</span> wants to use HUD as you. Signed in, HUD will be able to:</p>"#,
        esc(&p.client)
    );
    let body = format!(
        r#"<h1>Sign in to HUD with your atproto account</h1>
{intro}
<ul>
<li>write records you ask for, as likes and reposts, to your repository;</li>
<li>read personal feeds for you, as your timeline and notifications.</li>
</ul>
{error}
<form method="post" action="/oauth/authorize">
<input type="hidden" name="request" value="{id}">
<label for="handle">Your handle</label>
<input id="handle" name="handle" value="{hint}" placeholder="alice.bsky.social" autocomplete="username" autocapitalize="none" spellcheck="false" required autofocus>
<button type="submit">Continue</button>
<p class="create">Don't have an account? <button type="submit" name="create" value="1" formnovalidate>Create one</button></p>
</form>
<p class="note">You sign in at your account's own server; HUD never sees your password. By continuing you agree to HUD's <a href="/terms">Terms</a>, <a href="/privacy">Privacy Policy</a> and <a href="/guidelines">Community Guidelines</a>.</p>"#,
        id = esc(&p.id),
        hint = esc(p.login_hint.as_deref().unwrap_or_default()),
    );
    let mut r = page(status, "Sign in to HUD", &body);
    if allow_private {
        r.headers_mut().insert(
            header::CONTENT_SECURITY_POLICY,
            axum::http::HeaderValue::from_static(PAGE_CSP_PRIVATE),
        );
    }
    r
}

/// A page saying a sign-in cannot go on, and why.
fn error_page(status: StatusCode, why: &str) -> Response {
    let body = format!(
        "<h1>HUD can't sign you in</h1>\n<p class=\"error\">{}</p>\n<p class=\"note\">Start again from the app that sent you here.</p>",
        esc(why)
    );
    page(status, "HUD can't sign you in", &body)
}

/// A page saying the workspace's sign-in did not finish, and why, with a
/// way back to the workspace to start again.
fn web_error_page(status: StatusCode, why: &str) -> Response {
    let body = format!(
        "<h1>HUD can't sign you in</h1>\n<p class=\"error\">{}</p>\n<p><a href=\"/workspace\">Try again</a></p>",
        esc(why)
    );
    page(status, "HUD can't sign you in", &body)
}

#[cfg(test)]
mod tests {
    use super::*;
    use hud_core::Config;
    use tower::ServiceExt;

    #[test]
    fn pages_escape_what_others_wrote() {
        let p = Pending {
            id: "r1".into(),
            client: "<script>alert(1)</script>".into(),
            login_hint: Some("\"><b>".into()),
            straight: false,
            create: false,
        };
        let r = sign_in_page(false, StatusCode::OK, &p, Some("a & b"));
        assert_eq!(r.headers()[header::CONTENT_SECURITY_POLICY], PAGE_CSP);
        // With private addresses allowed, the form may go on to a local PDS
        // on plain http; without, only https.
        let local = sign_in_page(true, StatusCode::OK, &p, None);
        assert_eq!(
            local.headers()[header::CONTENT_SECURITY_POLICY],
            PAGE_CSP_PRIVATE
        );
        let html =
            futures::executor::block_on(axum::body::to_bytes(r.into_body(), usize::MAX)).unwrap();
        let html = String::from_utf8(html.to_vec()).unwrap();
        assert!(!html.contains("<script>"));
        assert!(html.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
        assert!(html.contains("value=\"&quot;&gt;&lt;b&gt;\""));
        assert!(html.contains("a &amp; b"));
        assert!(html.contains("name=\"request\" value=\"r1\""));
        // The workspace's failed sign-in leads back to the workspace.
        let html = futures::executor::block_on(axum::body::to_bytes(
            web_error_page(StatusCode::BAD_REQUEST, "no").into_body(),
            usize::MAX,
        ))
        .unwrap();
        let html = String::from_utf8(html.to_vec()).unwrap();
        assert!(html.contains("<a href=\"/workspace\">Try again</a>"));
    }

    /// `GET /oauth/authorize` through the router, with `extra` params: its
    /// status and HTML, or where it sends the browser.
    async fn authorize(
        hud: &Arc<Hud>,
        client_id: &str,
        redirect: &str,
        extra: &[(&str, &str)],
    ) -> (StatusCode, String) {
        let mut q = url::form_urlencoded::Serializer::new(String::new());
        q.extend_pairs([
            ("client_id", client_id),
            ("redirect_uri", redirect),
            ("response_type", "code"),
            ("code_challenge", &atproto::jose::sha256("verifier")),
            ("code_challenge_method", "S256"),
            ("resource", "https://hud.example/mcp"),
        ]);
        q.extend_pairs(extra);
        let req = axum::http::Request::get(format!("/oauth/authorize?{}", q.finish()))
            .body(axum::body::Body::empty())
            .unwrap();
        let r = crate::router(hud.clone(), None).oneshot(req).await.unwrap();
        let status = r.status();
        if let Some(to) = r.headers().get(header::LOCATION) {
            return (status, to.to_str().unwrap().to_string());
        }
        let html = axum::body::to_bytes(r.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, String::from_utf8(html.to_vec()).unwrap())
    }

    #[tokio::test]
    async fn the_app_naming_its_account_skips_the_page() {
        // No PLC to reach (a loopback address, refused): every account
        // named fails to resolve, offline.
        let data_dir =
            std::env::temp_dir().join(format!("hud-oauth-tests-{}", atproto::jose::random(6)));
        let hud = Hud::new(Config {
            port: 0,
            bind: "::".parse().unwrap(),
            public_origin: "https://hud.example".into(),
            cache_dir: data_dir.join("cache"),
            data_dir,
            oauth: true,
            oauth_scope: hud_core::scope::asked(hud_core::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            spaces: false,
            plc_url: "http://127.0.0.1:9".into(),
            handle_resolver: None,
            allow_private: false,
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            backlinks: hud_core::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: None,
            relay: None,
            // Unreachable, offline: a loopback address, refused.
            sign_up_pds: "http://127.0.0.1:9".into(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: hud_core::logs::KEEP,
        })
        .unwrap();
        let did = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
        // HUD's own app, naming its account: on to its server, tried; here
        // that fails, so sent back to the app, saying why, for its own
        // screen to show.
        let app = hud.auth().unwrap().app_client_id();
        let hinted = [("login_hint", did)];
        let (status, to) = authorize(&hud, &app, hud_core::oauth::APP_REDIRECT, &hinted).await;
        assert_eq!(status, StatusCode::SEE_OTHER, "{to}");
        let back: std::collections::HashMap<String, String> = url::Url::parse(&to)
            .unwrap()
            .query_pairs()
            .into_owned()
            .collect();
        assert!(to.starts_with(hud_core::oauth::APP_REDIRECT), "{to}");
        assert_eq!(back["error"], "access_denied");
        assert_eq!(
            back["error_description"],
            format!("{did} does not resolve to an account")
        );
        // An Android app on hudkit, sent back to its own application ID's
        // scheme: the same, at its redirect; another path refused outright.
        let android = "social.grain:/oauth/callback";
        let (status, to) = authorize(&hud, &app, android, &hinted).await;
        assert_eq!(status, StatusCode::SEE_OTHER, "{to}");
        assert!(to.starts_with(android), "{to}");
        let (status, _) = authorize(&hud, &app, "social.grain:/elsewhere", &hinted).await;
        assert_ne!(status, StatusCode::SEE_OTHER);
        // Any other client: the page, naming it, nothing tried.
        let body = json!({ "redirect_uris": ["http://127.0.0.1/cb"], "client_name": "Test host",
            "token_endpoint_auth_method": "none" });
        let other = hud.register(body.to_string().as_bytes()).unwrap();
        let other = other["client_id"].as_str().unwrap();
        let (status, html) = authorize(&hud, other, "http://127.0.0.1/cb", &hinted).await;
        assert_eq!(status, StatusCode::OK, "{html}");
        assert!(!html.contains("role=\"alert\""), "{html}");
        assert!(html.contains("Test host") && html.contains(&format!("value=\"{did}\"")));
        // The page offers "Create one", and links to the policies.
        assert!(html.contains(r#"name="create" value="1""#), "{html}");
        assert!(html.contains(r#"href="/terms""#) && html.contains(r#"href="/privacy""#));
        // HUD's own app asking for a new account: on to the sign-up PDS,
        // tried; here that fails, so sent back, saying why.
        let create = [("prompt", "create")];
        let (status, to) = authorize(&hud, &app, hud_core::oauth::APP_REDIRECT, &create).await;
        assert_eq!(status, StatusCode::SEE_OTHER, "{to}");
        assert!(
            to.contains("Accounts+can%27t+be+made+at+127.0.0.1+now%3B+try+again+later"),
            "{to}"
        );
        // Any other client's asking: ignored, the page, nothing tried.
        let (status, html) = authorize(&hud, other, "http://127.0.0.1/cb", &create).await;
        assert_eq!(status, StatusCode::OK, "{html}");
        assert!(!html.contains("role=\"alert\""), "{html}");
    }

    use axum::body::Body;
    use axum::http::{HeaderMap, Request};
    use std::sync::Mutex;

    const ORIGIN: &str = "https://hud.example";
    const DID: &str = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
    const REDIRECT: &str = "http://127.0.0.1/cb";

    /// An account's PDS and authorization server, as little as signs in:
    /// its DID document, its metadata, PAR (the last `state` pushed kept),
    /// and a token endpoint answering tokens for any code.
    async fn account_server() -> (String, Arc<Mutex<Option<String>>>) {
        use axum::extract::Path;
        use axum::routing::post;
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let pushed = Arc::new(Mutex::new(None));
        let form = |body: &str| -> std::collections::HashMap<String, String> {
            url::form_urlencoded::parse(body.as_bytes())
                .into_owned()
                .collect()
        };
        let doc = {
            let base = base.clone();
            move |Path(did): Path<String>| {
                let base = base.clone();
                async move {
                    axum::Json(json!({ "id": did, "service": [{ "id": "#atproto_pds",
                        "type": "AtprotoPersonalDataServer", "serviceEndpoint": base }] }))
                }
            }
        };
        let resource = {
            let base = base.clone();
            move || {
                let base = base.clone();
                async move { axum::Json(json!({ "authorization_servers": [base] })) }
            }
        };
        let meta = {
            let b = base.clone();
            move || {
                let b = b.clone();
                async move {
                    axum::Json(json!({
                        "issuer": b,
                        "authorization_endpoint": format!("{b}/authorize"),
                        "pushed_authorization_request_endpoint": format!("{b}/par"),
                        "token_endpoint": format!("{b}/token"),
                        "dpop_signing_alg_values_supported": ["ES256"],
                        "token_endpoint_auth_methods_supported": ["private_key_jwt"],
                    }))
                }
            }
        };
        let par = {
            let pushed = pushed.clone();
            move |body: String| {
                *pushed.lock().unwrap() = form(&body).remove("state");
                async {
                    (
                        StatusCode::CREATED,
                        axum::Json(
                            json!({ "request_uri": "urn:ietf:params:oauth:request_uri:r1" }),
                        ),
                    )
                }
            }
        };
        let token = || async {
            axum::Json(json!({ "access_token": "at", "refresh_token": "rt",
                "token_type": "DPoP", "scope": "atproto transition:generic",
                "sub": DID, "expires_in": 3600 }))
        };
        let app = Router::new()
            .route("/{did}", get(doc))
            .route("/.well-known/oauth-protected-resource", get(resource))
            .route("/.well-known/oauth-authorization-server", get(meta))
            .route("/par", post(par))
            .route("/token", post(token));
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (base, pushed)
    }

    /// A server with sign-in on, and the account server it signs in at.
    async fn server() -> (Arc<Hud>, String, Arc<Mutex<Option<String>>>) {
        let (base, pushed) = account_server().await;
        let data_dir =
            std::env::temp_dir().join(format!("hud-oauth-routes-{}", atproto::jose::random(6)));
        let hud = Hud::new(Config {
            port: 0,
            bind: "::".parse().unwrap(),
            public_origin: ORIGIN.into(),
            cache_dir: data_dir.join("cache"),
            data_dir,
            oauth: true,
            oauth_scope: hud_core::scope::asked(hud_core::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            sign_up_pds: base.clone(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: hud_core::logs::KEEP,
            spaces: false,
            plc_url: base.clone(),
            handle_resolver: None,
            allow_private: true,
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            backlinks: hud_core::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: None,
            relay: None,
        })
        .unwrap();
        (hud, base, pushed)
    }

    /// A request through the router whole: its status, headers and body.
    async fn send(hud: &Arc<Hud>, req: Request<Body>) -> (StatusCode, HeaderMap, String) {
        let r = crate::router(hud.clone(), None).oneshot(req).await.unwrap();
        let (status, headers) = (r.status(), r.headers().clone());
        let body = axum::body::to_bytes(r.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, headers, String::from_utf8(body.to_vec()).unwrap())
    }

    fn get_of(path: &str) -> Request<Body> {
        Request::get(path).body(Body::empty()).unwrap()
    }

    fn post_of(path: &str, kind: &str, body: impl Into<Body>) -> Request<Body> {
        Request::post(path)
            .header("content-type", kind)
            .body(body.into())
            .unwrap()
    }

    const FORM: &str = "application/x-www-form-urlencoded";

    fn form(pairs: &[(&str, &str)]) -> String {
        url::form_urlencoded::Serializer::new(String::new())
            .extend_pairs(pairs)
            .finish()
    }

    fn json_of(body: &str) -> Json {
        serde_json::from_str(body).unwrap()
    }

    /// The request id a sign-in page's form carries.
    fn request_of(html: &str) -> String {
        let (_, rest) = html.split_once("name=\"request\" value=\"").unwrap();
        rest.split('"').next().unwrap().to_string()
    }

    /// A URL's query's pairs.
    fn query(url: &str) -> std::collections::HashMap<String, String> {
        url::Url::parse(url)
            .unwrap()
            .query_pairs()
            .into_owned()
            .collect()
    }

    #[tokio::test]
    async fn metadata_documents_any_origin_reads() {
        let (hud, _, _) = server().await;
        for (path, key, value) in [
            (
                "/.well-known/oauth-protected-resource",
                "resource",
                json!("https://hud.example/mcp"),
            ),
            (
                "/.well-known/oauth-protected-resource/mcp",
                "resource",
                json!("https://hud.example/mcp"),
            ),
            (
                "/.well-known/oauth-authorization-server",
                "issuer",
                json!(ORIGIN),
            ),
            (
                "/oauth/client-metadata.json",
                "client_id",
                json!("https://hud.example/oauth/client-metadata.json"),
            ),
            (
                "/oauth/app-client.json",
                "client_name",
                json!("HUD for iOS"),
            ),
            (
                "/oauth/jwks.json",
                "keys",
                json!(hud.auth().unwrap().jwks()["keys"]),
            ),
        ] {
            let (status, h, body) = send(&hud, get_of(path)).await;
            assert_eq!(status, StatusCode::OK, "{path}");
            assert_eq!(h[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
            assert_eq!(h[header::CACHE_CONTROL], "public, max-age=300");
            assert_eq!(h[header::CONTENT_TYPE], "application/json");
            assert_eq!(json_of(&body)[key], value, "{path}");
        }
        // A browser may ask before it posts to the token, revocation and
        // registration endpoints.
        for path in ["/oauth/token", "/oauth/revoke", "/oauth/register"] {
            let asked = Request::options(path).body(Body::empty()).unwrap();
            let (status, h, _) = send(&hud, asked).await;
            assert_eq!(status, StatusCode::NO_CONTENT);
            assert_eq!(h[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
            assert_eq!(h[header::ACCESS_CONTROL_ALLOW_METHODS], "POST");
            assert_eq!(
                h[header::ACCESS_CONTROL_ALLOW_HEADERS],
                "content-type, authorization"
            );
            assert_eq!(h[header::ACCESS_CONTROL_MAX_AGE], "86400");
        }
    }

    #[tokio::test]
    async fn an_mcp_client_signs_in_and_out() {
        let (hud, base, pushed) = server().await;
        let big = "x".repeat(MAX_BODY + 1);
        // Registered, its answer readable from any origin, never kept.
        let (status, _, body) = send(
            &hud,
            post_of("/oauth/register", "application/json", big.clone()),
        )
        .await;
        assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
        assert_eq!(json_of(&body)["error"], "invalid_client_metadata");
        let (status, _, body) =
            send(&hud, post_of("/oauth/register", "application/json", "{}")).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(json_of(&body)["error"], "invalid_client_metadata");
        let client = json!({ "redirect_uris": [REDIRECT], "client_name": "Test host",
            "grant_types": ["authorization_code", "refresh_token"] });
        let (status, h, body) = send(
            &hud,
            post_of("/oauth/register", "application/json", client.to_string()),
        )
        .await;
        assert_eq!(status, StatusCode::CREATED);
        assert_eq!(h[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
        assert_eq!(h[header::CACHE_CONTROL], "no-store");
        assert_eq!(h[header::PRAGMA], "no-cache");
        let id = json_of(&body)["client_id"].as_str().unwrap().to_string();
        // The authorization request: its sign-in page, naming the client; a
        // refusal sent back to it; or a page where nothing can be.
        let verifier = atproto::jose::random(32);
        let challenge = atproto::jose::sha256(&verifier);
        let asked = |response_type: &str| {
            format!(
                "/oauth/authorize?{}",
                form(&[
                    ("client_id", &id),
                    ("redirect_uri", REDIRECT),
                    ("response_type", response_type),
                    ("code_challenge", &challenge),
                    ("code_challenge_method", "S256"),
                    ("resource", "https://hud.example/mcp"),
                    ("state", "s1"),
                ])
            )
        };
        let (status, h, html) = send(&hud, get_of(&asked("code"))).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(h[header::CONTENT_SECURITY_POLICY], PAGE_CSP_PRIVATE);
        assert_eq!(h[header::X_FRAME_OPTIONS], "DENY");
        assert!(html.contains("<span class=\"client\">Test host</span> wants to use HUD"));
        let request = request_of(&html);
        let (status, h, _) = send(&hud, get_of(&asked("token"))).await;
        assert_eq!(status, StatusCode::SEE_OTHER);
        assert_eq!(h[header::CACHE_CONTROL], "no-store");
        assert_eq!(h[header::REFERRER_POLICY], "no-referrer");
        let to = h[header::LOCATION].to_str().unwrap();
        assert!(to.starts_with(REDIRECT), "{to}");
        assert_eq!(query(to)["error"], "unsupported_response_type");
        let (status, _, html) = send(&hud, get_of("/oauth/authorize")).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(html.contains("<p class=\"error\">client_id is required</p>"));
        // The sign-in page's form: too large, not a form, given twice, or
        // for a request gone, it has expired.
        let expired = "This sign-in has expired or was already used; start again from your app.";
        let (status, _, html) = send(&hud, post_of("/oauth/authorize", FORM, big.clone())).await;
        assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
        assert!(html.contains("The form is too large."));
        for (kind, body) in [
            (
                "text/plain",
                form(&[("request", &request), ("handle", DID)]),
            ),
            (
                FORM,
                form(&[
                    ("request", &request),
                    ("request", &request),
                    ("handle", DID),
                ]),
            ),
            (FORM, form(&[("request", "gone"), ("handle", DID)])),
        ] {
            let (status, _, html) = send(&hud, post_of("/oauth/authorize", kind, body)).await;
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert!(html.contains(expired), "{html}");
        }
        // A handle that is none: the page again, saying so, the handle kept.
        let (status, _, html) = send(
            &hud,
            post_of(
                "/oauth/authorize",
                FORM,
                form(&[("request", &request), ("handle", "no one")]),
            ),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(html.contains("no one is not a handle or a DID"));
        assert!(html.contains("value=\"no one\""));
        assert_eq!(request_of(&html), request);
        // The account named: on to its server's authorization page.
        let (status, h, _) = send(
            &hud,
            post_of(
                "/oauth/authorize",
                FORM,
                form(&[("request", &request), ("handle", DID)]),
            ),
        )
        .await;
        assert_eq!(status, StatusCode::SEE_OTHER);
        let to = h[header::LOCATION].to_str().unwrap();
        assert!(to.starts_with(&format!("{base}/authorize?")), "{to}");
        // Back from it: on to the client with HUD's code.
        let state = pushed.lock().unwrap().clone().unwrap();
        let back = format!(
            "/oauth/callback?{}",
            form(&[("state", &state), ("iss", &base), ("code", "good")])
        );
        let (status, h, _) = send(&hud, get_of(&back)).await;
        assert_eq!(status, StatusCode::SEE_OTHER);
        let to = h[header::LOCATION].to_str().unwrap();
        assert!(to.starts_with(REDIRECT), "{to}");
        let code = query(to)["code"].clone();
        // The same answer again is one HUD no longer waits for.
        let (status, _, html) = send(&hud, get_of(&back)).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(html.contains("This sign-in has expired or was already used"));
        // The code exchanged for HUD's tokens, once.
        let exchange = form(&[
            ("grant_type", "authorization_code"),
            ("client_id", &id),
            ("code", &code),
            ("redirect_uri", REDIRECT),
            ("code_verifier", &verifier),
        ]);
        let (status, h, body) = send(&hud, post_of("/oauth/token", FORM, exchange.clone())).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(h[header::CACHE_CONTROL], "no-store");
        let tokens = json_of(&body);
        assert_eq!(tokens["sub"], DID);
        let access = tokens["access_token"].as_str().unwrap().to_string();
        let (status, _, body) = send(&hud, post_of("/oauth/token", FORM, big.clone())).await;
        assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
        assert_eq!(
            json_of(&body),
            json!({ "error": "invalid_request", "error_description": "The body is too large" })
        );
        // Revoked, by a JSON body: the token names no account after.
        let auth = hud.auth().unwrap();
        assert!(auth.account(&access).is_some());
        let (status, _, body) = send(&hud, post_of("/oauth/revoke", FORM, big)).await;
        assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
        assert_eq!(json_of(&body)["error"], "invalid_request");
        let (status, _, body) = send(&hud, post_of("/oauth/revoke", FORM, "")).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(json_of(&body)["error_description"], "token is required");
        let revoke = json!({ "token": access }).to_string();
        let (status, _, body) =
            send(&hud, post_of("/oauth/revoke", "application/json", revoke)).await;
        assert_eq!((status, json_of(&body)), (StatusCode::OK, json!({})));
        assert!(auth.account(&access).is_none());
        // The code, used again, is refused.
        let (status, _, body) = send(&hud, post_of("/oauth/token", FORM, exchange)).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(json_of(&body)["error"], "invalid_grant");
    }

    #[tokio::test]
    async fn the_workspace_signs_in_with_a_cookie() {
        let (hud, base, pushed) = server().await;
        let authorize = &format!("{base}/authorize?");
        let started = |hud: Arc<Hud>| async move {
            let asked = Request::post("/workspace/signin")
                .header("content-type", "application/json")
                .header("x-hud", "1")
                .header(header::ORIGIN, ORIGIN)
                .body(Body::from(json!({ "handle": DID }).to_string()))
                .unwrap();
            let (status, _, body) = send(&hud, asked).await;
            assert_eq!(status, StatusCode::OK, "{body}");
            let to = json_of(&body)["url"].as_str().unwrap().to_string();
            assert!(to.starts_with(authorize), "{to}");
        };
        // Back from the account's server: to the workspace, its cookie set.
        started(hud.clone()).await;
        let state = pushed.lock().unwrap().clone().unwrap();
        let back = format!(
            "/oauth/callback?{}",
            form(&[("state", &state), ("iss", &base), ("code", "good")])
        );
        let (status, h, _) = send(&hud, get_of(&back)).await;
        assert_eq!(status, StatusCode::SEE_OTHER);
        assert_eq!(h[header::LOCATION], "/workspace");
        let cookie = h[header::SET_COOKIE].to_str().unwrap();
        let value = cookie
            .strip_prefix("hud_session=")
            .and_then(|c| c.split(';').next())
            .unwrap();
        assert_eq!(hud.auth().unwrap().web_account(value).unwrap().did, DID);
        // Signed in again with that cookie still set: the session it names
        // ends, and the new one takes its place.
        started(hud.clone()).await;
        let state = pushed.lock().unwrap().clone().unwrap();
        let back = format!(
            "/oauth/callback?{}",
            form(&[("state", &state), ("iss", &base), ("code", "good")])
        );
        let mut again = get_of(&back);
        let was = format!("hud_session={value}").parse().unwrap();
        again.headers_mut().insert(header::COOKIE, was);
        let (status, h2, _) = send(&hud, again).await;
        assert_eq!(status, StatusCode::SEE_OTHER);
        assert!(h2.contains_key(header::SET_COOKIE));
        assert!(hud.auth().unwrap().web_account(value).is_none());
        // Refused there: HUD's own page, with a way to start again.
        started(hud.clone()).await;
        let state = pushed.lock().unwrap().clone().unwrap();
        let back = format!(
            "/oauth/callback?{}",
            form(&[("state", &state), ("error", "access_denied")])
        );
        let (status, h, html) = send(&hud, get_of(&back)).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(h[header::CONTENT_SECURITY_POLICY], PAGE_CSP);
        assert!(html.contains("The sign-in at your account&#39;s server did not finish"));
        assert!(html.contains("<a href=\"/workspace\">Try again</a>"));
    }

    #[tokio::test]
    async fn the_app_naming_its_account_and_create_one_go_on_to_a_server() {
        let (hud, base, _) = server().await;
        let authorize = format!("{base}/authorize?");
        let challenge = atproto::jose::sha256("verifier");
        let asked = |client: &str, redirect: &str, extra: &[(&str, &str)]| {
            let mut pairs = vec![
                ("client_id", client),
                ("redirect_uri", redirect),
                ("response_type", "code"),
                ("code_challenge", &challenge),
                ("code_challenge_method", "S256"),
                ("resource", "https://hud.example/mcp"),
            ];
            pairs.extend_from_slice(extra);
            get_of(&format!("/oauth/authorize?{}", form(&pairs)))
        };
        // HUD's own app naming its account: on to its server.
        let app = hud.auth().unwrap().app_client_id();
        let hinted = asked(&app, hud_core::oauth::APP_REDIRECT, &[("login_hint", DID)]);
        let (status, h, _) = send(&hud, hinted).await;
        assert_eq!(status, StatusCode::SEE_OTHER);
        assert!(
            h[header::LOCATION]
                .to_str()
                .unwrap()
                .starts_with(&authorize)
        );
        // The page's "Create one": on to the sign-up PDS's server.
        let client = json!({ "redirect_uris": [REDIRECT], "client_name": "Test host",
            "token_endpoint_auth_method": "none" });
        let client = hud.register(client.to_string().as_bytes()).unwrap();
        let id = client["client_id"].as_str().unwrap();
        let (_, _, html) = send(&hud, asked(id, REDIRECT, &[])).await;
        let create = form(&[("request", &request_of(&html)), ("create", "1")]);
        let (status, h, _) = send(&hud, post_of("/oauth/authorize", FORM, create)).await;
        assert_eq!(status, StatusCode::SEE_OTHER);
        assert!(
            h[header::LOCATION]
                .to_str()
                .unwrap()
                .starts_with(&authorize)
        );
        // The workspace's "Create one" too.
        let created = Request::post("/workspace/signin")
            .header("content-type", "application/json")
            .header("x-hud", "1")
            .header(header::ORIGIN, ORIGIN)
            .body(Body::from(json!({ "create": true }).to_string()))
            .unwrap();
        let (status, _, body) = send(&hud, created).await;
        assert_eq!(status, StatusCode::OK, "{body}");
        let to = json_of(&body)["url"].as_str().unwrap().to_string();
        assert!(to.starts_with(&authorize), "{to}");
    }
}