Fix XSS in API Responses in Camping
In the lightweight world of Camping, API responses are often just raw strings. If you aren't explicitly defining your Content-Type headers, you're leaving the door open for MIME-sniffing XSS. An attacker can inject a payload into a data field that, when reflected, triggers script execution because the browser treats the JSON-ish string as HTML.
The Vulnerable Pattern
module App::Controllers
class Profile < R '/profile/(\d+)'
def get(id)
user = Models::User.find(id)
# VULNERABLE: No Content-Type set. Browser might sniff this as text/html.
# If user.name contains , it executes.
"{ \"id\": #{user.id}, \"name\": \"#{user.name}\" }"
end
end
end
The Secure Implementation
The fix is two-fold. First, force the browser's hand by setting the 'Content-Type' header to 'application/json'. This prevents the browser from guessing that the response might be HTML. Second, never use string interpolation to build JSON. Using the 'json' gem's '.to_json' method ensures that any malicious characters (like quotes or angle brackets) are properly escaped according to the JSON spec, neutralizing the XSS payload even if the header is somehow bypassed.
require 'json'module App::Controllers class Profile < R ‘/profile/(\d+)’ def get(id) user = Models::User.find(id) # SECURE: Explicitly set Content-Type to application/json @headers[‘Content-Type’] = ‘application/json; charset=utf-8’
# SECURE: Use a real JSON serializer to handle escaping { id: user.id, name: user.name }.to_json end
end end
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.