aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
blob: 62a6ec9c9b772975436698da8a12a91f62d2dade (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
require "cases/helper"
require 'logger'
require 'active_support/core_ext/object/inclusion'

class SanitizerTest < ActiveModel::TestCase
  attr_accessor :logger

  class Authorizer < ActiveModel::MassAssignmentSecurity::PermissionSet
    def deny?(key)
      key.in?(['admin'])
    end
  end

  def setup
    @logger_sanitizer = ActiveModel::MassAssignmentSecurity::LoggerSanitizer.new(self)
    @strict_sanitizer = ActiveModel::MassAssignmentSecurity::StrictSanitizer.new(self)
    @authorizer = Authorizer.new
  end

  test "sanitize attributes" do
    original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' }
    attributes = @logger_sanitizer.sanitize(original_attributes, @authorizer)

    assert attributes.key?('first_name'), "Allowed key shouldn't be rejected"
    assert !attributes.key?('admin'),     "Denied key should be rejected"
  end

  test "debug mass assignment removal with LoggerSanitizer" do
    original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' }
    log = StringIO.new
    self.logger = Logger.new(log)
    @logger_sanitizer.sanitize(original_attributes, @authorizer)
    assert_match(/admin/, log.string, "Should log removed attributes: #{log.string}")
  end

  test "debug mass assignment removal with StrictSanitizer" do
    original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' }
    assert_raise ActiveModel::MassAssignmentSecurity::Error do
      @strict_sanitizer.sanitize(original_attributes, @authorizer)
    end
  end

end