Fix XSS in API Responses in CherryPy
XSS in APIs occurs when an endpoint reflects untrusted input in a response without proper sanitization or incorrect Content-Type headers. In CherryPy, if a response is served as 'text/html' (often the default) instead of 'application/json', or if 'X-Content-Type-Options: nosniff' is missing, browsers may interpret the payload as executable script. Secure API design requires strict MIME type enforcement and proper output encoding.
The Vulnerable Pattern
import cherrypyclass VulnerableAPI: @cherrypy.expose def error(self, msg): # VULNERABLE: Directly reflects input. # If msg is , the browser may execute it. return f”{{‘status’: ‘error’, ‘message’: ‘{msg}’}}”
cherrypy.quickstart(VulnerableAPI())
The Secure Implementation
The vulnerability is mitigated by forcing the browser to treat the response strictly as data, not markup. First, the `@cherrypy.tools.json_out()` decorator ensures the 'Content-Type' is 'application/json', which prevents modern browsers from executing HTML. Second, we manually set 'X-Content-Type-Options: nosniff' to disable MIME-sniffing, which stops older browsers from 'guessing' if the content is HTML. Finally, returning a Python dictionary to the JSON tool ensures that all characters (like <, >, &) are correctly escaped during serialization, neutralizing any injected script tags.
import cherrypy import jsonclass SecureAPI: @cherrypy.expose @cherrypy.tools.json_out() def error(self, msg): # SECURE: json_out tool sets ‘Content-Type: application/json’. # Security headers prevent MIME sniffing. cherrypy.response.headers[‘X-Content-Type-Options’] = ‘nosniff’ cherrypy.response.headers[‘Content-Security-Policy’] = “default-src ‘none’”
# Return a dictionary; the tool handles safe JSON serialization. return {'status': 'error', 'message': msg}
cherrypy.quickstart(SecureAPI())
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.