• This repository has been archived on 17/Aug/2017
  • Stars
    star
    1,271
  • Rank 35,493 (Top 0.8 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 12 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Taint and required checking for Action Pack and enforcement in Active Model

Build Status Gem Version

Strong Parameters

With this plugin Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted. This means you'll have to make a conscious choice about which attributes to allow for mass updating and thus prevent accidentally exposing that which shouldn't be exposed.

In addition, parameters can be marked as required and flow through a predefined raise/rescue flow to end up as a 400 Bad Request with no effort.

class PeopleController < ActionController::Base
  # This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment
  # without an explicit permit step.
  def create
    Person.create(params[:person])
  end

  # This will pass with flying colors as long as there's a person key in the parameters, otherwise
  # it'll raise an ActionController::ParameterMissing exception, which will get caught by
  # ActionController::Base and turned into that 400 Bad Request reply.
  def update
    person = current_account.people.find(params[:id])
    person.update_attributes!(person_params)
    redirect_to person
  end

  private
    # Using a private method to encapsulate the permissible parameters is just a good pattern
    # since you'll be able to reuse the same permit list between create and update. Also, you
    # can specialize this method with per-user checking of permissible attributes.
    def person_params
      params.require(:person).permit(:name, :age)
    end
end

Permitted Scalar Values

Given

params.permit(:id)

the key :id will pass the whitelisting if it appears in params and it has a permitted scalar value associated. Otherwise the key is going to be filtered out, so arrays, hashes, or any other objects cannot be injected.

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

params.permit(:id => [])

To whitelist an entire hash of parameters, the permit! method can be used

params.require(:log_entry).permit!

This will mark the :log_entry parameters hash and any subhash of it permitted. Extreme care should be taken when using permit! as it will allow all current and future model attributes to be mass-assigned.

Nested Parameters

You can also use permit on nested parameters, like:

params.permit(:name, {:emails => []}, :friends => [ :name, { :family => [ :name ], :hobbies => [] }])

This declaration whitelists the name, emails and friends attributes. It is expected that emails will be an array of permitted scalar values and that friends will be an array of resources with specific attributes : they should have a name attribute (any permitted scalar values allowed), a hobbies attribute as an array of permitted scalar values, and a family attribute which is restricted to having a name (any permitted scalar values allowed, too).

Thanks to Nick Kallen for the permit idea!

Require Multiple Parameters

If you want to make sure that multiple keys are present in a params hash, you can call the method twice:

params.require(:token)
params.require(:post).permit(:title)

Handling of Unpermitted Keys

By default parameter keys that are not explicitly permitted will be logged in the development and test environment. In other environments these parameters will simply be filtered out and ignored.

Additionally, this behaviour can be changed by changing the config.action_controller.action_on_unpermitted_parameters property in your environment files. If set to :log the unpermitted attributes will be logged, if set to :raise an exception will be raised.

Use Outside of Controllers

While Strong Parameters will enforce permitted and required values in your application controllers, keep in mind that you will need to sanitize untrusted data used for mass assignment when in use outside of controllers.

For example, if you retrieve JSON data from a third party API call and pass the unchecked parsed result on to Model.create, undesired mass assignments could take place. You can alleviate this risk by slicing the hash data, or wrapping the data in a new instance of ActionController::Parameters and declaring permissions the same as you would in a controller. For example:

raw_parameters = { :email => "[email protected]", :name => "John", :admin => true }
parameters = ActionController::Parameters.new(raw_parameters)
user = User.create(parameters.permit(:name, :email))

More Examples

Head over to the Rails guide about Action Controller.

Installation

In Gemfile:

gem 'strong_parameters'

and then run bundle. To activate the strong parameters, you need to include this module in every model you want protected.

class Post < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection
end

Alternatively, you can protect all Active Record resources by default by creating an initializer and pasting the line:

ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

If you want to now disable the default whitelisting that occurs in Rails 3.2, change the config.active_record.whitelist_attributes property in your config/application.rb:

config.active_record.whitelist_attributes = false

This will allow you to remove / not have to use attr_accessible and do mass assignment inside your code and tests.

Migration Path to Rails 4

In order to have an idiomatic Rails 4 application, Rails 3 applications may use this gem to introduce strong parameters in preparation for their upgrade.

The following is a way to do that gradually:

1 Depend on strong_parameters

Add this gem to the application Gemfile:

gem 'strong_parameters'

and run bundle install.

After this change, the params object in requests is of type ActionController::Parameters. That is a subclass of ActiveSupport::HashWithIndifferentAccess and therefore everything should work as before. The test suite should be green, and the application can be deployed.

2 Compute a Topological Sort of Active Record Models

We are going to work model by model, and the natural order to do that systematically is topological. That is, if post has many comments, first you do Post, and later you do Comment.

Reason is that order plays well with nested attributes. You can mass-assign ActionController::Parameters to Post, and if that includes comments_attributes and the Comment model is not yet done, it will work. But if Comment is done first, then the mass-assigning to Post won't permit its attributes and won't work.

This script prints a topological sort of the Active Record models to standard output:

require 'tsort'
require 'set'

class Graph < Hash
  include TSort

  alias tsort_each_node each_key

  def tsort_each_child(node, &block)
    fetch(node).each(&block)
  end
end

def children(model)
  Set.new.tap do |children|
    model.reflect_on_all_associations.each do |association|
      next unless [:has_many, :has_one].include?(association.macro)
      next if association.options[:through]

      children << association.klass
    end
  end
end

Dir.glob('app/models/**/*.rb') do |model|
  load model
end

graph = Graph.new
ActiveRecord::Base.descendants.each do |model|
  graph[model] = children(model) unless model.abstract_class?
end

graph.tsort.reverse_each do |klass|
  puts klass.name
end

Execute it with rails runner.

3 Protect Every Active Record Model, One at a Time

Once the dependency is in place and the topological listing computed, you can work model by model. Do one model, deploy. Do another model, deploy. Etc.

For each model:

3.1 Add Protection

Remove any attr_accessible or attr_protected declarations and include ActiveModel::ForbiddenAttributesProtection:

class Post < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection
end

3.2 (Optional) Check the Suite is Red

If the application performs any mass-assignment into that model, the test suite should not pass. Expect the test suite to raise ActiveModel::ForbiddenAttributes in those spots.

If the test suite is green, either it lacks coverage (fix it), or there is no mass-assignment going on (ready to deploy).

3.3 Whitelisting

Go to every controller whose actions trigger mass-assignment on that model via params and sanitize the input data using require and permit, as explained above.

3.4 Deploy

Once everything is whitelisted and the suite is green, this particular model can be pushed.

Ready to work on the next model.

4 Add Protection Globally

Once all models are done, remove their inclusion of the protecting module:

class Post < ActiveRecord::Base
  # REMOVE THIS LINE IN EVERY PERSISTENT MODEL
  include ActiveModel::ForbiddenAttributesProtection
end

and add it globally in an initializer:

# config/initializers/strong_parameters.rb
ActiveRecord::Base.class_eval do
  include ActiveModel::ForbiddenAttributesProtection
end

5 Upgrade to Rails 4

To upgrade to Rails 4 just remove the previous initializer, everything else is ready as far as strong parameters is concerned.

Compatibility

This plugin is only fully compatible with Rails versions 3.0, 3.1 and 3.2 but not 4.0+, as it is part of Rails Core in 4.0. An unofficial Rails 2 version is strong_parameters_rails2.

More Repositories

1

rails

Ruby on Rails
Ruby
54,600
star
2

webpacker

Use Webpack to manage app-like JavaScript modules in Rails
Ruby
5,313
star
3

thor

Thor is a toolkit for building powerful command-line interfaces.
Ruby
5,066
star
4

jbuilder

Jbuilder: generate JSON objects with a Builder-style DSL
Ruby
4,298
star
5

spring

Rails application preloader
Ruby
2,782
star
6

jquery-ujs

Ruby on Rails unobtrusive scripting adapter for jQuery
JavaScript
2,610
star
7

rails-dev-box

A virtual machine for Ruby on Rails core development
Shell
2,049
star
8

tailwindcss-rails

Ruby
1,343
star
9

kredis

Higher-level data structures built on Redis
Ruby
1,341
star
10

activeresource

Connects business objects and REST web services
Ruby
1,309
star
11

docked

Running Rails from Docker for easy start to development
Dockerfile
1,262
star
12

globalid

Identify app models with a URI
Ruby
1,164
star
13

actioncable

Framework for real-time communication over websockets
1,087
star
14

importmap-rails

Use ESM with importmap to manage modern JavaScript in Rails without transpiling or bundling.
Ruby
990
star
15

jquery-rails

A gem to automate using jQuery with Rails
Ruby
946
star
16

sprockets

Rack-based asset packaging system
Ruby
919
star
17

sass-rails

Ruby on Rails stylesheet engine for Sass
Ruby
858
star
18

exception_notification

NOTICE: official repository moved to https://github.com/smartinez87/exception_notification
Ruby
844
star
19

sdoc

Standalone sdoc generator
JavaScript
820
star
20

propshaft

Deliver assets for Rails
Ruby
785
star
21

jsbundling-rails

Bundle and transpile JavaScript in Rails with esbuild, rollup.js, or Webpack.
Ruby
778
star
22

rails-perftest

Benchmark and profile your Rails apps
Ruby
775
star
23

activejob

Declare job classes that can be run by a variety of queueing backends
Ruby
746
star
24

activestorage

Store files in Rails applications
734
star
25

solid_cache

A database-backed ActiveSupport::Cache::Store
Ruby
682
star
26

pjax_rails

PJAX integration for Rails
Ruby
670
star
27

actioncable-examples

Action Cable Examples
Ruby
663
star
28

cache_digests

Ruby
644
star
29

sprockets-rails

Sprockets Rails integration
Ruby
569
star
30

cssbundling-rails

Bundle and process CSS in Rails with Tailwind, PostCSS, and Sass via Node.js.
Ruby
539
star
31

activerecord-session_store

Active Record's Session Store extracted from Rails
Ruby
524
star
32

rails-observers

Rails observer (removed from core in Rails 4.0)
Ruby
513
star
33

execjs

Run JavaScript code from Ruby
Ruby
509
star
34

actiontext

Edit and display rich text in Rails applications
406
star
35

acts_as_list

NOTICE: official repository moved to https://github.com/swanandp/acts_as_list
Ruby
384
star
36

marcel

Find the mime type of files, examining file, filename and declared type
Ruby
369
star
37

request.js

JavaScript
356
star
38

actionpack-page_caching

Static page caching for Action Pack (removed from core in Rails 4.0)
Ruby
343
star
39

commands

Run Rake/Rails commands through the console
Ruby
338
star
40

ssl_requirement

NOTICE: official repository moved to https://github.com/retr0h/ssl_requirement
Ruby
315
star
41

rubocop-rails-omakase

Omakase Ruby styling for Rails
Ruby
310
star
42

rails-controller-testing

Brings back `assigns` and `assert_template` to your Rails tests
Ruby
295
star
43

rails-html-sanitizer

Ruby
294
star
44

open_id_authentication

NOTICE: official repository moved to https://github.com/Velir/open_id_authentication
Ruby
284
star
45

acts_as_tree

NOTICE: official repository moved to https://github.com/amerine/acts_as_tree
Ruby
279
star
46

actionpack-action_caching

Action caching for Action Pack (removed from core in Rails 4.0)
Ruby
260
star
47

in_place_editing

NOTICE: official repository moved to https://github.com/amerine/in_place_editing
Ruby
230
star
48

protected_attributes

Protect attributes from mass-assignment in ActiveRecord models.
Ruby
230
star
49

journey

A router for rails
Ruby
221
star
50

auto_complete

NOTICE: official repository moved to https://github.com/david-kerins/auto_complete
Ruby
211
star
51

dartsass-rails

Integrate Dart Sass with the asset pipeline in Rails
Ruby
192
star
52

dynamic_form

NOTICE: official repository moved to https://github.com/joelmoss/dynamic_form
Ruby
192
star
53

country_select

NOTICE: official repository moved to https://github.com/stefanpenner/country_select
Ruby
176
star
54

rails-dom-testing

Extracting DomAssertions and SelectorAssertions from ActionView.
Ruby
168
star
55

routing_concerns

Abstract common routing resource concerns to cut down on duplication.
Ruby
154
star
56

esbuild-rails

Bundle and transpile JavaScript in Rails with esbuild
Ruby
147
star
57

rails-contributors

The web application that runs https://contributors.rubyonrails.org
Ruby
136
star
58

actionmailbox

Receive and process incoming emails in Rails
125
star
59

requestjs-rails

JavaScript
103
star
60

activemodel-globalid

Serializing models to a single string makes it easy to pass references around
Ruby
90
star
61

account_location

NOTICE: official repository moved to https://github.com/bbommarito/account_location
Ruby
73
star
62

acts_as_nested_set

NOTICE: official repository moved to https://github.com/bbommarito/acts_as_nested_set
Ruby
71
star
63

iso-3166-country-select

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
70
star
64

activerecord-deprecated_finders

Ruby
68
star
65

spring-watcher-listen

Ruby
63
star
66

weblog

Superseded by https://github.com/rails/website
HTML
63
star
67

prototype-ujs

JavaScript
62
star
68

prototype_legacy_helper

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
60
star
69

verification

NOTICE: official repository moved to https://github.com/sikachu/verification
Ruby
58
star
70

website

HTML
55
star
71

prototype-rails

Add RJS, Prototype, and Scriptaculous helpers to Rails 3.1+ apps
Ruby
55
star
72

activemodel-serializers-xml

Ruby
52
star
73

record_tag_helper

ActionView Record Tag Helpers
Ruby
50
star
74

homepage

Superseded by https://github.com/rails/website
HTML
50
star
75

rollupjs-rails

Bundle and transpile JavaScript in Rails with rollup.js
Ruby
49
star
76

actionpack-xml_parser

XML parameters parser for Action Pack (removed from core in Rails 4.0)
Ruby
49
star
77

activesupport-json_encoder

Ruby
48
star
78

etagger

Declare what goes in to your ETags: asset versions, account ID, etc.
Ruby
41
star
79

upload_progress

NOTICE: official repository moved to https://github.com/rishav/upload_progress
Ruby
39
star
80

atom_feed_helper

NOTICE: official repository moved to https://github.com/TrevorBramble/atom_feed_helper
Ruby
38
star
81

render_component

NOTICE: official repository moved to https://github.com/malev/render_component. Components allow you to call other actions for their rendered response while executing another action
Ruby
38
star
82

gsoc2014

Project website and wiki for Ruby on Rails proposals to Google Summer of Code 2014
37
star
83

gsoc2013

Project website and wiki for Ruby on Rails proposals to Google Summer of Code 2013
31
star
84

ruby-coffee-script

Ruby CoffeeScript Compiler
Ruby
28
star
85

asset_server

NOTICE: official repository moved to https://github.com/andhapp/asset_server
Ruby
27
star
86

homepage-2011

This repo is now legacy. New homepage is at rails/homepage
HTML
26
star
87

deadlock_retry

NOTICE: official repository moved to https://github.com/heaps/deadlock_retry
Ruby
26
star
88

token_generator

NOTICE: official repository moved to https://github.com/bbommarito/token_generator
Ruby
25
star
89

rails-docs-server

Ruby
24
star
90

http_authentication

NOTICE: official repository moved to https://github.com/dshimy/http_authentication
Ruby
22
star
91

irs_process_scripts

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core. The extracted inspector, reaper, and spawner scripts from script/process/*
22
star
92

javascript_test

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
JavaScript
19
star
93

rails_fast_attributes

Experimental project
Rust
18
star
94

scriptaculous_slider

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
JavaScript
18
star
95

rails-ujs

Ruby on Rails unobtrusive scripting adapter
17
star
96

request_profiler

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core. Request profiler based on integration test scripts
Ruby
17
star
97

scaffolding

NOTICE: official repository moved to https://github.com/KeysetTS/scaffolding
Ruby
17
star
98

rails-new

Shell
16
star
99

buildkite-config

Fallback configuration for branches that lack a .buildkite/ directory
Ruby
16
star
100

tzinfo_timezone

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
13
star