GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Ktor

XSS in Ktor APIs occurs when user-controlled input is reflected in response bodies without proper output encoding or when the 'Content-Type' is incorrectly set to 'text/html'. This allows an attacker to inject malicious scripts that execute in the victim's browser context. To mitigate this, you must enforce strict content types and utilize context-aware escaping.

The Vulnerable Pattern

get("/v1/search") {
    val query = call.parameters["q"] ?: ""
    // VULNERABLE: Direct reflection into HTML context without sanitization
    call.respondText("Results for: $query", ContentType.Text.Html)
}

The Secure Implementation

The vulnerability exists because Ktor's respondText allows manual definition of the Content-Type. If set to Text.Html, the browser renders the payload as a document. The fix involves three layers: 1. Data Serialization: Use 'ContentNegotiation' to return JSON; browsers treat this as data, not executable code. 2. Auto-Escaping: If rendering HTML, use the 'ktor-server-html-builder' DSL which escapes special characters by default. 3. Security Headers: Deploy the 'DefaultHeaders' plugin to set 'X-Content-Type-Options: nosniff' and a strict 'Content-Security-Policy' to prevent unauthorized script execution even if an injection occurs.

install(ContentNegotiation) {
    json()
}

@Serializable data class SearchResponse(val query: String, val results: List)

get(“/v1/search”) { val query = call.parameters[“q”] ?: "" // SECURE: Use Content-Type: application/json. Browsers do not execute scripts in JSON contexts. call.respond(SearchResponse(query = query, results = emptyList())) }

// ALTERNATIVE: If HTML is required, use Ktor’s HTML DSL for auto-escaping get(“/v1/search-ui”) { val query = call.parameters[“q”] ?: "" call.respondHtml { body { p { +“Results for: $query” } // The ’+’ operator automatically HTML-escapes the string } } }

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