From 86898857d6f6089c365ec7a5c085784769df1c69 Mon Sep 17 00:00:00 2001 From: Christian Grothoff Date: Wed, 18 Nov 2026 10:51:22 +0100 Subject: [PATCH 6/9] api: let routes answer OPTIONS requests that are not CORS preflights tower-http's CorsLayer answered every OPTIONS request as a preflight, so a route's own OPTIONS handler never ran; a tus server, for one, could not tell its clients the largest upload it takes. The CORS middleware now answers only real preflights, those with Access-Control-Request-Method, and passes every other OPTIONS request to its route. A preflight is allowed the request headers that it names in Access-Control-Request-Headers. The wildcard "*" that CorsLayer sent does not cover Authorization (Fetch standard), so browsers refused every request with a bearer token from another origin. Assisted by LLM --- common/taler-api/Cargo.toml | 1 - common/taler-api/src/api.rs | 151 ++++++++++++++++++++++++++++++++---- 2 files changed, 138 insertions(+), 14 deletions(-) diff --git a/common/taler-api/Cargo.toml b/common/taler-api/Cargo.toml index 2ea77e4..6bed8d6 100644 --- a/common/taler-api/Cargo.toml +++ b/common/taler-api/Cargo.toml @@ -16,7 +16,6 @@ listenfd = "1.0.0" dashmap = "6.1" http-body-util.workspace = true zlib-rs = "0.6.3" -tower-http = { version = "0.7", features = ["cors"] } tokio = { workspace = true, features = ["signal"] } rand.workspace = true serde.workspace = true diff --git a/common/taler-api/src/api.rs b/common/taler-api/src/api.rs index 38617aa..789841b 100644 --- a/common/taler-api/src/api.rs +++ b/common/taler-api/src/api.rs @@ -24,6 +24,7 @@ use std::{ use axum::{ extract::{MatchedPath, Request, State}, + http::{HeaderValue, Method, header}, middleware::{self, Next}, response::Response, }; @@ -36,7 +37,6 @@ use taler_common::{ types::amount::{Amount, Currency}, }; use tokio::signal; -use tower_http::cors::{Any, CorsLayer}; use tracing::{Level, debug, info}; use wire::WireGateway; @@ -123,12 +123,7 @@ impl TalerRouter for Router { fn finalize(self) -> Router { self.method_not_allowed_fallback(async || failure_code(ErrorCode::GENERIC_METHOD_INVALID)) .fallback(async || failure_code(ErrorCode::GENERIC_ENDPOINT_UNKNOWN)) - .layer( - CorsLayer::new() - .allow_origin(Any) - .allow_methods(Any) - .allow_headers(Any), - ) + .layer(middleware::from_fn(cors_middleware)) .layer(middleware::from_fn(logger_middleware)) } @@ -165,6 +160,57 @@ impl TalerRouter for Router { } } +/// Allow cross-origin requests from any origin, with any method and headers. +/// +/// Only a CORS preflight, an OPTIONS request with Access-Control-Request-Method +/// (Fetch standard, "CORS-preflight request"), is answered here. Any other +/// OPTIONS request goes to its route like every other method, so that a route +/// can answer OPTIONS itself (tus, for example, announces its limits there); +/// tower-http's CorsLayer answered every OPTIONS request as a preflight. +/// +/// A preflight is allowed the request headers that it names in +/// Access-Control-Request-Headers, as CorsLayer's `mirror_request` does. The +/// wildcard `*` does not cover `Authorization` (Fetch standard, "CORS +/// non-wildcard request-header name"), so with `*` alone a browser refuses +/// every request with a bearer token from another origin. A preflight that +/// names no headers gets `*`. +async fn cors_middleware(request: Request, next: Next) -> Response { + const ANY: HeaderValue = HeaderValue::from_static("*"); + let preflight = request.method() == Method::OPTIONS + && request + .headers() + .contains_key(header::ACCESS_CONTROL_REQUEST_METHOD); + let mut response = if preflight { + let requested: Vec = request + .headers() + .get_all(header::ACCESS_CONTROL_REQUEST_HEADERS) + .iter() + .cloned() + .collect(); + let mut response = Response::default(); + let headers = response.headers_mut(); + headers.insert(header::ACCESS_CONTROL_ALLOW_METHODS, ANY); + if requested.is_empty() { + headers.insert(header::ACCESS_CONTROL_ALLOW_HEADERS, ANY); + } + for value in requested { + headers.append(header::ACCESS_CONTROL_ALLOW_HEADERS, value); + } + response + } else { + next.run(request).await + }; + let headers = response.headers_mut(); + headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, ANY); + headers.append( + header::VARY, + HeaderValue::from_static( + "origin, access-control-request-method, access-control-request-headers", + ), + ); + response +} + struct LifetimeMiddlewareState { lifetime: AtomicU32, notify: Arc, @@ -357,12 +403,91 @@ mod tests { } async fn send(router: &Router, method: Method, uri: &str) -> StatusCode { - let request = Request::builder() - .method(method) - .uri(uri) - .body(Body::empty()) - .unwrap(); - router.clone().oneshot(request).await.unwrap().status() + request(router, method, uri, &[]).await.status() + } + + async fn request( + router: &Router, + method: Method, + uri: &str, + headers: &[(&str, &str)], + ) -> Response { + let mut request = Request::builder().method(method).uri(uri); + for (k, v) in headers { + request = request.header(*k, *v); + } + let request = request.body(Body::empty()).unwrap(); + router.clone().oneshot(request).await.unwrap() + } + + fn header<'a>(response: &'a Response, name: &str) -> Option<&'a str> { + response.headers().get(name).map(|v| v.to_str().unwrap()) + } + + #[tokio::test] + async fn cors_leaves_plain_options_to_the_route() { + let (_captured, _guard) = capture(); + let router = Router::new() + .route( + "/upload", + get(async || "ok") + .options(async || (StatusCode::NO_CONTENT, [("x-limit", "1024")])), + ) + .route("/config", get(async || "ok")) + .finalize(); + let origin = ("origin", "https://example.com"); + let preflight = [origin, ("access-control-request-method", "POST")]; + + // A preflight is answered by the CORS layer, not by the route. + for uri in ["/upload", "/config", "/unknown"] { + let r = request(&router, Method::OPTIONS, uri, &preflight).await; + assert_eq!(r.status(), StatusCode::OK, "{uri}"); + assert_eq!(header(&r, "access-control-allow-origin"), Some("*")); + assert_eq!(header(&r, "access-control-allow-methods"), Some("*")); + assert_eq!(header(&r, "access-control-allow-headers"), Some("*")); + assert_eq!(header(&r, "x-limit"), None); + } + + // Any other OPTIONS request reaches the route, with or without Origin. + for headers in [&[][..], &[origin][..]] { + let r = request(&router, Method::OPTIONS, "/upload", headers).await; + assert_eq!(r.status(), StatusCode::NO_CONTENT); + assert_eq!(header(&r, "x-limit"), Some("1024")); + assert_eq!(header(&r, "access-control-allow-origin"), Some("*")); + assert_eq!(header(&r, "access-control-allow-methods"), None); + } + let r = request(&router, Method::OPTIONS, "/config", &[origin]).await; + assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED); + assert_eq!(header(&r, "access-control-allow-origin"), Some("*")); + + // A preflight that names request headers is allowed exactly those: + // `*` would not cover Authorization. + let asking = [ + origin, + ("access-control-request-method", "PATCH"), + ( + "access-control-request-headers", + "authorization,content-type,tus-resumable,upload-offset", + ), + ]; + let r = request(&router, Method::OPTIONS, "/upload", &asking).await; + assert_eq!(r.status(), StatusCode::OK); + assert_eq!( + header(&r, "access-control-allow-headers"), + Some("authorization,content-type,tus-resumable,upload-offset") + ); + assert_eq!(header(&r, "access-control-allow-methods"), Some("*")); + assert_eq!(header(&r, "access-control-allow-origin"), Some("*")); + assert!(header(&r, "vary").is_some_and(|v| v.contains("access-control-request-headers"))); + + // Ordinary requests get the CORS headers too. + let r = request(&router, Method::GET, "/config", &[origin]).await; + assert_eq!(r.status(), StatusCode::OK); + assert_eq!(header(&r, "access-control-allow-origin"), Some("*")); + assert!(header(&r, "vary").is_some_and(|v| v.contains("origin"))); + let r = request(&router, Method::GET, "/unknown", &[origin]).await; + assert_eq!(r.status(), StatusCode::NOT_FOUND); + assert_eq!(header(&r, "access-control-allow-origin"), Some("*")); } #[tokio::test] -- 2.47.3