Subscribe

Fixing wildcard CORS on an authenticated API

Our API answered every request with Access-Control-Allow-Origin: * and Allow-Credentials: true. Here is why that pair is both unsafe and broken, the allowlist middleware in Go that replaced it, the Vary and preflight details, and the curl re-test.

Fixing wildcard CORS on an authenticated API

The first VAPT run on our API flagged this response header pair on every request:

access-control-allow-origin: *
access-control-allow-credentials: true

It was rated medium. You could argue for low, since the API uses a bearer token in the Authorization header and not cookies. But when you look closer, the problem is a bit more interesting than "wildcard bad".

In this blog we will look at what that pair actually does, the allowlist middleware that replaced it, two headers that are easy to forget, and how I re-test it with curl.

Too open and broken at the same time

Browsers do not allow * together with credentials. If a page calls fetch(url, {credentials: "include"}) and the response says Allow-Origin: *, the browser blocks the response. So the credentialed case never actually worked.

The non-credentialed case worked for everyone. Any page on the internet could call the API from a visitor's browser and read the response. For public endpoints that is a free scraping channel which looks like real user traffic, coming from real users' IPs.

The worst part is what this setup invites. Someone hits the credentials error one day, searches it, and the top answer says "echo back the request's Origin header". Now any site gets Allow-Origin: https://evil.example plus Allow-Credentials: true, and the browser will happily send cookies and hand over the response. That is the real CORS vulnerability, and our config was one quick fix away from it. It hadn't happened, I still wanted the code to make it impossible.

An allowlist, not a pattern

The fix is to echo the Origin back only when it is exactly on a list. Our API is gin, but the logic is the same in plain net/http, so here it is with the standard library only:

package cors

import (
    "net/http"
    "net/url"
    "strings"
)

const (
    allowHeaders  = "Authorization, Content-Type, X-Request-Id, X-Session-Id, X-App-Version"
    allowMethods  = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
    exposeHeaders = "Retry-After"
    maxAge        = "600" // seconds; Chromium caps this at 7200 anyway
)

// normalize turns a configured URL or an Origin header into scheme://host[:port].
func normalize(raw string) string {
    u, err := url.Parse(strings.TrimSpace(raw))
    if err != nil || u.Scheme == "" || u.Host == "" {
        return ""
    }
    return strings.ToLower(u.Scheme + "://" + u.Host)
}

// Middleware echoes the Origin back only when it is on the allowlist.
// devLocalhost lets any localhost port through, for non-production only.
func Middleware(allowed []string, devLocalhost bool, next http.Handler) http.Handler {
    set := make(map[string]bool, len(allowed))
    for _, a := range allowed {
        if o := normalize(a); o != "" {
            set[o] = true
        }
    }

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        h := w.Header()
        // The response depends on Origin, so caches must key on it.
        h.Add("Vary", "Origin")

        origin := normalize(r.Header.Get("Origin"))
        if origin != "" && (set[origin] || (devLocalhost && isLocalhost(origin))) {
            h.Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
            h.Set("Access-Control-Allow-Credentials", "true")
            h.Set("Access-Control-Allow-Headers", allowHeaders)
            h.Set("Access-Control-Allow-Methods", allowMethods)
            h.Set("Access-Control-Expose-Headers", exposeHeaders)
            h.Set("Access-Control-Max-Age", maxAge)
        }

        // Answer every preflight. Without an Allow-Origin header the browser
        // refuses the real request, which is the whole point.
        if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
            w.WriteHeader(http.StatusNoContent)
            return
        }

        next.ServeHTTP(w, r)
    })
}

func isLocalhost(origin string) bool {
    u, err := url.Parse(origin)
    if err != nil {
        return false
    }
    switch u.Hostname() {
    case "localhost", "127.0.0.1", "::1":
        return true
    }
    return false
}

Where does the list come from? Not hardcoded. We build it from config values the app already has for building email links (the web app URL, the admin panel URL and the marketing site), plus a comma separated CORS_ALLOWED_ORIGINS for odd cases like a preview deploy. That way dev, staging and production each allow their own front ends without a code change. normalize matters here, because config values are full base URLs with paths and a trailing slash, and the Origin header never has either.

