HIGH double freefiberapi keys

Double Free in Fiber with Api Keys

Double Free in Fiber with Api Keys — how this specific combination creates or exposes the vulnerability

A Double Free in the context of a Fiber application that relies on API keys occurs when memory is incorrectly managed such that the same dynamic resource is released more than once, often because key validation or allocation logic is duplicated or conditionally bypassed. In Go, this typically does not manifest as manual free calls, but as double closure of resources, repeated deallocation of wrapped objects, or multiple code paths that each attempt to clean up the same key state. The presence of API keys introduces multiple branches that handle authentication, key validation, and request authorization, increasing the risk that two paths can trigger the same cleanup logic under certain request sequences or error conditions.

Consider a Fiber route that authenticates using an API key and conditionally creates per-request context objects. If middleware both validates the key and, on failure, attempts to clean up partially initialized structures, a crafted request can cause both paths to execute for the same request. For example, a middleware that allocates a context map for valid keys and another branch that attempts to clear it on invalid keys can lead to duplicate release of the same map reference when key validation logic is intertwined with error handling. This can corrupt internal runtime structures, leading to crashes or unpredictable behavior. The vulnerability is exposed when the API key handling logic is not strictly single-owner: initialization and cleanup responsibilities overlap across functions, and the request lifecycle allows both to run.

With OpenAPI/Swagger spec analysis, cross-references between spec definitions and runtime findings can highlight endpoints that accept API keys without clear ownership semantics, making it easier to spot routes where double-free-like conditions might arise from duplicated validation and cleanup steps. Because the scan runs 12 security checks in parallel, issues such as improper state management around API keys can be surfaced alongside related input validation and authentication checks, helping to narrow the conditions that lead to double-free scenarios.

Real-world attack patterns tied to this class of issue include malformed requests that force both authentication success and failure paths to execute within the same request lifecycle, or misuse of context cancellation that triggers cleanup in multiple middleware layers. While the vulnerability is not about parsing malformed JSON directly, it is closely related to how API key extraction and validation are orchestrated across the Fiber middleware chain.

To detect these patterns, the scanner exercises the unauthenticated attack surface and inspects how API key–bearing requests navigate authentication, property authorization, and input validation checks. Findings are mapped to relevant portions of the OWASP API Top 10 and can be tracked over time via the Web Dashboard, which helps teams see whether changes to key handling reduce the likelihood of state corruption issues.

Api Keys-Specific Remediation in Fiber — concrete code fixes

Remediation focuses on ensuring a single, clear owner for API key state and guaranteeing that initialization and cleanup occur along one path per request. In Fiber, this means structuring middleware so that key validation either fully succeeds and sets request context, or fails and aborts without leaving partially initialized structures. Avoid allocating resources in one middleware branch and freeing them in another; instead, centralize lifecycle management.

Below are concrete, working examples of API key handling in Fiber that avoid double-free-like conditions by using a single validation path and explicit context management.

Example 1: Centralized API key validation with request-scoped context

package main

import (
	"fmt"
	"net/http"

	"github.com/gofiber/fiber/v2"
)

type apiKeyContextKey string

const apiKeyKey apiKeyContextKey = "apiKey"

func apiKeyValidator(c *fiber.Ctx) error {
	// Extract key from header
	key := c.Get("X-API-Key")
	if key == "" {
		return c.Status(http.StatusUnauthorized).JSON(fiber.Map{"error": "missing api key"})
	}

	// Validate key (replace with your backend check)
	valid := key == "super-secret-key"
	if !valid {
		return c.Status(http.StatusForbidden).JSON(fiber.Map{"error": "invalid api key"})
	}

	// Attach validated key to context for downstream handlers
	c.Locals(apiKeyKey, key)
	return c.Next()
}

func handler(c *fiber.Ctx) error {
	key, ok := c.Locals(apiKeyKey).(string)
	if !ok {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "internal state error"})
	}
	return c.JSON(fiber.Map{"message": "ok", "key_present": key != ""})
}

func main() {
	app := fiber.New()
	app.Use(apiKeyValidator)
	app.Get("/secure", handler)
	app.Listen(":3000")
}

Example 2: Graceful error handling without duplicate cleanup

package main

import (
	"fmt"
	"net/http"

	"github.com/gofiber/fiber/v2"
)

func keyMiddleware(c *fiber.Ctx) error {
	// Single point of failure handling: if invalid, abort immediately
	k := c.Get("Authorization")
	if len(k) < 7 || k[:7] != "Bearer " {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "authorization header malformed"})
	}
	token := k[7:]
	if token != "valid-token" {
		return c.Status(http.StatusUnauthorized).JSON(fiber.Map{"error": "invalid token"})
	}
	c.Locals("auth", token)
	return c.Next()
}

func getData(c *fiber.Ctx) error {
	// Safe to use authenticated context; no additional cleanup branches
	return c.JSON(fiber.Map{"data": "sensitive"})
}

func main() {
	app := fiber.New()
	app.Use(keyMiddleware)
	app.Get("/data", getData)
	app.Listen(":3000")
}

These patterns avoid the conditions that can lead to double-free-like behavior by ensuring that once authentication succeeds, downstream handlers rely on a stable context. If validation fails, the request terminates before any allocations that would need cleanup. For teams using the Pro plan, continuous monitoring can be added via the GitHub Action to enforce that risk scores remain below a chosen threshold, and findings related to authentication and state management can be surfaced in CI/CD pipelines.

Use the CLI to scan from terminal with middlebrick scan <url> to validate that your endpoints correctly handle API keys under varied request paths. The MCP Server can also scan APIs directly from your AI coding assistant to catch problematic patterns during development.

Frequently Asked Questions

Can a Double Free in Fiber with API keys corrupt runtime state even if Go uses garbage collection?
Yes. In Go, double-free-like issues typically arise from releasing the same underlying resource (such as a map or slice) multiple times or from concurrent cleanup paths. This can corrupt internal structures and lead to crashes or data races, even without manual memory management.
How does middleBrick detect issues related to API key handling and state management?
middleBrick runs 12 security checks in parallel, including Authentication, Input Validation, and Property Authorization, while also analyzing OpenAPI/Swagger specs with full $ref resolution. This helps identify endpoints where API key flows may introduce duplicated or overlapping cleanup logic that can lead to state corruption.