GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Rocket

Rust doesn't save you from logic-level XSS. If your Rocket API endpoints reflect user-controlled input into a response context that a browser can interpret as HTML, you've got an injection vector. The goal is to enforce strict Content-Type headers and ensure data is never interpreted as markup.

The Vulnerable Pattern

use rocket::response::content;

#[get(“/api/greet?name=”)] fn vulnerable_greet(name: &str) -> content::RawHtml { // EXPLOIT: /api/greet?name= // Returning RawHtml treats the input as executable markup. content::RawHtml(format!(“

Hello, {}

”, name)) }

The Secure Implementation

The vulnerability stems from using `content::RawHtml`, which sets the `Content-Type` to `text/html`. An attacker can break out of the intended H1 tag and inject a script block. The fix involves three layers: 1. Use the `Json` responder to ensure the response is served as `application/json`, which prevents the browser from sniffing the content as HTML. 2. If you must return HTML, use a templating engine like `rocket_dyn_templates` (Tera/Handlebars) which performs automatic contextual output encoding. 3. Set a strict `Content-Security-Policy` header globally to block inline scripts as a defense-in-depth measure.

use rocket::serde::json::{Json, serde_json};
use serde::Serialize;

#[derive(Serialize)] struct GreetResponse { message: String, }

#[get(“/api/greet?name=”)] fn secure_greet(name: &str) -> Json { // FIX: Use the Json responder to force Content-Type: application/json // The browser will treat the payload as data, not as an HTML document. Json(GreetResponse { message: format!(“Hello, {}”, name), }) }

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