Xss Cross Site Scripting in Echo Go with Bearer Tokens
Xss Cross Site Scripting in Echo Go with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Cross-site scripting (XSS) in an Echo Go API often originates from reflecting untrusted data into HTML, JavaScript, or CSS without proper escaping. When an API uses Bearer Tokens for authentication, tokens can inadvertently become part of the response—such as being logged, echoed in error messages, or rendered in a JSON payload consumed by a frontend that later injects the value into the DOM. This combination creates a scenario where an attacker who obtains or guesses a token (or tricks a victim into making a request with a valid token) can craft a URL or request body that causes the server to reflect the token inside a script context, leading to stored, reflected, or DOM-based XSS.
For example, if an Echo Go handler directly includes a token value from a header or query parameter into an HTML response without sanitization, an attacker can supply a token containing a script payload. When the response is served to a user who is authenticated with that token (or whose browser automatically sends the token via an Authorization header), the injected script executes in their browser. Bearer Tokens are often long-lived or reused across requests; if a token is reflected into a page that lacks Content Security Policy (CSP), the impact is amplified because the token itself may be exfiltrated or abused in a secondary attack such as CSRF or privilege escalation.
XSS in this context does not require authentication if the endpoint is public, but Bearer Tokens increase the value of the stolen payload because the token can act as a credential. Additionally, if the API serves a web UI or is consumed by a JavaScript client that places the token into localStorage and later reads it into innerHTML or evaluates it, the token becomes a vector for client-side code execution. Attack patterns such as CVE-2021-41067-style injection or DOM-based XSS commonly exploit this behavior. The risk is further increased when APIs return user-controlled data alongside tokens in JSON responses without proper output encoding, enabling attackers to chain XSS with token theft.
Bearer Tokens-Specific Remediation in Echo Go — concrete code fixes
To mitigate XSS when using Bearer Tokens in Echo Go, ensure that tokens are never reflected into HTML, JavaScript, or CSS contexts. Always treat token values as opaque credentials and avoid including them in responses that are rendered in the browser. When tokens must be used client-side, store them securely in memory or in httpOnly cookies, and never concatenate them into HTML attributes or JavaScript strings.
On the server side, sanitize and validate all inputs that may influence output, and set appropriate response headers. Below is a secure Echo Go handler example that reads a Bearer token from the Authorization header, validates it, and ensures it is not reflected into the response body or headers:
package main
import (
"net/http"
"strings"
"github.com/labstack/echo/v4"
)
func main() {
e := echo.New()
e.GET("/profile", func(c echo.Context) error {
auth := c.Request().Header.Get("Authorization")
if auth == "" {
return c.JSON(http.StatusUnauthorized, map[string]string{"error", "missing authorization header"})
}
const bearerPrefix = "Bearer "
if !strings.HasPrefix(auth, bearerPrefix) {
return c.JSON(http.StatusUnauthorized, map[string]string{"error", "invalid authorization scheme"})
}
token := auth[len(bearerPrefix):]
if token == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error", "token is empty"})
}
// Validate the token via your auth service (not reflected in output)
valid, err := validateToken(token)
if err != nil || !valid {
return c.JSON(http.StatusForbidden, map[string]string{"error", "invalid token"})
}
// Do NOT include the token in the response body or headers
return c.JSON(http.StatusOK, map[string]string{"message", "ok"})
})
e.Logger.Fatal(e.Start(":8080"))
}
func validateToken(token string) (bool, error) {
// Implement token validation logic (e.g., JWT verification)
return true, nil
}
On the client side, if your frontend consumes this API, avoid placing the token into the DOM. For example, do not do this:
// Unsafe: injecting token into innerHTML
fetch('/profile', {
headers: { Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' }
})
.then(res => res.json())
.then(data => {
document.getElementById('token-display').innerHTML = data.token; // dangerous
});
Instead, keep the token out of the response entirely and manage it in memory:
// Safer: keep token in memory, never render it
token = null;
fetch('/profile', {
headers: { Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' }
})
.then(res => res.json())
.then(data => {
// Do not assign token from response; use token only for subsequent authenticated requests
console.log(data.message);
});
Additionally, set security headers in Echo Go to reduce the impact of any potential XSS:
e.Use(middleware.SecureWithConfig(middleware.SecureConfig{
XSSProtection: true,
ContentTypeNosniff: true,
XFrameOptions: middleware.XFrameOptionsDeny,
}))
These measures ensure that Bearer Tokens are handled as credentials and are not exposed in contexts where they can be abused for XSS.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |