Fix XSS in API Responses in Falcon
Falcon is optimized for speed, but performance doesn't excuse lazy output handling. XSS in Falcon APIs occurs when developers manually override content types to 'text/html' or 'text/xml' and reflect unsanitized query parameters or request bodies directly into the response. Even in JSON-based APIs, failing to enforce 'application/json' or 'X-Content-Type-Options: nosniff' can lead to MIME-sniffing exploits where the browser executes a payload hidden in a response.
The Vulnerable Pattern
import falcon
class UserProfile:
def on_get(self, req, resp):
# VULNERABLE: Directly reflecting query param into HTML response
username = req.get_param(‘username’) or ‘Guest’
resp.status = falcon.HTTP_200
resp.content_type = ‘text/html’
resp.text = f’
Profile of {username}
’
The Secure Implementation
The vulnerability exists because raw user input is concatenated into an HTML string. To secure this: 1. Default to 'resp.media' which uses Falcon's JSON handler; this ensures 'application/json' headers, preventing the browser from rendering the response as HTML. 2. If you must render HTML, use 'html.escape()' to neutralize characters like <, >, and ". 3. Implement a Middleware to globally apply 'X-Content-Type-Options: nosniff' and a strict 'Content-Security-Policy' (CSP) to block inline scripts and unauthorized sources.
import falcon
import html
class UserProfile:
def on_get(self, req, resp):
username = req.get_param(‘username’) or ‘Guest’
# SECURE OPTION 1: Return JSON (Best practice for APIs)
# Falcon sets Content-Type to application/json and handles encoding
resp.media = {'username': username}
# SECURE OPTION 2: If HTML is required, escape the input
# escaped_name = html.escape(username, quote=True)
# resp.status = falcon.HTTP_200
# resp.content_type = falcon.MEDIA_HTML
# resp.text = f'<html><body><h1>Profile of {escaped_name}</h1></body></html>'</code></pre>
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.