Today I came across an interesting issue in a Rails app. A simple params[:key] was throwing an error.
Why that happens
It turns out that while params[:something] is often assumed to be either a string or nil, but that isn’t always the case. It can also become arrays or hashes.
Passing ?page or ?page[string] will automatically turn parameters to either arrays or hashes.
Security issues ahead
Whenever using params[:key], it would be wise to think “what if an array/hash is passed here?“. In this hypothetical example, the intention might be to delete one record, but it might unintentionally allow multiple deletions.
Thankfully this won't work, because Rails has #destroy_all for collections rather than #destroy.
Hey! I write articles about web development and productivity. If you'd like
to support me, subscribe to the email list so you don't miss out on updates.
Solution: strong parameters
Rails 5’s new Strong Parameters feature prevents from issues like this. Using #permit will prevent arrays and hashes from coming through.
Using params.permit will reject hashes and arrays.
In contrast, using params.require will only let hashes and arrays through. Using both permit and require can be used to define the shape of the expected input.