sanitization.rb 7.9 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6 7
module ActiveRecord
  module Sanitization
    extend ActiveSupport::Concern

    module ClassMethods
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
      # Accepts an array or string of SQL conditions and sanitizes
      # them into a valid SQL fragment for a WHERE clause.
      #
      #   sanitize_sql_for_conditions(["name=? and group_id=?", "foo'bar", 4])
      #   # => "name='foo''bar' and group_id=4"
      #
      #   sanitize_sql_for_conditions(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
      #   # => "name='foo''bar' and group_id='4'"
      #
      #   sanitize_sql_for_conditions(["name='%s' and group_id='%s'", "foo'bar", 4])
      #   # => "name='foo''bar' and group_id='4'"
      #
      #   sanitize_sql_for_conditions("name='foo''bar' and group_id='4'")
      #   # => "name='foo''bar' and group_id='4'"
      def sanitize_sql_for_conditions(condition)
        return nil if condition.blank?
24

25 26 27 28 29 30
        case condition
        when Array; sanitize_sql_array(condition)
        else        condition
        end
      end
      alias :sanitize_sql :sanitize_sql_for_conditions
31

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
      # Accepts an array, hash, or string of SQL conditions and sanitizes
      # them into a valid SQL fragment for a SET clause.
      #
      #   sanitize_sql_for_assignment(["name=? and group_id=?", nil, 4])
      #   # => "name=NULL and group_id=4"
      #
      #   sanitize_sql_for_assignment(["name=:name and group_id=:group_id", name: nil, group_id: 4])
      #   # => "name=NULL and group_id=4"
      #
      #   Post.sanitize_sql_for_assignment({ name: nil, group_id: 4 })
      #   # => "`posts`.`name` = NULL, `posts`.`group_id` = 4"
      #
      #   sanitize_sql_for_assignment("name=NULL and group_id='4'")
      #   # => "name=NULL and group_id='4'"
      def sanitize_sql_for_assignment(assignments, default_table_name = table_name)
        case assignments
        when Array; sanitize_sql_array(assignments)
        when Hash;  sanitize_sql_hash_for_assignment(assignments, default_table_name)
        else        assignments
51
        end
52
      end
53

54 55 56 57 58 59 60 61 62 63
      # Accepts an array, or string of SQL conditions and sanitizes
      # them into a valid SQL fragment for an ORDER clause.
      #
      #   sanitize_sql_for_order(["field(id, ?)", [1,3,2]])
      #   # => "field(id, 1,3,2)"
      #
      #   sanitize_sql_for_order("id ASC")
      #   # => "id ASC"
      def sanitize_sql_for_order(condition)
        if condition.is_a?(Array) && condition.first.to_s.include?("?")
64 65 66
          disallow_raw_sql!(
            [condition.first],
            permit: connection.column_name_with_order_matcher
67 68 69 70 71 72
          )

          # Ensure we aren't dealing with a subclass of String that might
          # override methods we use (eg. Arel::Nodes::SqlLiteral).
          if condition.first.kind_of?(String) && !condition.first.instance_of?(String)
            condition = [String.new(condition.first), *condition[1..-1]]
73
          end
74 75 76 77

          Arel.sql(sanitize_sql_array(condition))
        else
          condition
78
        end
79
      end
80

81 82 83 84 85 86 87
      # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
      #
      #   sanitize_sql_hash_for_assignment({ status: nil, group_id: 1 }, "posts")
      #   # => "`posts`.`status` = NULL, `posts`.`group_id` = 1"
      def sanitize_sql_hash_for_assignment(attrs, table)
        c = connection
        attrs.map do |attr, value|
D
Daniel Colson 已提交
88
          type = type_for_attribute(attr)
