GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix XSS in API Responses
in Salvo

Executive Summary

Salvo's performance is top-tier, but misconfiguring response types turns your API into an XSS delivery vehicle. If your endpoint reflects user-controlled input without strict Content-Type enforcement (specifically application/json), browsers might sniff the content as HTML and execute malicious payloads. Don't let your API act like a template engine.

The Vulnerable Pattern

VULNERABLE CODE
use salvo::prelude::*;

#[handler] async fn vuln_api(req: &mut Request, res: &mut Response) { let user_id = req.query::(“id”).unwrap_or_default(); // VULNERABLE: Reflecting input directly in a response that defaults to or allows text/html // An attacker sends: ?id= res.render(Text::Html(format!(”{{“status”: “error”, “id”: ”{}”}}”, user_id))); }

The Secure Implementation

The vulnerability stems from manual string concatenation and the use of `Text::Html`, which sets the `Content-Type` to `text/html`. This allows a browser to interpret the JSON-like string as an HTML document, triggering any embedded scripts. The fix involves two layers: 1. Use Salvo's `Json` renderer which explicitly sets `Content-Type: application/json`. 2. Utilize `serde` for serialization. This ensures that the data is treated as a literal string within a JSON structure, preventing the browser's parser from ever reaching an 'execution' state for HTML tags.

SECURE CODE
use salvo::prelude::*;
use serde::Serialize;

#[derive(Serialize)] struct ErrorResponse { status: String, id: String, }

#[handler] async fn secure_api(req: &mut Request, res: &mut Response) { let user_id = req.query::(“id”).unwrap_or_default();

// SECURE: Use the Json helper to force application/json and proper serialization
res.render(Json(ErrorResponse {
    status: "error".to_string(),
    id: user_id,
}));

}

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