Is it safe to use search parameters [: id] in Rails?

Rails commonly uses expressions like the following:

@project = Project.find params[:id] # example 1

@project = current_user.projects.find params[:project_id] # example 2

However, I understand that it findalso accepts arrays! This would mean unexpected and potentially dangerous code behavior that is written with the assumption that @projectthis is a single project, not an array.

Now the question is:

  • should i output params[:id].to_severy time i use it in find?
  • Should I use strong parameters with findto avoid arrays? find params.permit(:id)[:id])? (better than to_sif you do not want to convert nilto "")
  • Are there any other alternatives or common practices?

The above vulnerability appears only if the routes do not define a parameter with this name .

For instance:

# SAFE routes.rb
resources :projects

# projects_controller.rb
Project.find params[:id]

The query /projects/3?id[]=4&id[]=5produces only {id: 3}as a parameter. This would make the use Project.find params[:id]safe: however, I cannot find documentation for this behavior and I don’t know if I can rely on it: maybe it is just by chance .

In addition, the following is not equivalent at all and would create a vulnerability in controllers:

# Likely UNSAFE routes.rb
# E.g.: 
# /projects?id=3 => params = {id: 3}
# /projects?id[]=3&id[]=4 => params = {id: [3, 4]}
put '/projects' => 'projects#update'
+4
source share

Source: https://habr.com/ru/post/1653295/


All Articles