HIGH cross site request forgeryfiberapi keys

Cross Site Request Forgery in Fiber with Api Keys

Cross Site Request Forgery in Fiber with Api Keys

Cross Site Request Forgery (CSRF) in a Fiber-based API can occur when endpoints rely solely on static API keys for authentication without additional anti-CSRF protections. Because API keys are often stored in headers or query parameters, a browser-based malicious site can trigger cross-origin requests that include those keys if they are accessible to JavaScript (e.g., embedded in client-side code or leaked via Referer headers). In a Fiber service, if routes accept API keys via headers such as x-api-key and do not validate the request origin, an attacker can craft a form or script on another domain that performs state-changing actions on behalf of the key holder.

Consider a Fiber endpoint that uses API keys for authorization but does not enforce the SameSite attribute on cookies or validate the Origin/Referer headers. An authenticated user visiting a malicious site could cause their browser to send authorized requests to the Fiber service. Because API keys are long-lived secrets sometimes embedded in JavaScript, they may be readable via XSS or inadvertently exposed through Referer headers when navigating to external links. This combination means an attacker can forge requests that the server treats as legitimate, leading to unauthorized operations such as changing email addresses, initiating transfers, or modifying settings.

middleBrick detects this risk as part of its Authentication and BOLA/IDOR checks by correlating unauthenticated and authenticated behavior with the OpenAPI specification. When scanning a Fiber endpoint, the scanner tests whether actions that mutate state can be invoked without a valid origin check even when an API key is required. The tool also inspects how the API key is transmitted — query parameters increase exposure risk compared to headers — and flags endpoints that lack CSRF-relevant mitigations such as origin validation or anti-CSRF tokens. Findings include severity ratings and remediation guidance mapped to the OWASP API Top 10 and related compliance frameworks.

For example, a vulnerable Fiber route might look like this, illustrating the problem:

package main

import (
    "github.com/gofiber/fiber/v2"
    "net/http"
)

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

    // Vulnerable: API key check without origin validation
    app.Post("/transfer", func(c *fiber.Ctx) error {
        apiKey := c.Get("X-API-Key")
        if apiKey != "SECRET_KEY_123" {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid api key"})
        }

        var req struct {
            To   string `json:"to"`
            Amount int64 `json:"amount"`
        }
        if err := c.BodyParser(&req); err != nil {
            return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
        }

        // Perform transfer without CSRF token or SameSite/Origin check
        return c.JSON(fiber.Map{"status": "transfer initiated"})
    })

    app.Listen(":3000")
}

In this example, any site can POST to /transfer as long as the attacker can get the victim’s browser to include the X-API-Key header. This can happen via an image tag, fetch request, or form submission if the key is embedded in JavaScript or leaked via Referer. Proper remediation involves validating request origins and using anti-CSRF tokens or other synchronization patterns, even when API keys are used.

Api Keys-Specific Remediation in Fiber

To mitigate CSRF in Fiber when using API keys, adopt defense-in-depth: validate request origins, avoid exposing keys in browser-executable contexts, and use anti-CSRF tokens for state-changing operations. Do not rely on API keys alone for critical actions if they can be automatically included by browsers. The following patterns demonstrate secure approaches.

Origin and Referer validation ensures that requests come from expected sources. By checking the Origin and Referer headers, you can block cross-origin forgeries. Combine this with strict CORS policies to reduce risk.

package main

import (
    "github.com/gofiber/fiber/v2"
    "net/http"
    "strings"
)

func isAllowedOrigin(c *fiber.Ctx) bool {
    origin := c.Get("Origin")
    referer := c.Get("Referer")
    // Define allowed origins explicitly
    allowed := map[string]bool{
        "https://api.yourapp.com": true,
        "https://app.yourapp.com": true,
    }
    return allowed[origin] || allowed[referer]
}

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

    app.Post("/transfer", func(c *fiber.Ctx) error {
        if !isAllowedOrigin(c) {
            return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "invalid origin"})
        }

        apiKey := c.Get("X-API-Key")
        if apiKey != "SECRET_KEY_123" {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid api key"})
        }

        var req struct {
            To     string `json:"to"`
            Amount int64  `json:"amount"`
        }
        if err := c.BodyParser(&req); err != nil {
            return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
        }

        return c.JSON(fiber.Map{"status": "transfer initiated"})
    })

    app.Listen(":3000")
}

Use anti-CSRF tokens for operations that change state, even when API keys are used. Generate per-session or per-request tokens and require them in a header or form field. This prevents cross-origin requests from being honored because the attacker cannot read or predict the token.

package main

import (
    "github.com/gofiber/fiber/v2"
    "math/rand"
    "net/http"
    "time"
)

var csrfTokens = map[string]string{} // In practice, use a secure store with expiration

func generateCSRFToken(apiKey string) string {
    rand.Seed(time.Now().UnixNano())
    token := fmt.Sprintf("%d", rand.Intn(999999))
    csrfTokens[apiKey] = token
    return token
}

func validateCSRFToken(apiKey, token string) bool {
    expected, exists := csrfTokens[apiKey]
    return exists && expected == token
}

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

    app.Post("/init-transfer", func(c *fiber.Ctx) error {
        apiKey := c.Get("X-API-Key")
        if apiKey != "SECRET_KEY_123" {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid api key"})
        }
        token := generateCSRFToken(apiKey)
        return c.JSON(fiber.Map{"csrf_token": token})
    })

    app.Post("/transfer", func(c *fiber.Ctx) error {
        apiKey := c.Get("X-API-Key")
        if apiKey != "SECRET_KEY_123" {
            return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid api key"})
        }

        token := c.Get("X-CSRF-Token")
        if !validateCSRFToken(apiKey, token) {
            return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "invalid CSRF token"})
        }

        var req struct {
            To     string `json:"to"`
            Amount int64  `json:"amount"`
        }
        if err := c.BodyParser(&req); err != nil {
            return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
        }

        return c.JSON(fiber.Map{"status": "transfer initiated"})
    })

    app.Listen(":3000")
}

Avoid storing API keys in places accessible to client-side code. Do not embed keys in JavaScript that runs in the browser, and set the Referrer-Policy header to limit leakage via Referer. For public clients, consider using short-lived tokens or OAuth flows instead of long-lived API keys.

middleBrick can support your remediation by verifying that these mitigations are reflected in your OpenAPI spec and by testing that endpoints reject cross-origin requests when expected. Using the CLI (middlebrick scan <url>) or the GitHub Action, you can automate detection and prevent risky deployments. The dashboard helps you track improvements over time, while the MCP Server lets you run scans directly from your IDE.

Frequently Asked Questions

Can API keys alone prevent CSRF in Fiber APIs?
No. API keys do not prevent CSRF because browsers automatically include headers like X-API-Key on cross-origin requests if the key is available to JavaScript or exposed via Referer. You must add origin validation or anti-CSRF tokens.
How does middleBrick detect CSRF risks in API specs?
middleBrick correlates authentication requirements with mutation endpoints, checking for missing origin validation and token requirements. It compares the OpenAPI spec to runtime behavior and flags endpoints that allow state-changing actions without CSRF protections.