Fix XSS in API Responses in Tide
API-based XSS in Tide occurs when developers reflect untrusted input into responses without enforcing strict MIME types. If an endpoint returns user-controlled data with a 'text/html' header—or fails to set one, allowing the browser to sniff the content—attackers can execute arbitrary JavaScript in the context of the origin. In the Rust ecosystem, safety is a priority, but logic flaws in response handling still leave the door wide open.
The Vulnerable Pattern
use tide::Request;
async fn vuln_handler(req: Request<()>) -> tide::Result {
let user_input: String = req.param(“input”)?;
// VULNERABILITY: Direct string interpolation into a response.
// If a browser interprets this as HTML,
The Secure Implementation
To kill XSS in Tide APIs, you must break the browser's ability to interpret the response as HTML. First, never return raw strings; use Serde to serialize data into JSON via 'Body::from_json', which automatically sets 'Content-Type: application/json'. Second, implement 'X-Content-Type-Options: nosniff' to disable MIME-type sniffing, ensuring the browser doesn't try to 'helpfully' render your JSON as HTML. Finally, use a restrictive 'Content-Security-Policy' header to ensure no scripts can execute even if a bypass is found.
use tide::{Request, Response, StatusCode, Body};
use serde::Serialize;
#[derive(Serialize)]
struct ErrorResponse {
error: String,
}
async fn secure_handler(req: Request<()>) -> tide::Result {
let user_input: String = req.param(“input”)?;
let body = ErrorResponse { error: format!(“User {} not found”, user_input) };
let mut res = Response::new(StatusCode::NotFound);
// FIX 1: Use Body::from_json to force application/json and escape content
res.set_body(Body::from_json(&body)?);
// FIX 2: Explicitly set security headers to prevent MIME sniffing
res.insert_header("X-Content-Type-Options", "nosniff");
res.insert_header("Content-Security-Policy", "default-src 'none'");
Ok(res)
}
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.