Fix Mass Assignment in Grape
Mass assignment in Grape occurs when an application blindly accepts and processes user-supplied input to update model attributes. Without strict filtering, an attacker can inject 'over-posting' payloads to modify sensitive fields like 'is_admin', 'role', or 'balance' that should never be user-controllable.
The Vulnerable Pattern
resource :users do
desc 'Update user profile'
put ':id' do
user = User.find(params[:id])
# VULNERABLE: Directly passing the entire params hash to the model
# An attacker can send { "is_admin": true } in the JSON body
user.update(params)
present user
end
end
The Secure Implementation
The fix relies on Grape's `declared(params)` method. By default, the `params` hash contains every key sent in the request. The `declared` helper strips out any key that wasn't explicitly defined in the `params` DSL block. Setting `include_missing: false` prevents the inclusion of optional keys that weren't provided in the request, ensuring you don't overwrite existing data with nils. This creates a whitelist-only interface between the API and your ORM.
resource :users do
desc 'Update user profile'
params do
# Explicitly define allowed parameters
requires :email, type: String
optional :bio, type: String
# Sensitive fields like 'is_admin' are excluded here
end
put ':id' do
user = User.find(params[:id])
# SECURE: declared(params) filters the input to ONLY what is defined in the params block
safe_params = declared(params, include_missing: false)
user.update(safe_params)
present user
end
end
Your Grape API
might be exposed to Mass Assignment
74% of Grape 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.