Fix Mass Assignment in Ktor
Mass Assignment (or Overposting) in Ktor occurs when the application deserializes untrusted JSON directly into internal domain models or database entities. By injecting unexpected keys into the request body, an attacker can overwrite sensitive fields like 'is_admin', 'role', or 'balance' that were never intended to be user-mutable.
The Vulnerable Pattern
data class UserAccount(val id: Int, var username: String, var isAdmin: Boolean = false)
post(“/profile/update”) { // VULNERABLE: Directly receiving the entity class from the request val updatedData = call.receive() userRepository.update(updatedData) call.respond(HttpStatusCode.OK) }
The Secure Implementation
To kill Mass Assignment, you must decouple your API contract from your persistence layer. The fix involves implementing Data Transfer Objects (DTOs) that act as strict whitelists. In the secure example, even if an attacker sends '{"username": "hacker", "isAdmin": true}', the Ktor ContentNegotiation plugin only maps the 'username' field to the ProfileUpdateRequest. The 'isAdmin' field is discarded during deserialization, preventing unauthorized privilege escalation.
data class ProfileUpdateRequest(val username: String)post(“/profile/update”) { // SECURE: Use a dedicated DTO to whitelist allowed fields val request = call.receive
() val userId = call.sessions.get ()?.id ?: throw UnauthorizedException() val user = userRepository.findById(userId) user.username = request.username userRepository.save(user) call.respond(HttpStatusCode.OK)
}
Your Ktor API
might be exposed to Mass Assignment
74% of Ktor 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.