How to fix Mass Assignment
in Plug
Executive Summary
Mass assignment in Plug-based applications (like Phoenix) occurs when raw, unsanitized request parameters are piped directly into internal structs or database changesets. Attackers exploit this by injecting unexpected keys (e.g., 'is_admin', 'role', 'balance') into the payload, which the application then blindly persists. If you're not explicitly whitelisting keys, you're giving users full control over your data model.
The Vulnerable Pattern
def update(conn, %{"id" => id, "user" => user_params}) do
user = Repo.get!(User, id)
# VULNERABLE: Blindly merging untrusted map into the struct
updated_user = Map.merge(user, user_params)
Repo.update(updated_user)
end
The Secure Implementation
The vulnerability stems from using generic map-merging functions like Map.merge/2 or struct/2 on raw input. This allows an attacker to overwrite any field in the database schema. The fix is to implement a 'Permitted Attributes' pattern. In Elixir, Ecto.Changeset.cast/3 is your primary defense; it acts as an allow-list filter, ignoring any key-value pairs in the input that are not explicitly defined in the second argument. Even if an attacker sends 'is_admin=true', the cast function will silently drop it if it's not in the whitelist.
def update(conn, %{"id" => id, "user" => user_params}) do user = Repo.get!(User, id) # SECURE: Use Ecto.Changeset.cast/3 to enforce a strict whitelist user |> User.update_changeset(user_params) |> Repo.update() endIn User schema
def update_changeset(user, attrs) do user |> cast(attrs, [:username, :bio, :email]) # Only these fields can be modified |> validate_required([:username]) end
Your Plug API
might be exposed to Mass Assignment
74% of Plug 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.