GuardAPI Logo
GuardAPI

Fix XSS in API Responses in TurboGears

TurboGears controllers are vulnerable to XSS when they reflect untrusted input in responses without explicit content-type enforcement. If a controller returns a raw string containing user input, the browser may sniff the response as 'text/html', allowing an attacker to execute arbitrary JavaScript in the victim's session.

The Vulnerable Pattern

from tg import expose

class RootController(BaseController): @expose() def echo(self, user_input): # VULNERABLE: Returns a raw string containing unsanitized input. # Browser may interpret this as HTML, leading to XSS. return “

User said: ” + user_input + "
"

The Secure Implementation

The vulnerability stems from the lack of a 'Content-Type' header that prevents HTML parsing. In the vulnerable example, @expose() defaults to a generic response that browsers often treat as HTML. By switching to @expose('json'), TurboGears utilizes its JSON renderer which automatically sets the 'Content-Type' to 'application/json' and serializes the output, neutralising HTML injection. For non-JSON responses, always use a templating engine like Kajiki or Mako which performs automatic contextual HTML escaping, and set 'X-Content-Type-Options: nosniff' in your middleware stack to prevent MIME-sniffing attacks.

from tg import expose

class RootController(BaseController): @expose(‘json’) def echo(self, user_input): # SECURE: Using the ‘json’ renderer forces ‘Content-Type: application/json’. # Modern browsers will not execute script blocks inside JSON payloads. return dict(message=“User said: ” + user_input)

System Alert • ID: 4016
Target: API Responses API
Potential Vulnerability

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.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.