HIGH cors wildcardfiberapi keys

Cors Wildcard in Fiber with Api Keys

Cors Wildcard in Fiber with Api Keys — how this specific combination creates or exposes the vulnerability

Cross-origin resource sharing (CORS) misconfigurations in Go Fiber can expose an API key–based authentication scheme to unauthorized origins. A common pattern is to apply a wildcard Access-Control-Allow-Origin: * while also using API keys for authorization. The vulnerability occurs because CORS is a browser-enforced mechanism; API keys are typically validated in application code after the CORS preflight succeeds. A wildcard origin allows any domain to make authenticated requests, undermining the isolation that API keys are meant to provide.

In Fiber, the CORS middleware is configured independently of the API key validation logic. If cors.New(cors.Config{AllowOrigins: "*"}) is used alongside a custom API key check, the browser permits cross-origin requests, but the server still expects a valid key in the header. However, a wildcard origin enables any website to include the required key in requests if the key is embedded or leaked (for example, in JavaScript, logs, or referrer headers). This combination can inadvertently expose the API key–based boundary, enabling cross-origin abuse such as credential harvesting or unauthorized invocation of sensitive endpoints.

During a scan, middleware-level authorization checks like API key validation may be classified under Property Authorization and Authentication, while the CORS misconfiguration may map to BFLA/Privilege Escalation or Input Validation. The scanner can detect that a wildcard origin coexists with key-based checks without additional origin validation or strict referer policies. Attack patterns such as origin spoofing or referrer leakage become feasible, especially when responses include keys or tokens in headers or bodies that are exposed to unauthorized origins.

Real-world examples include endpoints that return sensitive data with Access-Control-Allow-Origin: * while requiring an X-API-Key header. If a key is inadvertently included in error messages or preflight responses, or if a client embeds the key in page JavaScript, any site on the internet can make authenticated calls. This violates the principle of same-origin policy and can lead to data exposure or unauthorized operations, mapped in frameworks such as OWASP API Top 10 (2023) API5:5 — Broken Function Level Authorization.

Because middleBrick performs black-box scanning without credentials, it can identify mismatches between declared CORS policy and actual enforcement of API key requirements. Findings typically recommend replacing the wildcard with an allowlist of trusted origins, enforcing strict CORS headers, and ensuring API keys are never exposed to client-side code or cross-origin contexts. These steps reduce the attack surface by ensuring that even when keys are used, requests are only accepted from known, controlled sources.

Api Keys-Specific Remediation in Fiber — concrete code fixes

To secure a Fiber API that uses API keys, configure CORS with explicit origins and enforce key validation before routing. Avoid wildcard origins and instead specify a controlled list of trusted domains. Combine this with strict header checks and secure handling of keys to prevent leakage across origins.

Example of a secure Fiber setup with API keys and restricted CORS:

package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/cors"
)

func main() {
    app := fiber.New()

    // Restrict origins instead of using wildcard
    corsConfig := cors.New(cors.Config{
        AllowOrigins:     "https://app.example.com,https://admin.example.com",
        AllowMethods:     "GET,POST,PUT,DELETE",
        AllowHeaders:     "Content-Type,Authorization,X-API-Key",
        ExposeHeaders:    "Content-Length,Content-Type",
        AllowCredentials: true,
        MaxAge:           3600,
    })

    app.Use(corsConfig)

    // API key validation middleware
    apiKeyMiddleware := func(c *fiber.Ctx) error {
        const expectedKey = "YOUR_STRONG_API_KEY" // ideally from env
        key := c.Get("X-API-Key")
        if key != expectedKey {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
                "error": "unauthorized",
                "code":  401,
            })
        }
        return c.Next()
    }

    app.Use(apiKeyMiddleware)

    app.Get("/secure", func(c *fiber.Ctx) error {
        return c.JSON(fiber.Map{"message": "Authenticated and CORS-safe"})
    })

    app.Listen(":3000")
}

Key practices illustrated:

  • Set AllowOrigins to specific trusted origins rather than "*" to prevent arbitrary domains from participating in authenticated requests.
  • Include Authorization and custom headers like X-API-Key in AllowHeaders so that credentials are explicitly permitted.
  • Enable AllowCredentials: true only when necessary and pair it with explicit origins; browsers will reject credentials if the origin is *.
  • Validate API keys in middleware before handler execution, returning 401 for missing or incorrect keys.
  • Keep keys in environment variables or secure configuration stores, and avoid logging or exposing them in responses that could be seen by unauthorized origins.

For automated oversight, the CLI tool can be used to validate these configurations: middlebrick scan <url> returns findings and remediation steps. In CI/CD, the GitHub Action can enforce that any change which introduces a wildcard CORS policy with key-based auth fails the build if the risk score drops below your defined threshold. The MCP Server also allows you to scan API definitions directly from your IDE, catching these issues early during development.

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

Can a wildcard CORS policy be safe if API keys are used?
No. A wildcard Access-Control-Allow-Origin: * allows any website to make requests that include credentials when AllowCredentials is enabled, which can expose API keys if they are required. Use explicit origin allowlists and never combine wildcard origins with authenticated endpoints.
How does middleBrick detect CORS and API key issues?
middleBrick runs 12 parallel security checks including Authentication, Property Authorization, and BFLA/Privilege Escalation. It compares OpenAPI/Swagger specs with runtime behavior to identify mismatches such as a wildcard CORS policy coexisting with API key requirements, and reports findings with severity and remediation guidance.