Posted almost 8 years ago. Visible to the public.

Safely chain scopes with hash conditions

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.

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:

Copy
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:

Copy
visible_article.chain_safely.some_scope.chain_safely.some_other_scope

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Henning Koch
Last edit:
over 3 years ago
by Henning Koch
Attachments:
chain_safely.rb
Keywords:
authorization
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more