HIGH token leakagefiber

Token Leakage in Fiber

How Token Leakage Manifests in Fiber

Token leakage in Fiber applications typically occurs through improper handling of authentication tokens in HTTP responses, logs, and error messages. The most common manifestation is when access tokens or refresh tokens are inadvertently included in API responses due to developer oversight or improper error handling.

A typical scenario involves middleware that catches panics or errors and includes request context in error responses. Consider this problematic Fiber pattern:

app.Use(func(c *fiber.Ctx) error {
    defer func() {
        if err := recover(); err != nil {
            c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
                "error": "internal error",
                "request_id": c.Get(fiber.HeaderXRequestID),
                "token": c.Locals("token") // LEAKED
            })
        }
    }()
    return c.Next()
})

Another common leak occurs through logging middleware that captures request bodies or headers. Fiber's default logging can expose tokens if not properly configured:

app.Use(middleware.Logger()) // Logs Authorization headers by default

Token leakage also manifests in Fiber through improper use of context values. Developers often store tokens in context for downstream use but forget to clear them, leading to accidental exposure in templates or response data.

Cross-site request forgery (CSRF) vulnerabilities in Fiber can lead to token leakage when combined with improper CORS configuration. An attacker can trick a user's browser into making requests that expose authentication tokens through error responses or logging.

Fiber-Specific Detection

Detecting token leakage in Fiber applications requires both manual code review and automated scanning. The most effective approach combines static analysis with runtime testing.

For static detection, look for these Fiber-specific patterns:

// Search for these patterns in your codebase
c.Locals("token")
c.Locals("jwt")
c.Locals("auth")
c.Get("Authorization")
c.Get("Cookie")

// Check for logging middleware usage
middleware.Logger()

// Look for error handling that might expose context
recover()
c.JSON(fiber.Map{...})

middleBrick's scanner specifically detects token leakage in Fiber applications by analyzing HTTP responses for sensitive headers and values. It tests for:

  • Authorization headers in response bodies
  • Cookie headers containing session tokens
  • XSRF tokens in error responses
  • Authentication tokens in logging output
  • Bearer tokens in JSON responses

The scanner also tests for Fiber-specific vulnerabilities by sending malformed requests and analyzing error responses for token exposure. It checks if Fiber's default error handlers inadvertently include sensitive context data.

For runtime detection, implement request logging that specifically watches for token patterns:

app.Use(func(c *fiber.Ctx) error {
    // Check for tokens in request body
    if strings.Contains(c.Body(), "token") || 
       strings.Contains(c.Body(), "jwt") {
        // Log potential token leakage
        log.Printf("Potential token in request body: %s", c.Path())
    }
    return c.Next()
})

Fiber-Specific Remediation

Remediating token leakage in Fiber requires a multi-layered approach. Start by implementing proper token handling middleware:

// Secure token extraction middleware
func SecureTokenMiddleware() fiber.Handler {
    return func(c *fiber.Ctx) error {
        // Extract token securely without storing in context
        authHeader := c.Get("Authorization")
        if authHeader != "" {
            parts := strings.SplitN(authHeader, " ", 2)
            if len(parts) == 2 && parts[0] == "Bearer" {
                token := parts[1]
                // Validate token immediately
                if err := validateToken(token); err != nil {
                    return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
                        "error": "invalid token",
                    })
                }
                // Store minimal context, not the token itself
                c.Locals("user_id", extractUserID(token))
            }
        }
        return c.Next()
    }
}

Implement secure error handling that never exposes tokens:

app.Use(func(c *fiber.Ctx) error {
    defer func() {
        if err := recover(); err != nil {
            // Never include sensitive data in error responses
            c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
                "error": "internal server error",
                "request_id": uuid.New().String(),
            })
        }
    }()
    return c.Next()
})

Use Fiber's built-in security features to prevent token leakage:

app.Use(middleware.CORS())
app.Use(middleware.Secure())
app.Use(middleware.Recover())

// Custom logging that redacts tokens
app.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
    Format: "${time} ${method} ${path} ${status} ${latency}\n",
    Output: logger, // Custom logger that redacts sensitive data
}))

For comprehensive protection, integrate middleBrick's CLI into your development workflow:

# Scan your Fiber API for token leakage
middlebrick scan https://your-fiber-api.com

# Integrate into CI/CD
middlebrick scan --fail-on-severity=high --output=json https://staging.your-fiber-api.com

This combination of secure coding practices, proper middleware configuration, and automated scanning ensures that tokens remain protected throughout your Fiber application's lifecycle.

Frequently Asked Questions

How does middleBrick detect token leakage in Fiber applications?
middleBrick uses black-box scanning to test Fiber endpoints for token leakage. It sends requests designed to trigger error responses and analyzes the returned data for sensitive information like Authorization headers, cookies, and authentication tokens. The scanner checks for 12 security categories including authentication flaws, data exposure, and input validation issues specific to Fiber's architecture.
Can token leakage occur even with proper middleware configuration?
Yes, token leakage can still occur through improper error handling, logging configurations, or custom middleware that inadvertently exposes sensitive data. Even with Fiber's built-in security middleware, developers must carefully review their error handlers, logging output, and response formatting to ensure tokens are never included in responses, logs, or error messages.