HIGH cors wildcardgorilla muxcockroachdb

Cors Wildcard in Gorilla Mux with Cockroachdb

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

A CORS wildcard (Access-Control-Allow-Origin: *) combined with Gorilla Mux routing and a CockroachDB backend can unintentionally expose sensitive data and elevate cross-origin threats. When a handler serving CockroachDB data uses a wildcard origin, any website can make authenticated-style requests from a victim’s browser and read the responses if credentials or tokens are included.

Gorilla Mux does not enforce CORS itself; it relies on middleware that you add. If that middleware sets Access-Control-Allow-Origin: * and also allows credentials (e.g., Access-Control-Allow-Credentials: true), browsers will reject the response, but before that rejection, a malicious site can learn that the endpoint exists and that preflight passes. More critically, if your CockroachDB HTTP API or an intermediary service uses per-request tokens and the frontend origin is wildcarded, a compromised page on any other origin can relay requests and harvest query results that should be origin-isolated.

Consider an endpoint that queries CockroachDB for user-specific rows using an authenticated session cookie. With a wildcard CORS policy, a page on an attacker-controlled site can issue requests that include cookies (if credentials are allowed) and observe responses via JavaScript. This can lead to unauthorized data access, aligning with BOLA/IDOR patterns when object-level permissions are not enforced server-side. In a typical stack, Gorilla Mux routes like /api/users/{userID} map to handlers that run SQL against CockroachDB; if CORS is misconfigured, the route’s existence and data visibility become exfiltratable across origins.

Another scenario involves preflight caching. A wildcard Access-Control-Allow-Origin with a long max-age can cause browsers to cache the permissive policy, making it harder to roll back after a fix. Combined with Cockroachdb’s externally exposed SQL layer or an ORM layer in your Go service, this can amplify the impact of any handler-side logic flaws, such as missing row-level security checks.

Cockroachdb-Specific Remediation in Gorilla Mux — concrete code fixes

Apply strict CORS policies in your Gorilla Mux middleware and validate origins explicitly. Avoid wildcard origins when credentials or sensitive CockroachDB data are involved. Use typed handlers that enforce per-request authorization before touching CockroachDB rows.

// main.go
package main

import (
	"database/sql"
	"log"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
	_ "github.com/lib/pq"
)

func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		origin := r.Header.Get("Origin")
		// Replace with your frontend origin(s); do not use "*" if credentials are required
		allowed := map[string]bool{
			"https://app.yourcompany.com": true,
			"https://staging.yourcompany.com": true,
		}
		if allowed[origin] {
			w.Header().Set("Access-Control-Allow-Origin", origin)
			w.Header().Set("Access-Control-Allow-Credentials", "true")
		} else {
			w.Header().Set("Access-Control-Allow-Origin", "")
			w.WriteHeader(http.StatusForbidden)
			return
		}
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func userHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		userID := vars["userID"]
		// Enforce authorization: ensure requesting user matches userID
		requesterID := r.Header.Get("X-User-ID") // use a proper auth context in production
		if requesterID != userID {
			http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
			return
		}
		var email string
		err := db.QueryRow(r.Context(), "SELECT email FROM users WHERE id = $1", userID).Scan(&email)
		if err != nil {
			http.Error(w, `{"error":"not found"}`, http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"email":"` + email + `"}`))
	}
}

func main() {
	db, err := sql.Open("postgres", "postgresql://user:password@host:26257/dbname?sslmode=require")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	r := mux.NewRouter()
	r.Use(corsMiddleware)
	r.HandleFunc("/api/users/{userID}", userHandler(db)).Methods("GET")

	// Test preflight explicitly
	preflight := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "https://app.yourcompany.com")
		w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Authorization")
		w.WriteHeader(http.StatusOK)
	})

	log.Println("Server on :8080")
	http.ListenAndServe(":8080", r)
}

Key points specific to Cockroachdb:

  • Always parameterize queries (use $1 placeholders) to avoid injection that could bypass application-level CORS checks.
  • Enforce row-level security in SQL when possible, so even if a request slips through CORS, CockroachDB will restrict rows to the owning user.
  • Do not rely on CORS alone for authorization; treat it as a first-layer safety net, not a security boundary.

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

Why is a wildcard CORS dangerous when serving Cockroachdb-backed APIs?
A wildcard allows any origin to read responses if credentials are permitted, enabling cross-origin data leakage. Combine this with missing row-level checks in Cockroachdb queries and attackers can harvest data across origins via crafted requests.
How can I safely expose an endpoint that serves Cockroachdb data to multiple trusted origins?
Use an allowlist in your CORS middleware, set Access-Control-Allow-Credentials only when necessary, and enforce strict per-request authorization before running SQL against Cockroachdb.