HIGH xss cross site scriptingecho goapi keys

Xss Cross Site Scripting in Echo Go with Api Keys

Xss Cross Site Scripting in Echo Go with Api Keys — how this specific combination creates or exposes the vulnerability

Cross-site scripting (XSS) in an Echo Go API that exposes API keys can occur when user-controlled data containing script payloads is reflected into HTML, JSON, or JavaScript contexts without proper encoding, and the API key is inadvertently exposed to the client or logged in a way that enables further exploitation. In Echo Go, this typically arises when handlers embed raw query parameters, headers, or request bodies directly into HTML responses or JSON fields that a browser interprets as executable script, and the API key is transmitted in a manner that violates the same-origin or least-privilege principles.

For example, if an Echo Go endpoint accepts a name query parameter and injects it into an HTML page while also returning an API key in a JSON field or a cookie without the HttpOnly and Secure attributes, an attacker can craft a URL like https://api.example.com/search?name=<script>stealCookies()</script>. When a victim’s browser renders the response, the injected script executes in the context of the origin, potentially reading other cookies or making unauthorized requests that include the API key. If the API key is also stored in client-side JavaScript (e.g., in a config object fetched from the same endpoint), an XSS payload can exfiltrate it to an attacker-controlled server, compounding the impact by enabling unauthorized access to backend resources.

Another scenario involves path traversal or IDOR-like behavior where an attacker manipulates identifiers to access resources that include sensitive keys, and the response reflects these keys alongside unsanitized user input. Even in JSON APIs consumed by web clients, if the API key is returned in a field that the frontend embeds into the DOM (e.g., innerHTML or document.write), an XSS vector can be formed. This is especially relevant when OpenAPI specs are not rigorously validated; a definition that marks a key as a plain string without indicating it should never appear in browser-visible responses can lead to accidental leakage and subsequent script execution via reflected or stored XSS.

middleBrick’s 12 security checks, including Input Validation, Data Exposure, and Unsafe Consumption, are designed to detect these patterns by correlating runtime behavior with OpenAPI/Swagger 2.0, 3.0, and 3.1 specifications and their $ref resolutions. The scanner flags instances where API keys appear in responses that are not explicitly marked as non-browser-safe and where user input is reflected without context-aware escaping. This helps teams identify misconfigured handlers that unintentionally expose keys through XSS-prone rendering paths.

Api Keys-Specific Remediation in Echo Go — concrete code fixes

Remediation focuses on preventing script injection and ensuring API keys are never exposed to browser contexts. In Echo Go, always treat user input as untrusted and encode data based on the output context: HTML, attribute, JavaScript, or URL. Use the html package to escape reflected content and avoid embedding secrets in responses that reach frontend code.

Example of a vulnerable handler:

package main

import (
    "net/http"
    "github.com/labstack/echo/v4"
)

func searchHandler(c echo.Context) error {
    name := c.QueryParam("name")
    apiKey := getAPIKey() // Assume this retrieves a sensitive key
    // Vulnerable: reflects user input into HTML and exposes key
    resp := map[string]string{
        "result": name,
        "key":    apiKey,
    }
    return c.JSON(http.StatusOK, resp)
}

Fixed version with context-aware escaping and key protection:

package main

import (
    "html"
    "net/http"
    "github.com/labstack/echo/v4"
)

func searchHandler(c echo.Context) error {
    name := c.QueryParam("name")
    // Encode user input for HTML context if embedding in a template
    safeName := html.EscapeString(name)
    // Do not expose API keys in responses; retrieve per-request only if necessary
    apiKey := getAPIKey()
    // Use the key server-side for external calls, never return to client
    _ = callExternalService(apiKey, safeName)
    return c.JSON(http.StatusOK, map[string]string{
        "result": safeName,
    })
}

Additional measures include setting HttpOnly, Secure, and SameSite attributes on any cookies that might carry session-like identifiers, validating and sanitizing OpenAPI schemas to ensure keys are marked as writeOnly and never included in examples or client-side schemas, and leveraging Echo’s middleware to strip or redact keys from logs. For automated oversight, the CLI tool middlebrick scan <url> can be integrated into CI/CD to fail builds when scans detect endpoints that return API keys in insecure contexts, and the Pro plan’s continuous monitoring can alert on regressions across deployed versions.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can XSS in Echo Go APIs be detected by middleBrick scans?
Yes. middleBrick tests input reflection and data exposure across 12 checks, including Input Validation and Data Exposure, and maps findings to frameworks like OWASP API Top 10 to highlight XSS risks and remediation guidance.
Should API keys ever be returned to browser-based clients in Echo Go responses?
No. API keys should remain server-side. If a key must be used client-side, use short-lived tokens scoped to specific origins and enforce strict Content-Security-Policy headers; however, the safest pattern is to keep keys on the backend and never echo them in API responses.