GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix Mass Assignment
in Vapor (Swift)

Executive Summary

Mass Assignment in Vapor occurs when an application binds HTTP request parameters directly to a Fluent database model. This allows an attacker to manipulate protected fields—such as 'isAdmin', 'role', or 'balance'—simply by including them in the JSON payload of a POST or PUT request. If you decode directly into your Model, you're giving the client write-access to your database schema.

The Vulnerable Pattern

VULNERABLE CODE
app.post("profile", "update") { req -> EventLoopFuture in
    // VULNERABLE: Decoding directly into the Fluent Model
    let updatedUser = try req.content.decode(User.self)
    return User.find(req.auth.get(User.self)?.id, on: req.db)
        .unwrap(or: Abort(.notFound))
        .flatMap { user in
            // Attacker can pass {"isAdmin": true} in JSON to escalate privileges
            user.username = updatedUser.username
            user.isAdmin = updatedUser.isAdmin
            return user.save(on: req.db).transform(to: .ok)
        }
}

The Secure Implementation

The fix involves decoupling your API contract from your database schema. By using a Data Transfer Object (DTO)—a simple struct conforming to 'Content'—you create a whitelist of allowed fields. Even if an attacker sends extra fields in the JSON payload, the 'UpdateUserRequest' struct will ignore them during decoding. Only the properties explicitly defined in the DTO are mapped to the Fluent model, ensuring that sensitive internal state remains immutable from the frontend.

SECURE CODE
struct UpdateUserRequest: Content {
    var username: String
    // Notice: isAdmin is omitted here
}

app.post(“profile”, “update”) { req -> EventLoopFuture in // SECURE: Decoding into a dedicated Data Transfer Object (DTO) let input = try req.content.decode(UpdateUserRequest.self) return User.find(req.auth.get(User.self)?.id, on: req.db) .unwrap(or: Abort(.notFound)) .flatMap { user in user.username = input.username // Internal fields are never touched by user input return user.save(on: req.db).transform(to: .ok) } }

System Alert • ID: 7475
Target: Vapor (Swift) API
Potential Vulnerability

Your Vapor (Swift) API might be exposed to Mass Assignment

74% of Vapor (Swift) 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.