Api Key Exposure in Fiber
How Api Key Exposure Manifests in Fiber
API key exposure in Fiber applications typically occurs through several distinct attack vectors that exploit the framework's design patterns. The most common manifestation is through endpoint misconfiguration where API keys are returned in responses that should be protected or where keys are inadvertently logged in error messages.
A critical Fiber-specific vulnerability arises from improper error handling in middleware chains. When Fiber's error middleware catches exceptions, it often includes request context in error responses. If an API key was part of the request headers, it can be reflected back in the error response body, creating an information disclosure vulnerability.
// Vulnerable Fiber middleware pattern
app.Use(func(c *fiber.Ctx) error {
apiKey := c.Get("x-api-key")
if apiKey == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": "missing api key",
"key_provided": apiKey, // EXPOSURE HERE
})
}
return c.Next()
})
Another Fiber-specific exposure pattern occurs in logging middleware. Fiber's structured logging often captures request headers by default, and if logging configuration isn't properly filtered, API keys end up in log files that may be accessible to unauthorized users or stored in insecure locations.
Response reflection attacks are particularly problematic in Fiber due to its flexible context handling. Developers often use c.Locals() to store API key validation results, but if this data isn't properly sanitized before being included in JSON responses, sensitive authentication data leaks to clients.
// Vulnerable response pattern
app.Get("/user", func(c *fiber.Ctx) error {
userID := c.Locals("user_id")
apiKey := c.Locals("api_key") // STORED BUT NOT SANITIZED
return c.JSON(fiber.Map{
"user_id": userID,
"api_key_used": apiKey, // EXPOSURE HERE
})
})
Fiber's middleware execution order also creates exposure risks. If authentication middleware fails but doesn't short-circuit the chain properly, subsequent handlers might execute with incomplete authentication context, leading to partial API key exposure through fallback behaviors.
Fiber-Specific Detection
Detecting API key exposure in Fiber applications requires examining both the application code and runtime behavior. Static analysis should focus on identifying patterns where API keys are handled without proper sanitization.
Code review should target these specific Fiber patterns:
- Middleware that captures request headers without filtering sensitive data
- Error handlers that include request context in responses
- Logging configurations that capture full request headers
- Response handlers that include authentication context in JSON responses
Runtime detection with middleBrick's API security scanner specifically identifies Fiber applications through HTTP response patterns and middleware behaviors. The scanner tests for API key reflection by sending requests with known test API keys and analyzing responses for key exposure.
# Scan a Fiber API endpoint with middleBrick
middlebrick scan https://api.example.com/v1/users
middleBrick's scanner detects Fiber-specific vulnerabilities through these methods:
- Header reflection testing: sends requests with test API keys and checks if they appear in responses
- Error response analysis: triggers controlled errors to examine how Fiber's error middleware handles authentication context
- Logging endpoint testing: identifies endpoints that might log sensitive request data
The scanner's LLM/AI security module also tests for AI-specific API key exposure patterns that are common in modern Fiber applications using AI services.
Manual testing should include:
# Test for API key reflection
curl -H "x-api-key: test-key-123" https://api.example.com/v1/endpoint
# Check if test-key-123 appears in response
Network traffic analysis can reveal exposure through middleware chains. Using tools like Wireshark or browser dev tools to examine Fiber's request processing can identify where API keys might be leaked through response headers or body content.
Fiber-Specific Remediation
Remediating API key exposure in Fiber requires implementing proper data handling patterns and leveraging Fiber's middleware architecture correctly. The primary defense is strict separation between authentication context and response data.
Implement a secure authentication middleware that never stores API keys in request context:
// Secure authentication middleware
func AuthMiddleware(apiKeys map[string]string) fiber.Handler {
return func(c *fiber.Ctx) error {
apiKey := c.Get("x-api-key")
if apiKey == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": "missing api key",
})
}
// Validate without storing the key
if _, valid := apiKeys[apiKey]; !valid {
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
"error": "invalid api key",
})
}
// Store only user ID, never the API key itself
c.Locals("user_id", "authenticated_user")
return c.Next()
}
}
Implement secure error handling that strips sensitive data:
// Secure error middleware
app.Use(func(c *fiber.Ctx) error {
return c.Next()
})
app.Use(func(c *fiber.Ctx) error {
err := c.Next()
if err != nil {
// Log the error internally with full context
log.Printf("Error: %v", err)
// Return sanitized response
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "internal server error",
"request_id": c.Locals("request_id"), // Safe to expose
})
}
return nil
})
Configure secure logging middleware that filters sensitive headers:
// Logging middleware with header filtering
app.Use(func(c *fiber.Ctx) error {
// Capture request without sensitive headers
requestLog := map[string]interface{}{
"method": c.Method(),
"path": c.Path(),
"ip": c.IP(),
"user_agent": c.Get("User-Agent"),
// Exclude x-api-key and other sensitive headers
}
log.Printf("Request: %+v", requestLog)
return c.Next()
})
Use Fiber's context clearing for sensitive operations:
// Clear sensitive context after use
app.Get("/sensitive", func(c *fiber.Ctx) error {
defer func() {
// Clear any sensitive locals
c.Locals("sensitive_data", nil)
}()
return c.JSON(fiber.Map{
"data": "safe response",
})
})
Integrate middleBrick's continuous monitoring to catch regressions:
# GitHub Action for Fiber API security
name: API Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run middleBrick Scan
run: |
npm install -g middlebrick
middlebrick scan https://staging.example.com/api --fail-on-severity=high
Regular security audits using middleBrick's dashboard help track API key exposure risks over time and ensure remediation efforts remain effective as the codebase evolves.