View Issue Details

IDProjectCategoryView StatusLast Update
0012181Talertaler-rustpublic2026-11-18 15:57
Reporterbot-cg [agent]  
ImplementerAntoine A  
Fast-trackYes — The control, the release and the deployment are skipped: whoever implemented this change verifies and closes it themselves.
PrioritynormalSeveritytrivial 
Status implementing 
Target Version1.7 
Summary0012181: taler-api: let routes answer OPTIONS requests that are not CORS preflights
Descriptiontower-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.

Files: common/taler-api/Cargo.toml, common/taler-api/src/api.rs (paths in the taler-rust tree). The patch is attached; it is number 6 of the series in the parent issue, against taler-rust 2c678873, and applies on top of the patches before it.
TagsNo tags attached.
Attached Files
0006-api-let-routes-answer-OPTIONS-requests-that-are-not-.patch (9,373 bytes)   
From 86898857d6f6089c365ec7a5c085784769df1c69 Mon Sep 17 00:00:00 2001
From: Christian Grothoff <christian@grothoff.org>
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<HeaderValue> = 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<tokio::sync::Notify>,
@@ -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

Required notifications

Address or linkRemarkAdded byNotifiedActions

Relationships

child of 0012175 implementing taler-api: nine patches that Beekeeper carries on its vendored copy (patch series attached) 

Activities

bot-cg [agent]

2026-11-18 14:42

updater   ~0030580

Correction: this issue was filed in the category "exchange" by mistake. It concerns taler-rust (common/taler-api or common/taler-common), like its parent 0012175, and belongs in the category "taler-rust". This reporter account cannot change the category; could someone with updater rights move it?

Issue History

Date ModifiedUsernameFieldChange
2026-11-18 14:41bot-cgNew Issue
2026-11-18 14:41bot-cgRelationship addedchild of 0012175
2026-11-18 14:41bot-cgImplementer => oec
2026-11-18 14:41bot-cgReviewer => Christian Grothoff
2026-11-18 14:41bot-cgRelease signed by => Florian Dold
2026-11-18 14:41bot-cgDeployed by => Christian Grothoff
2026-11-18 14:41bot-cgVerifier => oec
2026-11-18 14:41bot-cgCommunicator => CM_7
2026-11-18 14:42bot-cgFile Added: 0006-api-let-routes-answer-OPTIONS-requests-that-are-not-.patch
2026-11-18 14:42bot-cgNote Added: 0030580
2026-11-18 15:53Christian GrothoffImplementeroec => Antoine A
2026-11-18 15:53Christian GrothoffReviewerChristian Grothoff => Florian Dold
2026-11-18 15:53Christian GrothoffSeverityminor => trivial
2026-11-18 15:53Christian GrothoffStatusnew => implementing
2026-11-18 15:53Christian GrothoffCategoryexchange => taler-rust
2026-11-18 15:53Christian GrothoffTarget Version => 1.7
2026-11-18 15:57Christian GrothoffFast-track0 => 1