HIGH token leakageecho gobearer tokens

Token Leakage in Echo Go with Bearer Tokens

Token Leakage in Echo Go with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Token leakage in an Echo Go service using Bearer tokens typically occurs when tokens are transmitted, stored, or logged in a way that exposes them to unauthorized parties. In Go services built with the Echo framework, Bearer tokens are often passed in the Authorization header as Authorization: Bearer <token>. If the application does not enforce strict transport security and proper header handling, tokens can be exposed through insecure routes, misconfigured middleware, or verbose logging.

One common pattern that leads to leakage is inadvertently logging the Authorization header. Echo’s default logger may capture request headers when debugging is enabled, and if the log output is aggregated or stored without redaction, Bearer tokens can be written to logs or standard output. For example, a route handler that logs the full request without filtering sensitive headers can expose tokens:

// Insecure: logs headers including Authorization
app.GET("/profile", func(c echo.Context) error {
    headers := make(map[string]string)
    for key, values := range c.Request().Header {
        headers[key] = values[0]
    }
    log.Printf("Request headers: %+v", headers)
    return c.JSON(http.StatusOK, "ok")
})

Another leakage vector involves redirect handling. If an Echo route performs an HTTP redirect (e.g., 302) and includes sensitive query parameters or headers in the redirect location, the Bearer token can be passed to a different origin or exposed to referrers. Tokens can also leak through Cross-Origin Resource Sharing (CORS) misconfigurations where credentials are allowed indiscriminately, enabling browser-based JavaScript to capture authorization headers via insecure origins.

Middleware that modifies or proxies requests without sanitizing headers can compound the risk. For instance, a custom middleware that forwards requests to a backend service might pass along the Authorization header without verifying the target’s trust boundary. If the backend response is captured by a client-side application or intercepted, the Bearer token is effectively compromised. In microservice chains within Echo Go, failing to strip or reissue tokens at service boundaries can lead to token propagation beyond intended scopes.

Tokens may also be exposed in error messages. Echo’s default error handler can return detailed stack traces or request details when panics occur. If a handler inadvertently includes context containing the Authorization header in error responses, tokens can be surfaced to unauthenticated attackers. For example, a validation failure that echoes the full request context might include header values in JSON error output.

Lastly, weak transport configurations can facilitate token leakage. Even when Bearer tokens are correctly set in headers, failing to enforce HTTPS in Echo via TLS middleware allows tokens to be transmitted in cleartext. Without strict transport security, network observers can capture Authorization headers, rendering Bearer token protections ineffective. Proper configuration of TLS and redirect policies in Echo is essential to prevent on-path token interception.

Bearer Tokens-Specific Remediation in Echo Go — concrete code fixes

Remediation focuses on preventing exposure of Bearer tokens through logging, redirects, CORS, and error handling. The following patterns demonstrate secure handling of Authorization headers in Echo Go.

1. Redact sensitive headers in logging:

// Secure: exclude Authorization from logs
app.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
    LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
        // Explicitly exclude Authorization header
        headers := map[string]string{}
        for k, vals := range c.Request().Header {
            if k == "Authorization" {
                headers[k] = "[redacted]"
            } else {
                headers[k] = vals[0]
            }
        }
        log.Printf("Request path: %s, headers: %+v", c.Path(), headers)
        return nil
    },
}))

app.GET("/profile", func(c echo.Context) error {
    return c.JSON(http.StatusOK, "ok")
})

2. Avoid including Bearer tokens in redirects and query parameters:

// Secure: redirect without leaking tokens
app.GET("/login", func(c echo.Context) error {
    token := c.Get("token").(string)
    // Do not append token to redirect URL
    return c.Redirect(http.StatusFound, "/dashboard")
})

// If state must be passed, use opaque session references instead of tokens
app.GET("/callback", func(c echo.Context) error {
    state := c.QueryParam("state")
    // Validate state against a server-side store, do not forward raw token
    return c.Redirect(http.StatusSeeOther, "/home")
})

3. Harden CORS to prevent cross-origin token leakage:

// Secure: restrict CORS instead of allowing all credentials
app.Use(middleware.CORSWithConfig(middleware.CORSConfig{
    AllowOrigins: []string{"https://trusted.example.com"},
    AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType},
    ExposeHeaders: []string{"Content-Length"},
    AllowCredentials: false, // avoid exposing tokens to browser contexts
    MaxAge: 12 * time.Hour,
}))

app.Use(middleware.AddSecureMiddleware)
app.Use(middleware.RemoveSensitiveHeaders(map[string]string{"Authorization": ""}))

4. Ensure HTTPS enforcement to protect token transmission:

// Secure: enforce TLS before routes
app.Use(middleware.TLSWithConfig(middleware.TLSConfig{
    MiddlewareConfig: middleware.MiddlewareConfig{
        Skipper: middleware.DefaultSkipper,
    },
    TLSConfig: &tls.Config{
        MinVersion: tls.VersionTLS12,
    },
}))

// Redirect HTTP to HTTPS
app.Use(middleware.HTTPSRedirect())

app.Start(":443")

5. Sanitize error outputs to exclude Authorization headers:

// Secure: custom error handler that scrubs headers
app.HTTPErrorHandler = func(err error, c echo.Context) {
    if he, ok := err.(*echo.HTTPError); ok {
        log.Printf("error code=%d, path=%s, sanitized headers logged", he.Code, c.Path())
    }
    // Do not expose request details containing tokens
    c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal error"})
}

// Prevent panics from exposing context
app.Use(middleware.Recover())
app.Use(middleware.RequestID())

These measures reduce the likelihood of Bearer token leakage in Echo Go services by addressing logging, redirects, CORS, transport security, and error handling explicitly.

Frequently Asked Questions

How can I verify that Bearer tokens are not being logged by Echo?
Review your logging configuration and ensure that the Authorization header is explicitly redacted. Use structured logging with field-level exclusion for sensitive headers and inspect log outputs to confirm tokens are not present.
Does using the middleBrick CLI help detect token leakage in Echo Go services?
Yes. The middleBrick CLI can scan your API endpoints and identify insecure header handling, missing transport security, and logging risks that may lead to Bearer token exposure. Run middlebrick scan <your-api-url> to surface findings related to token leakage.