Cors Wildcard in Gorilla Mux with Api Keys
Cors Wildcard in Gorilla Mux with Api Keys — how this specific combination creates or exposes the vulnerability
A CORS wildcard (Access-Control-Allow-Origin: *) combined with API key authentication in Gorilla Mux can unintentionally expose protected endpoints to any origin that knows or guesses a valid key. When a handler is registered with the wildcard and an API key check is performed, the browser may still present credentials (cookies, authorization headers) to cross-origin requests if the endpoint relies on key validation rather than a same-origin policy. This means a malicious site can make a request with a valid API key, and the response is allowed cross-origin, potentially leaking data to unauthorized web pages.
In Gorilla Mux, this typically occurs when routes are set with Origins("*") while also enforcing API key middleware. The CORS middleware may reflect the incoming Origin header into Access-Control-Allow-Origin: * even when credentials or keys are required, violating the principle that wildcards and credentials (including custom headers such as API keys) should not be used together. An attacker who obtains a valid API key—through logging errors, client-side leakage, or social engineering—can issue cross-origin requests that succeed, bypassing same-origin protections intended by the API key mechanism.
Consider a route defined to require an API key via a custom header X-API-Key. If the CORS configuration responds with *, preflight requests (OPTIONS) may return the wildcard, and the actual request with the key header can be processed and returned to an untrusted origin. This misconfiguration maps to common web risks such as Cross-Site Data Theft and is relevant to findings under standards like OWASP API Top 10 (2023) — API1:2023 Broken Object Level Authorization when combined with improper access control, and data exposure issues under Data Exposure checks performed by scanners like middleBrick.
During black-box scanning, tools can detect this by sending preflight and authenticated requests from an external origin, observing whether the response includes a wildcard Access-Control-Allow-Origin alongside successful authenticated responses. middleBrick’s CORS and Authentication checks can surface this as a high-severity finding, noting that wildcard origins with API key authentication create a path for unauthorized cross-origin access if any key is discoverable.
Developers should ensure that when API keys are used, the CORS configuration scopes origins explicitly to trusted domains, avoids the wildcard when credentials or custom headers are required, and validates the Origin header server-side before echoing it into response headers. This aligns with secure defaults where credentials and wildcards are mutually exclusive, and where API keys are treated as sensitive headers not to be reflected carelessly.
Api Keys-Specific Remediation in Gorilla Mux — concrete code fixes
To remediate CORS issues while preserving API key authentication in Gorilla Mux, configure CORS to allow only specific origins and ensure the API key middleware runs before CORS handling, with proper header reflection limited to trusted origins. Below are concrete, working examples.
Secure CORS configuration with API key validation
// Gorilla Mux secure CORS + API key example
package main
import (
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func apiKeyMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
expectedKey := "REPLACE_WITH_STRONG_KEY"
supplied := r.Header.Get("X-API-Key")
if supplied != expectedKey {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/secure", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
}).Methods("GET")
// Define allowed origins explicitly — never use "*" when API keys are required
allowedOrigins := handlers.AllowedOrigins([]string{"https://app.yourcompany.com", "https://admin.yourcompany.com"})
allowedMethods := handlers.AllowedMethods([]string{"GET", "OPTIONS"})
allowedHeaders := handlers.AllowedHeaders([]string{"X-API-Key", "Content-Type"})
exposedHeaders := handlers.ExposedHeaders([]string{"X-Request-ID"})
// Wrap routes with API key first, then CORS
handler := apiKeyMiddleware(r)
corsHandler := handlers.CORSHandler(handler, allowedOrigins, allowedMethods, allowedHeaders, exposedHeaders)
http.ListenAndServe(":8080", corsHandler)
}
Key points in the example
AllowedOriginslists specific trusted domains instead of*.apiKeyMiddlewarevalidatesX-API-Keybefore the request reaches CORS reflection logic.- Exposed headers are limited to non-sensitive metadata; no sensitive keys are echoed back.
Alternative: per-route configuration
// Apply CORS on a per-route basis to limit exposure
func main() {
r := mux.NewRouter()
r.HandleFunc("/public", publicHandler).Methods("GET")
r.HandleFunc("/secure", secureHandler).Methods("GET")
secureRoute := r.PathPrefix("/secure").Subrouter()
secureRoute.Use(apiKeyMiddleware)
// Build CORS middleware selectively
corsOpts := handlers.CORSOptions{
AllowedOrigins: []string{"https://app.yourcompany.com"},
AllowedMethods: []string{"GET"},
AllowedHeaders: []string{"X-API-Key"},
ExposedHeaders: []string{"X-Request-ID"},
}
secureRoute.Use(handlers.CORS(corsOpts))
http.ListenAndServe(":8080", r)
}
By combining explicit origin lists with ordered middleware, you prevent wildcard-based access while keeping API key checks intact. middleBrick’s CLI can be used to verify these fixes: with middlebrick scan <url>, you can confirm that CORS headers no longer include a wildcard when authenticated endpoints are tested.
For teams with multiple services, the Pro plan’s continuous monitoring and GitHub Action integration can enforce that future route definitions do not reintroduce wildcard CORS when API key or other authentication headers are present. This helps maintain compliance with frameworks mapped by middleBrick, such as OWASP API Top 10 and SOC2 controls related to access control and data exposure.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |
Frequently Asked Questions
Why is a CORS wildcard dangerous when API keys are used in Gorilla Mux?
How can I verify my Gorilla Mux routes are not vulnerable?
middlebrick scan <your-api-url>. The scan checks CORS headers and authentication handling, reporting findings such as wildcard origins with credentialed headers and providing remediation guidance.