Data Exposure in Echo Go with Bearer Tokens
Data Exposure in Echo Go with Bearer Tokens — how this specific combination creates or exposes the vulnerability
The Data Exposure check in middleBrick examines whether sensitive information such as authentication material, personal data, or secrets can be retrieved or inferred through the API surface. When testing an Echo Go service, this check looks for endpoints that return or leak Bearer tokens either directly in response bodies, headers, logs, or error messages. Echo Go is a common pattern for building HTTP services in Go using the Echo framework, and it often integrates Bearer tokens for route or method-level authorization.
In Echo Go, developers commonly use middleware to validate Bearer tokens from the Authorization header. If implementation details are exposed — for example, returning the raw token in a debug response, logging the header verbatim, or including the token in URLs via query parameters — the API can inadvertently disclose credentials. middleBrick’s Data Exposure check sends requests that probe for these patterns, comparing runtime behavior against the OpenAPI specification when available. If the specification marks a response as sensitive but the runtime returns a token-like string, a finding is generated.
Another scenario specific to Echo Go involves route grouping and nested routes. Developers sometimes attach Bearer token validation to a parent route group and inadvertently allow child routes to return sensitive data without proper authorization. middleBrick’s checks include inventory management and property authorization to detect cases where endpoints expose data that should be restricted. For example, a route like /debug/tokens or an unguarded health endpoint might echo the Authorization header back in the response body, creating a direct data exposure path.
Echo Go applications that use structured JSON responses may also leak tokens when error handling is inconsistent. If a middleware failure results in a JSON payload such as {"error": "invalid token", "token": "xxx"}, middleBrick’s output scanning flags this as a Data Exposure finding. The scanner does not rely on internal code inspection; instead, it correlates specification definitions with observed responses to identify inconsistencies that could expose Bearer tokens.
SSRF and Unsafe Consumption checks further relate to Data Exposure in Echo Go services that accept URLs or file paths provided by the caller. An attacker might supply a URL that causes the server to fetch an internal resource containing token metadata, which then appears in logs or responses. By running these checks in parallel, middleBrick identifies whether data exposure occurs through token leakage, improper error handling, or unsafe external data consumption.
Bearer Tokens-Specific Remediation in Echo Go — concrete code fixes
To remediate Bearer token exposure in Echo Go services, follow secure coding practices that prevent tokens from appearing in responses, logs, or URLs. Use environment variables for token material, avoid echoing the Authorization header, and ensure error messages do not include sensitive values. The following examples illustrate secure patterns.
Example 1: Secure Authorization Header Parsing
Instead of returning or logging the raw token, extract and validate it without exposing contents.
// Secure Echo Go handler example
package main
import (
"context"
"net/http"
"github.com/labstack/echo/v4"
)
func secureHandler(c echo.Context) error {
auth := c.Request().Header.Get("Authorization")
if auth == "" {
return echo.NewHTTPError(http.StatusUnauthorized, "authorization header missing")
}
// Validate token format without echoing it back
token, err := extractBearerToken(auth)
if err != nil || !isValidToken(token) {
return echo.NewHTTPError(http.StatusUnauthorized, "invalid authorization")
}
// Do not include the token in any response or log
return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
}
func extractBearerToken(auth string) (string, error) {
const prefix = "Bearer "
if len(auth) < len(prefix) || auth[:len(prefix)] != prefix {
return "", ErrInvalidFormat
}
return auth[len(prefix):], nil
}
func isValidToken(token string) bool {
// Implement token validation logic, e.g., JWT verification
return len(token) > 0
}
Example 2: Avoid Token Exposure in Error Responses
Ensure error handlers do not include the token. Define a custom HTTP error handler that sanitizes messages.
// Secure error handling in Echo Go
package main
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
func init() {
e := echo.New()
// Centralized error handler that avoids leaking tokens
e.HTTPErrorHandler = func(err error, c echo.Context) {
code := http.StatusInternalServerError
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
}
// Generic message, no token details
c.JSON(code, map[string]string{"error": "request failed"})
}
// Apply middleware safely
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogStatus: true,
LogURI: true,
LogUserAgent: true,
BeforeLogFunc: func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Avoid logging Authorization header value
req := c.Request()
// Strip sensitive headers before logging
req.Header.Del("Authorization")
return next(c)
}
},
}))
}
Example 3: Secure Token Storage and Usage
Never pass Bearer tokens as query parameters or include them in URLs. Use secure headers and keep tokens out of logs.
// Avoid this in Echo Go
// ❌ Insecure: token in URL
// curl /api/resource?token=abc123
// Secure alternative: use Authorization header only
package main
import (
"net/http"
"github.com/labstack/echo/v4"
)
func apiHandler(c echo.Context) error {
req := c.Request()
auth := req.Header.Get("Authorization")
if auth == "" {
return echo.NewHTTPError(http.StatusBadRequest, "authorization header required")
}
// Validate token and proceed
return c.JSON(http.StatusOK, map[string]string{"result": "success"})
}
General Recommendations
- Do not concatenate Bearer tokens into URLs or form values; always use the Authorization header.
- Sanitize logs in Echo Go by removing or masking the Authorization header before writing log entries.
- Use structured error responses that avoid exposing internal details or token values.
- Validate token format server-side and enforce strict token lifecycle management outside the API layer.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |