Fix Mass Assignment in Hanami
Mass Assignment in Hanami occurs when untrusted user input is passed directly into a Repository or Entity without explicit filtering. If an attacker can guess internal attribute names like 'is_admin' or 'account_balance', they can escalate privileges or modify restricted data. In Hanami, the defense-in-depth approach leverages dry-validation schemas within the Action layer to strictly whitelist incoming data.
The Vulnerable Pattern
# app/actions/users/update.rb
module Web
module Actions
module Users
class Update < Web::Action
def handle(req, res)
user_repo = UserRepository.new
# VULNERABLE: Passing raw request params directly to the repository
# An attacker can send { "user": { "admin": true } } to escalate privileges
user_repo.update(req.params[:id], req.params[:user])
res.status = 200
end
end
end
end
end
The Secure Implementation
To kill Mass Assignment in Hanami, you must utilize the 'params' block in your Actions. This block uses dry-validation to create a schema that acts as a gatekeeper. When you access 'req.params', Hanami only provides the keys explicitly defined in that schema. Even if an attacker injects 'admin: true' into the JSON payload, the repository never sees it because it is filtered out during the validation phase. Always call '.valid?' and only process data that passes the schema check.
# app/actions/users/update.rb module Web module Actions module Users class Update < Web::Action # SECURE: Define a strict schema to whitelist only specific fields params do required(:id).filled(:integer) required(:user).hash do required(:email).filled(:string) optional(:bio).maybe(:string) # 'admin' or 'role' fields are omitted, so they are stripped even if sent end enddef handle(req, res) if req.params.valid? user_repo = UserRepository.new # SECURE: req.params.to_h only returns the whitelisted data user_repo.update(req.params[:id], req.params[:user]) res.status = 200 else res.status = 422 end end end end
end end
Your Hanami API
might be exposed to Mass Assignment
74% of Hanami 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.