HIGH phishing api keysfiber

Phishing Api Keys in Fiber

How Phishing API Keys Manifests in Fiber

In Fiber applications, API key phishing occurs when sensitive credentials are inadvertently exposed through error messages, debug endpoints, or logs. This creates an attack vector where malicious actors can harvest valid API keys by probing your application's responses.

Fiber-Specific Attack Patterns:

  • Debug Mode Information Leakage: Setting Debug: true in Fiber's configuration enables detailed error pages that may include environment variables, configuration snippets, or stack traces containing embedded API keys. For example, a database connection error might reveal a connection string with embedded credentials.
  • Unsanitized Error Responses: Custom error handlers that propagate raw errors (e.g., c.Status(500).SendString(err.Error())) can expose internal details. If an upstream service returns an error containing an API key, Fiber may forward it directly to the client.
  • Sensitive Logging Middleware: Default or custom logging middleware that records full request headers (including Authorization or X-API-Key) without redaction creates log-based phishing risks. If logs are accessible via a /logs endpoint or misconfigured storage, attackers can extract keys.
  • Debug Endpoints: Fiber apps sometimes include diagnostic routes (e.g., /debug/vars or /env) that expose environment variables. These endpoints, if left enabled in production, can directly leak API keys stored in environment variables.

Consider this vulnerable Fiber handler that echoes error details:

app.Get("/data", func(c *fiber.Ctx) error {
    // Simulate a downstream API call failure
    err := callExternalAPI()
    if err != nil {
        return c.Status(500).JSON(fiber.Map{
            "error":   err.Error(),
            "details": "See logs for more", // Might contain API keys in err.Error()
        })
    }
    return c.JSON(data)
})

If callExternalAPI fails with a message like "API key invalid: sk_live_...", the response leaks the key.

Fiber-Specific Detection

Manually detecting API key phishing in Fiber requires inspecting error responses, debug endpoints, and logs for secret patterns. Look for:

  • HTTP 500 responses containing long alphanumeric strings (typical API key format: sk_..., ak_..., xp_...).
  • Routes like /debug, /env, or /config that return environment variables.
  • Log entries that include Authorization or X-API-Key header values.

Scanning with middleBrick:

middleBrick automates detection by testing your Fiber API's unauthenticated endpoints. It sends probes designed to trigger error conditions and analyzes responses for leaked secrets using 27+ regex patterns covering common API key formats. It also checks for exposed debug endpoints and validates whether error messages contain sensitive data. For example, scanning a Fiber app might reveal:

{
  "category": "Data Exposure",
  "severity": "high",
  "finding": "API key leaked in error response at GET /data",
  "evidence": "Response contains pattern: sk_live_[a-zA-Z0-9]{24}"
}

To scan your Fiber API, use the web dashboard, CLI, or GitHub Action:

# Install CLI
npm install -g middlebrick

# Scan your Fiber app
middlebrick scan https://your-fiber-api.com

middleBrick's report includes per-category breakdowns and remediation guidance tailored to your framework.

Fiber-Specific Remediation

Remediation in Fiber focuses on suppressing sensitive data in responses, logs, and debug output. Apply these fixes:

  • Disable Debug Mode in Production: Ensure Debug is false in your Fiber config. Use environment-specific configuration:
app := fiber.New(fiber.Config{
    Debug: os.Getenv("APP_ENV") != "production", // Only enable debug in non-prod
    ErrorHandler: customErrorHandler,
})
  • Implement a Sanitizing Error Handler: Override Fiber's default error handler to strip sensitive data from responses. Log full errors internally (to a secure location) but return generic messages to clients:
func customErrorHandler(c *fiber.Ctx, err error) error {
    // Log the full error with stack trace for debugging (ensure logs are secured)
    log.Printf("Error: %s\nStack: %s", err.Error(), debug.Stack())

    // Return a generic response without sensitive details
    code := fiber.StatusInternalServerError
    if e, ok := err.(*fiber.Error); ok {
        code = e.Code
    }
    return c.Status(code).JSON(fiber.Map{
        "error": "Internal server error",
        "request_id": c.Get("X-Request-ID"), // For tracing
    })
}
  • Sanitize Logging Middleware: If using Fiber's built-in logger middleware or custom logging, filter sensitive headers. Example with fiber/middleware/logger:
app.Use(middleware.Logger(middleware.Config{
    Format: "${time} ${method} ${path} ${status} ${latency}\n",
    // Customize to skip sensitive headers
    Done: func(c *fiber.Ctx, logString []byte) {
        // Redact Authorization header from log output
        if auth := c.Get("Authorization"); auth != "" {
            logString = bytes.ReplaceAll(logString, []byte(auth), []byte("***REDACTED***"))
        }
        fmt.Print(string(logString))
    },
}))
  • Remove Debug Endpoints: Ensure routes like /debug/vars (from net/http/pprof) are not mounted in production. If you need health checks, create a minimal endpoint that excludes sensitive data:
if app.Environment() != fiber.EnvProduction {
    app.Get("/debug/vars", debugVars) // Only in non-prod
}

func debugVars(c *fiber.Ctx) error {
    // Return only non-sensitive system vars
    return c.JSON(fiber.Map{
        "uptime": time.Since(startTime),
        "status": "ok",
    })
}
  • Validate External Service Errors: When calling external APIs, inspect error responses before propagating. Wrap external calls to sanitize:
func callExternalAPI() error {
    resp, err := http.Get("https://external.api")
    if err != nil {
        return fmt.Errorf("external API unreachable") // Generic message
    }
    defer resp.Body.Close()
    if resp.StatusCode != 200 {
        body, _ := io.ReadAll(resp.Body)
        // Redact potential keys in response body
        sanitized := redactSecrets(string(body))
        return fmt.Errorf("external API error: %s", sanitized)
    }
    return nil
}

func redactSecrets(s string) string {
    // Replace patterns like sk_live_... with [REDACTED]
    re := regexp.MustCompile(`(sk|ak|xp)_[a-zA-Z0-9]{20,}`)
    return re.ReplaceAllString(s, "[REDACTED]")
}

After applying these fixes, rescan with middleBrick to verify that API key leakage is resolved. Remember: never expose raw errors or environment data in production Fiber apps.

FAQ

Q: Can middleBrick detect if my Fiber app's logs contain API keys?
A: Yes. middleBrick's scan includes analysis of log accessibility and content patterns. If your application exposes logs via an endpoint (e.g., /logs) or if logging middleware outputs sensitive headers, middleBrick will flag this as a data exposure risk with evidence of leaked key patterns.

Q: Does disabling Fiber's debug mode completely prevent API key phishing?
A: No. While disabling debug mode prevents verbose error pages, you must also sanitize custom error handlers, logging, and external service errors. middleBrick tests multiple attack vectors (including error injection) to ensure comprehensive coverage beyond just the debug setting.