How to fix Mass Assignment
in Phoenix
Executive Summary
Mass assignment in Phoenix/Ecto occurs when an application blindly accepts user-supplied input to update database records. Attackers exploit this by injecting extra keys into the JSON payload (e.g., 'is_admin': true) which are then processed by the Ecto changeset. If the changeset doesn't strictly whitelist fields, sensitive internal state can be manipulated.
The Vulnerable Pattern
def update_user(user, attrs) do
user
|> Ecto.Changeset.cast(attrs, Map.keys(attrs)) # DANGEROUS: Permitting all keys provided by user
|> Ecto.Changeset.validate_required([:email])
|> Repo.update()
end
The Secure Implementation
The primary defense is the `cast/3` function. Unlike `change/2`, `cast/3` filters the input map against a predefined list of allowed atoms. To fix mass assignment: 1. Never use `Map.keys(attrs)` or dynamic key generation in your changeset. 2. Implement 'Context-Specific Changesets'—create different functions for 'public' profile updates versus 'internal' administrative updates. 3. Treat the permitted fields list as a strict security boundary. If a field like 'permissions', 'balance', or 'owner_id' isn't in the list, Ecto will silently ignore it during the cast, neutralizing the injection.
def update_profile(user, attrs) do # SECURE: Explicitly whitelist only non-sensitive fields user |> Ecto.Changeset.cast(attrs, [:username, :bio, :avatar_url]) |> Ecto.Changeset.validate_required([:username]) |> Repo.update() enddef change_role(user, attrs) do
SECURE: Separate changeset for privileged operations, restricted to admin controllers
user |> Ecto.Changeset.cast(attrs, [:role]) |> Repo.update() end
Your Phoenix API
might be exposed to Mass Assignment
74% of Phoenix 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.