//! 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> { 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 { 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>) -> Result { auth_document(&hud, Auth::protected_resource) } async fn authorization_server(State(hud): State>) -> Result { auth_document(&hud, Auth::authorization_server) } async fn client_metadata(State(hud): State>) -> Result { auth_document(&hud, Auth::client_metadata) } async fn app_client_metadata(State(hud): State>) -> Result { auth_document(&hud, Auth::app_client_metadata) } async fn jwks(State(hud): State>) -> Result { 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>, 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>, 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>, 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, 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>, 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>, 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>, 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("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), 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#" {title}
{body}
"#, 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#""#, esc(e))) .unwrap_or_default(); let intro = format!( r#"

{} wants to use HUD as you. Signed in, HUD will be able to:

"#, esc(&p.client) ); let body = format!( r#"

Sign in to HUD with your atproto account

{intro}
  • write records you ask for, as likes and reposts, to your repository;
  • read personal feeds for you, as your timeline and notifications.
{error}

Don't have an account?

You sign in at your account's own server; HUD never sees your password. By continuing you agree to HUD's Terms, Privacy Policy and Community Guidelines.

"#, 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!( "

HUD can't sign you in

\n

{}

\n

Start again from the app that sent you here.

", 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!( "

HUD can't sign you in

\n

{}

\n

Try again

", 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: "".into(), login_hint: Some("\">".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("