GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Masonite

Cross-Site Scripting (XSS) in Masonite APIs typically manifests when a controller reflects unsanitized user input directly into the response body without enforcing strict content types. If the browser sniffs the response as HTML or if the 'Content-Type' is set to 'text/html', any injected scripts in the payload will execute in the context of the user's session.

The Vulnerable Pattern

from masonite.controllers import Controller
from masonite.request import Request

class SearchController(Controller): def show(self, request: Request): # VULNERABLE: Direct reflection of input in a string-based response # This defaults to text/html, allowing script injection via the ‘query’ parameter query = request.input(‘query’) return f’

Results for: {query}

The Secure Implementation

The vulnerability occurs because Masonite's default behavior for returning strings is to serve them as HTML. To mitigate this, always utilize the 'response.json()' method or return a dictionary, which forces the 'Content-Type: application/json' header. This prevents the browser from interpreting the response body as executable HTML/JavaScript. Furthermore, ensure that the 'X-Content-Type-Options: nosniff' header is enabled in your middleware to prevent MIME-type sniffing attacks.

from masonite.controllers import Controller
from masonite.request import Request
from masonite.response import Response

class SearchController(Controller): def show(self, request: Request, response: Response): # SECURE: Returning a dictionary or using response.json() # Masonite automatically sets Content-Type to application/json query = request.input(‘query’) return response.json({ ‘status’: ‘success’, ‘results_for’: query })

System Alert • ID: 7968
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.