{"id":13747593,"url":"https://github.com/rails/strong_parameters","last_synced_at":"2025-09-29T20:31:23.621Z","repository":{"id":2716127,"uuid":"3710607","full_name":"rails/strong_parameters","owner":"rails","description":"Taint and required checking for Action Pack and enforcement in Active Model","archived":true,"fork":false,"pushed_at":"2017-08-08T18:36:31.000Z","size":169,"stargazers_count":1271,"open_issues_count":65,"forks_count":167,"subscribers_count":44,"default_branch":"master","last_synced_at":"2024-05-23T09:44:38.517Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rails.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-03-13T19:48:14.000Z","updated_at":"2024-02-20T23:12:56.000Z","dependencies_parsed_at":"2022-09-03T12:01:11.365Z","dependency_job_id":null,"html_url":"https://github.com/rails/strong_parameters","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rails%2Fstrong_parameters","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rails%2Fstrong_parameters/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rails%2Fstrong_parameters/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rails%2Fstrong_parameters/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rails","download_url":"https://codeload.github.com/rails/strong_parameters/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234659883,"owners_count":18867634,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T06:01:34.572Z","updated_at":"2025-09-29T20:31:18.322Z","avatar_url":"https://github.com/rails.png","language":"Ruby","readme":"[![Build Status](https://travis-ci.org/rails/strong_parameters.svg?branch=master)](https://travis-ci.org/rails/strong_parameters)\n[![Gem Version](https://badge.fury.io/rb/strong_parameters.svg)](http://badge.fury.io/rb/strong_parameters)\n\n# Strong Parameters\n\nWith 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.\n\nIn 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.\n\n``` ruby\nclass PeopleController \u003c ActionController::Base\n  # This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment\n  # without an explicit permit step.\n  def create\n    Person.create(params[:person])\n  end\n\n  # This will pass with flying colors as long as there's a person key in the parameters, otherwise\n  # it'll raise an ActionController::ParameterMissing exception, which will get caught by\n  # ActionController::Base and turned into that 400 Bad Request reply.\n  def update\n    person = current_account.people.find(params[:id])\n    person.update_attributes!(person_params)\n    redirect_to person\n  end\n\n  private\n    # Using a private method to encapsulate the permissible parameters is just a good pattern\n    # since you'll be able to reuse the same permit list between create and update. Also, you\n    # can specialize this method with per-user checking of permissible attributes.\n    def person_params\n      params.require(:person).permit(:name, :age)\n    end\nend\n```\n\n## Permitted Scalar Values\n\nGiven\n\n``` ruby\nparams.permit(:id)\n```\n\nthe 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.\n\nThe permitted scalar types are `String`, `Symbol`, `NilClass`, `Numeric`, `TrueClass`, `FalseClass`, `Date`, `Time`, `DateTime`, `StringIO`, `IO`, `ActionDispatch::Http::UploadedFile` and `Rack::Test::UploadedFile`.\n\nTo declare that the value in `params` must be an array of permitted scalar values map the key to an empty array:\n\n``` ruby\nparams.permit(:id =\u003e [])\n```\n\nTo whitelist an entire hash of parameters, the `permit!` method can be used\n\n``` ruby\nparams.require(:log_entry).permit!\n```\n\nThis 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.\n\n## Nested Parameters\n\nYou can also use permit on nested parameters, like:\n\n``` ruby\nparams.permit(:name, {:emails =\u003e []}, :friends =\u003e [ :name, { :family =\u003e [ :name ], :hobbies =\u003e [] }])\n```\n\nThis 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).\n\nThanks to Nick Kallen for the permit idea!\n\n## Require Multiple Parameters\n\nIf you want to make sure that multiple keys are present in a params hash, you can call the method twice:\n\n``` ruby\nparams.require(:token)\nparams.require(:post).permit(:title)\n```\n\n## Handling of Unpermitted Keys\n\nBy 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.\n\nAdditionally, 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.\n\n## Use Outside of Controllers\n\nWhile Strong Parameters will enforce permitted and required values in your application controllers, keep in mind\nthat you will need to sanitize untrusted data used for mass assignment when in use outside of controllers.\n\nFor example, if you retrieve JSON data from a third party API call and pass the unchecked parsed result on to\n`Model.create`, undesired mass assignments could take place.  You can alleviate this risk by slicing the hash data,\nor wrapping the data in a new instance of `ActionController::Parameters` and declaring permissions the same as\nyou would in a controller.  For example:\n\n``` ruby\nraw_parameters = { :email =\u003e \"john@example.com\", :name =\u003e \"John\", :admin =\u003e true }\nparameters = ActionController::Parameters.new(raw_parameters)\nuser = User.create(parameters.permit(:name, :email))\n```\n\n## More Examples\n\nHead over to the [Rails guide about Action Controller](http://guides.rubyonrails.org/action_controller_overview.html#more-examples).\n\n## Installation\n\nIn Gemfile:\n\n``` ruby\ngem 'strong_parameters'\n```\n\nand then run `bundle`. To activate the strong parameters, you need to include this module in\nevery model you want protected.\n\n``` ruby\nclass Post \u003c ActiveRecord::Base\n  include ActiveModel::ForbiddenAttributesProtection\nend\n```\n\nAlternatively, you can protect all Active Record resources by default by creating an initializer and pasting the line:\n\n``` ruby\nActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)\n```\n\nIf 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`:\n\n``` ruby\nconfig.active_record.whitelist_attributes = false\n```\n\nThis will allow you to remove / not have to use `attr_accessible` and do mass assignment inside your code and tests.\n\n## Migration Path to Rails 4\n\nIn order to have an idiomatic Rails 4 application, Rails 3 applications may\nuse this gem to introduce strong parameters in preparation for their upgrade.\n\nThe following is a way to do that gradually:\n\n### 1 Depend on `strong_parameters`\n\nAdd this gem to the application `Gemfile`:\n\n``` ruby\ngem 'strong_parameters'\n```\n\nand run `bundle install`.\n\nAfter this change, the `params` object in requests is of type\n`ActionController::Parameters`. That is a subclass of\n`ActiveSupport::HashWithIndifferentAccess` and therefore everything should\nwork as before. The test suite should be green, and the application can be\ndeployed.\n\n### 2 Compute a Topological Sort of Active Record Models\n\nWe are going to work model by model, and the natural order to do that\nsystematically is topological. That is, if post has many comments, first you\ndo `Post`, and later you do `Comment`.\n\nReason is that order plays well with nested attributes. You can mass-assign\n`ActionController::Parameters` to `Post`, and if that includes\n`comments_attributes` and the `Comment` model is not yet done, it will work.\nBut if `Comment` is done first, then the mass-assigning to `Post` won't permit\nits attributes and won't work.\n\nThis script prints a topological sort of the Active Record models to standard\noutput:\n\n```ruby\nrequire 'tsort'\nrequire 'set'\n\nclass Graph \u003c Hash\n  include TSort\n\n  alias tsort_each_node each_key\n\n  def tsort_each_child(node, \u0026block)\n    fetch(node).each(\u0026block)\n  end\nend\n\ndef children(model)\n  Set.new.tap do |children|\n    model.reflect_on_all_associations.each do |association|\n      next unless [:has_many, :has_one].include?(association.macro)\n      next if association.options[:through]\n\n      children \u003c\u003c association.klass\n    end\n  end\nend\n\nDir.glob('app/models/**/*.rb') do |model|\n  load model\nend\n\ngraph = Graph.new\nActiveRecord::Base.descendants.each do |model|\n  graph[model] = children(model) unless model.abstract_class?\nend\n\ngraph.tsort.reverse_each do |klass|\n  puts klass.name\nend\n```\n\nExecute it with `rails runner`.\n\n### 3 Protect Every Active Record Model, One at a Time\n\nOnce the dependency is in place and the topological listing computed, you can\nwork model by model. Do one model, deploy. Do another model, deploy. Etc.\n\nFor each model:\n\n#### 3.1 Add Protection\n\nRemove any `attr_accessible` or `attr_protected` declarations and include\n`ActiveModel::ForbiddenAttributesProtection`:\n\n``` ruby\nclass Post \u003c ActiveRecord::Base\n  include ActiveModel::ForbiddenAttributesProtection\nend\n```\n\n#### 3.2 (Optional) Check the Suite is Red\n\nIf the application performs any mass-assignment into that model, the test\nsuite should not pass. Expect the test suite to raise\n`ActiveModel::ForbiddenAttributes` in those spots.\n\nIf the test suite is green, either it lacks coverage (fix it), or there is no\nmass-assignment going on (ready to deploy).\n\n#### 3.3 Whitelisting\n\nGo to every controller whose actions trigger mass-assignment on that model via\n`params` and sanitize the input data using `require` and `permit`, as\nexplained above.\n\n#### 3.4 Deploy\n\nOnce everything is whitelisted and the suite is green, this particular model\ncan be pushed.\n\nReady to work on the next model.\n\n### 4 Add Protection Globally\n\nOnce all models are done, remove their inclusion of the protecting module:\n\n``` ruby\nclass Post \u003c ActiveRecord::Base\n  # REMOVE THIS LINE IN EVERY PERSISTENT MODEL\n  include ActiveModel::ForbiddenAttributesProtection\nend\n```\n\nand add it globally in an initializer:\n\n``` ruby\n# config/initializers/strong_parameters.rb\nActiveRecord::Base.class_eval do\n  include ActiveModel::ForbiddenAttributesProtection\nend\n```\n\n### 5 Upgrade to Rails 4\n\nTo upgrade to Rails 4 just remove the previous initializer, everything else is\nready as far as strong parameters is concerned.\n\n## Compatibility\n\nThis 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.\nAn unofficial Rails 2 version is [strong_parameters_rails2](https://github.com/grosser/strong_parameters/tree/rails2).\n","funding_links":[],"categories":["Ruby"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frails%2Fstrong_parameters","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frails%2Fstrong_parameters","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frails%2Fstrong_parameters/lists"}