Fix XSS in API Responses in Hug
In Hug, XSS vulnerabilities typically manifest when developers use custom output formatters or the built-in HTML formatter to reflect unsanitized user input directly into the response body. Even in APIs, if a 'Content-Type' is misconfigured or a browser is tricked into sniffing the content as HTML, an attacker can execute arbitrary JavaScript in the context of the victim's session.
The Vulnerable Pattern
import hug
@hug.get(‘/user/profile’, output=hug.output_format.html)
def profile(username: str):
# VULNERABLE: Direct reflection of input into HTML without escaping
return f’
User: {username}
‘
The Secure Implementation
The vulnerability occurs because Hug's HTML output formatter does not automatically encode entities. By passing '' as the username, the payload executes in the browser. The fix involves two layers: 1) Defaulting to 'application/json' which prevents the browser from rendering the response as markup, and 2) Using 'html.escape()' to neutralize special characters if an HTML response is strictly necessary. Always enforce strict 'Content-Type' headers and avoid 'hug.output_format.text' for user-controlled strings.
import hug
import html
Approach 1: Use JSON (Default/Best Practice for APIs)
@hug.get(‘/user/profile/json’)
def profile_json(username: str):
return {‘username’: username}
Approach 2: Explicitly escape HTML if HTML output is required
@hug.get(‘/user/profile/html’, output=hug.output_format.html)
def profile_html(username: str):
safe_username = html.escape(username, quote=True)
return f’
User: {safe_username}
’
Your API Responses API
might be exposed to XSS
74% of API Responses apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.