HIGH cors wildcardgorilla muxgo

Cors Wildcard in Gorilla Mux (Go)

Cors Wildcard in Gorilla Mux with Go — how this specific combination creates or exposes the vulnerability

When building HTTP services in Go, the Gorilla Mux router is a common choice for advanced routing. A Cors Wildcard misconfiguration in this context occurs when the server responds with Access-Control-Allow-Origin: * while also exposing sensitive headers or supporting credentials. In Go handlers, this can happen when the CORS middleware sets the wildcard indiscriminately, rather than reflecting the Origin and validating against an allowlist. The combination of Gorilla Mux routes and a permissive CORS setup can unintentionally grant cross-origin read access to authenticated resources or leak non-public response headers.

More specifically, if your application uses methods like router.HandleFunc("/api/data", handler).Methods("GET") and the handler sets CORS headers with a wildcard, any webpage on any origin can read the response via browser-enforced CORS. This becomes a data exposure vector when responses contain user-specific or sensitive information. Additionally, if the server processes preflight requests (OPTIONS) by returning the wildcard without validating the Access-Control-Request-Method or Access-Control-Request-Headers, it can enable unauthorized cross-origin requests that bypass intended scope restrictions, effectively weakening method- and header-level controls.

Go-Specific Remediation in Gorilla Mux — concrete code fixes

To remediate CORS issues in Gorilla Mux, avoid using a static wildcard for Access-Control-Allow-Origin when responses contain sensitive data. Instead, implement origin validation and selectively reflect allowed origins. Below is a complete, concrete example that shows a secure CORS middleware integrated with Gorilla Mux routes.

package main

import (
    "net/http"
    "strings"

    "github.com/gorilla/mux"
)

var allowedOrigins = map[string]bool{
    "https://example.com": true,
    "https://app.example.com": true,
}

var allowedHeaders = []string{"Content-Type", "Authorization"}
var allowedMethods = []string{"GET", "POST", "OPTIONS"}

func corsMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        origin := r.Header.Get("Origin")
        if allowedOrigins[origin] {
            w.Header().Set("Access-Control-Allow-Origin", origin)
        }
        w.Header().Set("Access-Control-Allow-Methods", strings.Join(allowedMethods, ", "))
        w.Header().Set("Access-Control-Allow-Headers", strings.Join(allowedHeaders, ", "))
        w.Header().Set("Access-Control-Allow-Credentials", "true")

        if r.Method == "OPTIONS" {
            w.WriteHeader(http.StatusOK)
            return
        }

        next.ServeHTTP(w, r)
    })
}

func dataHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.Write([]byte(`{"message": "secure data"}`))
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/api/data", dataHandler).Methods("GET")

    handler := corsMiddleware(r)
    http.ListenAndServe(":8080", handler)
}

In this setup, the middleware checks the Origin against an allowlist map and only echoes back a specific origin rather than using a wildcard. It also explicitly sets allowed methods and headers, and handles OPTIONS preflight requests safely. This approach reduces the risk of unintended cross-origin access while remaining compatible with browsers and API consumers.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Does middleBrick detect CORS misconfigurations such as wildcard origins?
Yes. middleBrick runs a set of 12 security checks in parallel, including checks for CORS misconfigurations like wildcard origins, missing VARY headers, and unsafe exposure of credentials. Findings include severity, details, and remediation guidance.
Can I integrate middleBrick into my CI/CD to fail builds on high-severity CORS findings?
Yes. With the Pro plan, you can use the GitHub Action to add API security checks to your CI/CD pipeline and fail builds if risk scores or specific issue categories exceed your configured threshold.