Skip to content

Commit a8f6d5c

Browse files
committed
Integrate ActiveModel::ForbiddenAttributesProtection from StrongParameters gem
1 parent 8850054 commit a8f6d5c

File tree

4 files changed

+54
-0
lines changed

4 files changed

+54
-0
lines changed

activemodel/lib/active_model.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ module ActiveModel
3434
autoload :Conversion
3535
autoload :Dirty
3636
autoload :EachValidator, 'active_model/validator'
37+
autoload :ForbiddenAttributesProtection
3738
autoload :Lint
3839
autoload :MassAssignmentSecurity
3940
autoload :Model
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
module ActiveModel
2+
class ForbiddenAttributes < StandardError
3+
end
4+
5+
module ForbiddenAttributesProtection
6+
def sanitize_for_mass_assignment(new_attributes, options = {})
7+
if !new_attributes.respond_to?(:permitted?) || (new_attributes.respond_to?(:permitted?) && new_attributes.permitted?)
8+
super
9+
else
10+
raise ActiveModel::ForbiddenAttributes
11+
end
12+
end
13+
end
14+
end
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
require 'cases/helper'
2+
require 'models/mass_assignment_specific'
3+
4+
class ActiveModelMassUpdateProtectionTest < ActiveSupport::TestCase
5+
test "forbidden attributes cannot be used for mass updating" do
6+
params = { "a" => "b" }
7+
class << params
8+
define_method(:permitted?) { false }
9+
end
10+
assert_raises(ActiveModel::ForbiddenAttributes) do
11+
SpecialPerson.new.sanitize_for_mass_assignment(params)
12+
end
13+
end
14+
15+
test "permitted attributes can be used for mass updating" do
16+
params = { "a" => "b" }
17+
class << params
18+
define_method(:permitted?) { true }
19+
end
20+
assert_nothing_raised do
21+
assert_equal({ "a" => "b" },
22+
SpecialPerson.new.sanitize_for_mass_assignment(params))
23+
end
24+
end
25+
26+
test "regular attributes should still be allowed" do
27+
assert_nothing_raised do
28+
assert_equal({ a: "b" },
29+
SpecialPerson.new.sanitize_for_mass_assignment(a: "b"))
30+
end
31+
end
32+
end

activemodel/test/models/mass_assignment_specific.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ class Person
2020
public :sanitize_for_mass_assignment
2121
end
2222

23+
class SpecialPerson
24+
include ActiveModel::MassAssignmentSecurity
25+
include ActiveModel::ForbiddenAttributesProtection
26+
27+
public :sanitize_for_mass_assignment
28+
end
29+
2330
class Account
2431
include ActiveModel::MassAssignmentSecurity
2532
attr_accessible :name, :email, :as => [:default, :admin]

0 commit comments

Comments
 (0)