The localhost exemption is there because flutter run -d chrome picks a new random port on each launch. Pinning ports would make local work painful. In the real middleware it is gated on the environment name, so it can never switch on in production.

Requests with no Origin header at all (the mobile apps, server to server calls, curl) are left alone. CORS is a browser thing; adding headers for other clients doesn't help or hurt them.

Exact matching beats clever matching

I matched with a map lookup on purpose. The usual bugs in CORS code come from being clever: strings.HasSuffix(origin, "example.com") lets https://evilexample.com through, and a regex without anchors lets https://app.example.com.evil.example through. A set of exact strings has no such edge.

The tests check exactly those tricks. Five cases that must get nothing, on both GET and preflight:

func TestUnknownOriginsGetNothing(t *testing.T) {
    for _, origin := range []string{
        "https://evil.example",
        "https://app.example.com.evil.example", // suffix trick
        "http://app.example.com",               // right host, wrong scheme
        "null",
        "http://localhost:5173", // localhost is only for dev
    } {
        for _, method := range []string{http.MethodGet, http.MethodOptions} {
            rec := serve(t, false, method, origin)
            if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
                t.Errorf("%s %s: Allow-Origin = %q, want none", method, origin, got)
            }
            if rec.Header().Get("Access-Control-Allow-Credentials") != "" {
                t.Errorf("%s %s: credentials header set", method, origin)
            }
        }
    }
}

null is in there because sandboxed iframes and file:// pages send Origin: null. Never put null on an allowlist. The full test file (five tests, with the serve helper) passes with go test on Go 1.27.

Two headers that are easy to forget

Vary: Origin goes on every response, allowed or not. The response now depends on the Origin header. Without Vary, a CDN or shared cache can store the response it built for one site and serve it, with that site's Allow-Origin, to another.

Access-Control-Allow-Headers is the one that bites the other way. Our Flutter web client sends custom headers like X-Session-Id and X-App-Version on every call. A custom header makes the request non-simple, so the browser sends a preflight first. If a header the client sends is missing from this list, the browser refuses the real request. And since the client sends it on every call, every cross-origin request fails, not just one. When someone adds a new client header, this constant has to change in the same PR.

Expose-Headers is a smaller one. Our login lockout and rate limiter return Retry-After. Without exposing it, the web app could see the 429 but not read when to retry.

Preflight caching

Access-Control-Max-Age: 600 lets a browser reuse a preflight result for ten minutes. Without the header the default is 5 seconds. Firefox caps it at 24 hours and Chromium at 2 hours (per MDN), so a bigger number does nothing in Chrome.

The catch is the other direction. After you remove an origin or a header from the allowlist, a browser that cached a preflight keeps sending the real request for up to max-age. The server still won't add Allow-Origin to that response, so the browser still blocks the read, but your test right after deploy can look wrong for a few minutes. Test from a fresh private window, or simply wait for some time.

Re-testing with curl

The re-test needs no browser. I ran the middleware locally on port 8089 with https://app.example.com allowed and sent three requests:

curl -s -i http://127.0.0.1:8089/v1/me -H "Origin: https://app.example.com" \
  | grep -iE '^(HTTP|access-control|vary)'

curl -s -i http://127.0.0.1:8089/v1/me -H "Origin: https://evil.example" \
  | grep -iE '^(HTTP|access-control|vary)'

curl -s -i -X OPTIONS http://127.0.0.1:8089/v1/me \
  -H "Origin: https://evil.example" \
  -H "Access-Control-Request-Method: GET" \
  -H "Access-Control-Request-Headers: authorization" \
  | grep -iE '^(HTTP|access-control|vary)'

The allowed origin got all six Access-Control-* headers and Vary: Origin. The evil origin got 200 with only Vary: Origin. Its preflight got 204 No Content and again only Vary. No Allow-Origin means the browser refuses, which is what you want.

Against the real API, the VAPT re-test did the same thing: the web app's origin echoed back with credentials, https://evil.example.com got no Allow-Origin on GET, and its preflight came back 204 with none either. That check has stayed in every run since, the same way I described in comparing VAPT runs to catch security regressions. A CORS config is one careless "just allow everything for now" away from coming back, so it deserves a check that runs again and again.