Safely chain scopes with hash conditions

Updated . Posted . Visible to the public.

There is a nasty bug in all version of Rails 2 and some versions of Rails 3.x where two chained scopes with hash conditions on the same attribute would overwrite each other.

This is a horrible security issue if you are using scopes to limit what a user may see or change Show archive.org snapshot .

Workaround

If you are using an affected Rails version and cannot switch to a fixed version, you can use this manual workaround.

Copy the attached initializer into your project. You can then use a new pseudo-scope chain_safely that guarantees that conditions in the current chain are not going to be overwritten by the next chain link.

Use this for cases where you use scopes to restrict access, and want to further filter this scope based on user input:

class ArticlesController < ApplicationController

  def index
    articles = visible_articles
    articles = articles.chain_safely.for_users(params[:user_id_filter]) if params[:user_id_filter]
  end

  private

  def visible_articles
    current_user.articles
  end

end

Note that if you want to chain multiple scopes safely, you need to insert a chain_safely between each two links in the chain:

visible_article.chain_safely.some_scope.chain_safely.some_other_scope
Henning Koch
Last edit
Henning Koch
Attachments
Keywords
authorization
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-04-01 08:46)