89 90 91 92
          value = type.serialize(type.cast(value))
          "#{c.quote_table_name_for_assignment(table, attr)} = #{c.quote(value)}"
        end.join(", ")
      end
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
      # Sanitizes a +string+ so that it is safe to use within an SQL
      # LIKE statement. This method uses +escape_character+ to escape all occurrences of "\", "_" and "%".
      #
      #   sanitize_sql_like("100%")
      #   # => "100\\%"
      #
      #   sanitize_sql_like("snake_cased_string")
      #   # => "snake\\_cased\\_string"
      #
      #   sanitize_sql_like("100%", "!")
      #   # => "100!%"
      #
      #   sanitize_sql_like("snake_cased_string", "!")
      #   # => "snake!_cased!_string"
      def sanitize_sql_like(string, escape_character = "\\")
        pattern = Regexp.union(escape_character, "%", "_")
        string.gsub(pattern) { |x| [escape_character, x].join }
      end
B
Ben Toews 已提交
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
      # Accepts an array of conditions. The array has each value
      # sanitized and interpolated into the SQL statement.
      #
      #   sanitize_sql_array(["name=? and group_id=?", "foo'bar", 4])
      #   # => "name='foo''bar' and group_id=4"
      #
      #   sanitize_sql_array(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
      #   # => "name='foo''bar' and group_id=4"
      #
      #   sanitize_sql_array(["name='%s' and group_id='%s'", "foo'bar", 4])
      #   # => "name='foo''bar' and group_id='4'"
      def sanitize_sql_array(ary)
        statement, *values = ary
        if values.first.is_a?(Hash) && /:\w+/.match?(statement)
          replace_named_bind_variables(statement, values.first)
        elsif statement.include?("?")
          replace_bind_variables(statement, values)
        elsif statement.blank?
          statement
        else
          statement % values.collect { |value| connection.quote_string(value.to_s) }
134
        end
135
      end
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
      def disallow_raw_sql!(args, permit: connection.column_name_matcher) # :nodoc:
        unexpected = nil
        args.each do |arg|
          next if arg.is_a?(Symbol) || Arel.arel_node?(arg) ||
            arg.to_s.split(/\s*,\s*/).all? { |part| permit.match?(part) }
          (unexpected ||= []) << arg
        end

        return unless unexpected

        if allow_unsafe_raw_sql == :deprecated
          ActiveSupport::Deprecation.warn(
            "Dangerous query method (method whose arguments are used as raw " \
            "SQL) called with non-attribute argument(s): " \
            "#{unexpected.map(&:inspect).join(", ")}. Non-attribute " \
            "arguments will be disallowed in Rails 6.1. This method should " \
            "not be called with user-provided values, such as request " \
            "parameters or model attributes. Known-safe values can be passed " \
            "by wrapping them in Arel.sql()."
          )
        else
          raise(ActiveRecord::UnknownAttributeReference,
            "Query method called with non-attribute argument(s): " +
            unexpected.map(&:inspect).join(", ")
          )
        end
      end

165
      private
166
        def replace_bind_variables(statement, values)
167 168 169 170 171 172
          raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size)
          bound = values.dup
          c = connection
          statement.gsub(/\?/) do
            replace_bind_variable(bound.shift, c)
          end
173 174
        end

175
        def replace_bind_variable(value, c = connection)
176 177 178 179 180
          if ActiveRecord::Relation === value
            value.to_sql
          else
            quote_bound_value(value, c)
          end
181
        end
182

183
        def replace_named_bind_variables(statement, bind_vars)
184 185 186 187 188 189 190 191
          statement.gsub(/(:?):([a-zA-Z]\w*)/) do |match|
            if $1 == ":" # skip postgresql casts
              match # return the whole match
            elsif bind_vars.include?(match = $2.to_sym)
              replace_bind_variable(bind_vars[match])
            else
              raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
            end
192 193 194
          end
        end

195
        def quote_bound_value(value, c = connection)
196
          if value.respond_to?(:map) && !value.acts_like?(:string)
197 198
            quoted = value.map { |v| c.quote(v) }
            if quoted.empty?
199 200
              c.quote(nil)
            else
201
              quoted.join(",")
202
            end
203
          else
204
            c.quote(value)
205 206 207
          end
        end

208
        def raise_if_bind_arity_mismatch(statement, expected, provided)
209 210 211
          unless expected == provided
            raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
          end
212 213 214 215
        end
    end
  end
end