The personal finance app for everyone (by everyone)
Ruby
Reject null bytes in rule fields (#4109)
Orange🍊c28f9dc68721
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rbindex 1a320a809a..1787782922 100644--- a/app/controllers/rules_controller.rb+++ b/app/controllers/rules_controller.rb@@ -54,7 +54,7 @@ class RulesController < ApplicationControllerif @rule.saveredirect_to confirm_rule_path(@rule, reload_on_close: true)else- render :new, status: :unprocessable_entity+ render_invalid_rule :newendend@@ -81,7 +81,7 @@ class RulesController < ApplicationControllerformat.turbo_stream { stream_redirect_back_or_to rules_path, notice: t(".success") }endelse- render :edit, status: :unprocessable_entity+ render_invalid_rule :editendend@@ -119,6 +119,25 @@ class RulesController < ApplicationControllerendprivate+ def render_invalid_rule(template)+ # A native select cannot preserve an invalid option on resubmission.+ invalid_selector = @rule.errors[:resource_type].any? ||+ @rule.actions.any? { |action| action.errors[:action_type].any? } ||+ @rule.conditions.any? { |condition| invalid_condition_selector?(condition) }++ if invalid_selector+ render plain: @rule.errors.full_messages.to_sentence, status: :unprocessable_entity+ return+ end++ render template, status: :unprocessable_entity+ end++ def invalid_condition_selector?(condition)+ condition.errors[:condition_type].any? || condition.errors[:operator].any? ||+ condition.sub_conditions.any? { |sub_condition| invalid_condition_selector?(sub_condition) }+ end+# Names the provider that will actually run, and prices against it.## This previously hardcoded :openai, so an Anthropic install was quoted thediff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex 1aa6ed4257..99bc56233d 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -1479,6 +1479,8 @@ class Family::DataImporterdef resolve_multi_tag_action_value(action_data)value_ref = action_data["value_ref"]+ validate_rule_text!(value_ref, field: "value_ref")+ validate_rule_text!(action_data["value"], field: "value")refs = case value_refwhen Array then value_refwhen Hash then [ value_ref ]@@ -1531,6 +1533,8 @@ class Family::DataImporterdef rule_operand_value(data)raw_value = data["value"]+ validate_rule_text!(raw_value, field: "value")+ validate_rule_text!(data["value_ref"], field: "value_ref")value = raw_value.is_a?(String) ? raw_value.presence : raw_valuevalue_ref_name = data.dig("value_ref", "name")@@ -1540,6 +1544,12 @@ class Family::DataImportervalue_ref_nameend+ def validate_rule_text!(value, field:)+ return if DatabaseTextValidator.acceptable?(value)++ raise InvalidRecordError.new(record_type: "Rule", field: field, value: "(invalid text)")+ end+def uuid_like?(value)UuidFormat.valid?(value)enddiff --git a/app/models/rule.rb b/app/models/rule.rbindex 721a150e3d..1d5a787e5f 100644--- a/app/models/rule.rb+++ b/app/models/rule.rb@@ -11,8 +11,9 @@ class Rule < ApplicationRecordbefore_validation :normalize_name- validates :resource_type, presence: true- validates :name, length: { minimum: 1 }, allow_nil: true+ validates :resource_type, presence: true, if: -> { resource_type.to_s.valid_encoding? }+ validates :name, length: { minimum: 1 }, allow_nil: true, if: -> { name.to_s.valid_encoding? }+ validates_with DatabaseTextValidator, attributes: %i[name resource_type]validate :no_nested_compound_conditions# Every rule must have at least 1 action@@ -177,6 +178,10 @@ class Rule < ApplicationRecordenddef normalize_name- self.name = nil if name.is_a?(String) && name.strip.empty?+ return unless name.is_a?(String)+ return unless name.valid_encoding?+ return if name.include?("\0")++ self.name = nil if name.strip.empty?endenddiff --git a/app/models/rule/action.rb b/app/models/rule/action.rbindex a16bfe8c1e..ea311ae5af 100644--- a/app/models/rule/action.rb+++ b/app/models/rule/action.rb@@ -1,7 +1,8 @@class Rule::Action < ApplicationRecordbelongs_to :rule, touch: true- validates :action_type, presence: true+ validates :action_type, presence: true, if: -> { action_type.to_s.valid_encoding? }+ validates_with DatabaseTextValidator, attributes: %i[action_type value]# Pre-seed (watermark): when a send_email_notification action is created — on a# new rule OR added to an existing one — record all currently-matching@@ -25,7 +26,13 @@ class Rule::Action < ApplicationRecord# actions don't require a schema change. A single scalar value round-trips# unchanged, which keeps existing single-value rows backward compatible.def value=(val)- val = val.reject(&:blank?).join(",") if val.is_a?(Array)+ if val.is_a?(Array)+ val = val.reject do |item|+ next false if item.is_a?(String) && !item.valid_encoding?++ item.blank?+ end.join(",")+ endsuper(val)enddiff --git a/app/models/rule/condition.rb b/app/models/rule/condition.rbindex 67429f95c3..416a097b20 100644--- a/app/models/rule/condition.rb+++ b/app/models/rule/condition.rb@@ -12,9 +12,13 @@ class Rule::Condition < ApplicationRecordbefore_validation :normalize_legacy_condition_type- validates :condition_type, presence: true, inclusion: { in: SUPPORTED_CONDITION_TYPES, allow_blank: true }- validates :operator, presence: true- validates :value, presence: true, unless: -> { compound? || Rule::ConditionFilter::VALUELESS_OPERATORS.include?(operator) }+ validates :condition_type, presence: true, inclusion: { in: SUPPORTED_CONDITION_TYPES, allow_blank: true },+ if: -> { condition_type.to_s.valid_encoding? }+ validates :operator, presence: true, if: -> { operator.to_s.valid_encoding? }+ validates :value, presence: true,+ unless: -> { compound? || Rule::ConditionFilter::VALUELESS_OPERATORS.include?(operator) },+ if: -> { value.to_s.valid_encoding? }+ validates_with DatabaseTextValidator, attributes: %i[condition_type operator value]accepts_nested_attributes_for :sub_conditions, allow_destroy: true@@ -71,6 +75,7 @@ class Rule::Condition < ApplicationRecordprivatedef normalize_legacy_condition_type+ return unless condition_type.is_a?(String) && condition_type.valid_encoding?return if condition_type.blank?normalized = LEGACY_CONDITION_TYPE_ALIASES[condition_type]diff --git a/app/models/rule_import.rb b/app/models/rule_import.rbindex 6a204f7685..3f5be2e23e 100644--- a/app/models/rule_import.rb+++ b/app/models/rule_import.rb@@ -64,8 +64,8 @@ class RuleImport < Importrows.create!(source_row_number: index,- name: normalized_row[:name].to_s.strip,- resource_type: normalized_row[:resource_type].to_s.strip,+ name: normalized_rule_text(normalized_row[:name], attribute: :name),+ resource_type: normalized_rule_text(normalized_row[:resource_type], attribute: :resource_type),active: parse_boolean(normalized_row[:active]),effective_date: normalized_row[:effective_date].to_s.strip,conditions: normalized_row[:conditions].to_s.strip,@@ -96,6 +96,20 @@ class RuleImport < Import}end+ def normalized_rule_text(value, attribute:)+ text = value.to_s+ reject_invalid_text!(text, label: Rule.human_attribute_name(attribute))++ text.strip+ end++ def reject_invalid_text!(value, label:)+ return if DatabaseTextValidator.acceptable?(value)++ errors.add(:base, :invalid, message: "#{label} #{I18n.t("errors.messages.invalid")}")+ raise ActiveRecord::RecordInvalid.new(self)+ end+def extract_conditions_and_actions(fragments)pieces = Array(fragments).compactreturn [ "", "" ] if pieces.empty?@@ -117,8 +131,8 @@ class RuleImport < Importenddef create_or_update_rule_from_row(row)- rule_name = row.name.to_s.strip.presence- resource_type = row.resource_type.to_s.strip+ rule_name = normalized_rule_text(row.name, attribute: :name).presence+ resource_type = normalized_rule_text(row.resource_type, attribute: :resource_type)# Validate resource typeunless resource_type == "transaction"@@ -210,6 +224,7 @@ class RuleImport < Importdef resolve_import_condition_value(condition_data)condition_type = condition_data["condition_type"]value = condition_data["value"]+ reject_invalid_text!(value, label: Rule::Condition.human_attribute_name(:value))return value unless value.present?@@ -234,6 +249,7 @@ class RuleImport < Importdef resolve_import_action_value(action_data)action_type = action_data["action_type"]value = action_data["value"]+ reject_invalid_text!(value, label: Rule::Action.human_attribute_name(:value))return value unless value.present?diff --git a/app/validators/database_text_validator.rb b/app/validators/database_text_validator.rbnew file mode 100644index 0000000000..6184b27242--- /dev/null+++ b/app/validators/database_text_validator.rb@@ -0,0 +1,20 @@+# EachValidator calls blank? before validate_each, which raises for malformed UTF-8.+class DatabaseTextValidator < ActiveModel::Validator+ def self.acceptable?(value)+ case value+ when String then value.valid_encoding? && !value.include?("\0")+ when Array then value.all? { |item| acceptable?(item) }+ when Hash then value.all? { |key, item| acceptable?(key) && acceptable?(item) }+ else true+ end+ end++ def validate(record)+ options.fetch(:attributes).each do |attribute|+ value = record.public_send(attribute)+ next if self.class.acceptable?(value)++ record.errors.add(attribute, :invalid)+ end+ end+enddiff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rbindex b1a45555e0..8b651d3683 100644--- a/test/controllers/rules_controller_test.rb+++ b/test/controllers/rules_controller_test.rb@@ -91,6 +91,143 @@ class RulesControllerTest < ActionDispatch::IntegrationTestassert_redirected_to confirm_rule_url(rule, reload_on_close: true)end+ test "rejects a null byte in a condition instead of returning a server error" do+ assert_no_difference "Rule.count" do+ post rules_url, params: {+ rule: {+ resource_type: "transaction",+ conditions_attributes: {+ "0" => { condition_type: "transaction_name", operator: "like", value: "cof\0fee" }+ },+ actions_attributes: {+ "0" => { action_type: "exclude_transaction" }+ }+ }+ }+ end++ assert_response :unprocessable_entity+ assert_select "p.text-destructive", text: /Conditions value is invalid/+ end++ test "rejects a null byte when updating an action" do+ rule = rules(:one)+ action = rule.actions.first++ patch rule_url(rule), params: {+ rule: {+ actions_attributes: {+ "0" => { id: action.id, action_type: "set_transaction_name", value: "bad\0value" }+ }+ }+ }++ assert_response :unprocessable_entity+ assert_equal action.value, action.reload.value+ end++ test "rejects a null byte in the condition operator" do+ assert_no_difference "Rule.count" do+ post rules_url, params: {+ rule: {+ resource_type: "transaction",+ conditions_attributes: {+ "0" => { condition_type: "transaction_name", operator: "like\0", value: "coffee" }+ },+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }+ }+ }+ end++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_match(/operator is invalid/i, response.body)+ end++ test "rejects a null byte in a nested condition operator" do+ assert_no_difference "Rule.count" do+ post rules_url, params: {+ rule: {+ resource_type: "transaction",+ conditions_attributes: {+ "0" => {+ condition_type: "compound", operator: "and",+ sub_conditions_attributes: {+ "0" => { condition_type: "transaction_name", operator: "like\0", value: "coffee" }+ }+ }+ },+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }+ }+ }+ end++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_match(/operator is invalid/i, response.body)+ end++ test "rejects a null byte in the condition type without selecting a different type" do+ post rules_url, params: {+ rule: {+ resource_type: "transaction",+ conditions_attributes: {+ "0" => { condition_type: "transaction_name\0", operator: "like", value: "coffee" }+ },+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }+ }+ }++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_match(/condition type is invalid/i, response.body)+ end++ test "rejects a null byte in the action type without failing to render" do+ assert_no_difference "Rule.count" do+ post rules_url, params: {+ rule: {+ resource_type: "transaction",+ actions_attributes: { "0" => { action_type: "exclude_transaction\0" } }+ }+ }+ end++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_match(/action type is invalid/i, response.body)+ end++ test "rejects a null byte when updating the action type" do+ rule = rules(:one)+ action = rule.actions.first+ original_type = action.action_type++ patch rule_url(rule), params: {+ rule: { actions_attributes: { "0" => { id: action.id, action_type: "#{original_type}\0" } } }+ }++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_match(/action type is invalid/i, response.body)+ assert_equal original_type, action.reload.action_type+ end++ test "rejects a null byte in the resource type without failing to render" do+ assert_no_difference "Rule.count" do+ post rules_url, params: {+ rule: {+ resource_type: "transaction\0",+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }+ }+ }+ end++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_match(/resource type is invalid/i, response.body)+ end+test "can update rule" dorule = rules(:one)diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rbindex 1211fb74bc..351ad91bfe 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -1883,6 +1883,35 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert_equal category.id, action.valueend+ test "rejects invalid rule references before creating related records" do+ valid_condition = { condition_type: "transaction_name", operator: "like", value: "coffee" }+ cases = [+ [ { condition_type: "transaction_category", operator: "=", value: "Bad\0Category" },+ { action_type: "exclude_transaction" }, "value" ],+ [ valid_condition,+ { action_type: "set_transaction_merchant", value_ref: { name: "Bad\0Merchant" } }, "value_ref" ],+ [ valid_condition,+ { action_type: "set_transaction_tags", value_ref: [ { name: "Safe" }, { name: "Bad\0Tag" } ] }, "value_ref" ]+ ]+ counts = [ @family.rules.count, @family.categories.count, @family.merchants.count, @family.tags.count ]++ cases.each do |condition, action, field|+ ndjson = build_ndjson([ {+ type: "Rule", version: 1,+ data: { name: "Invalid reference", resource_type: "transaction", conditions: [ condition ], actions: [ action ] }+ } ])++ error = assert_raises(Family::DataImporter::InvalidRecordError) do+ Family::DataImporter.new(@family, ndjson).import!+ end++ assert_equal "invalid_import_record", error.code+ assert_equal field, error.details[:field]+ assert_equal "(invalid text)", error.details[:value]+ assert_equal counts, [ @family.rules.count, @family.categories.count, @family.merchants.count, @family.tags.count ]+ end+ end+test "imports transaction_tag rule condition by remapping the tag name to an id" dondjson = build_ndjson([{diff --git a/test/models/rule_import_test.rb b/test/models/rule_import_test.rbindex 7150b5d32f..04aea7e18d 100644--- a/test/models/rule_import_test.rb+++ b/test/models/rule_import_test.rb@@ -350,6 +350,98 @@ class RuleImportTest < ActiveSupport::TestCaseendend+ test "reports a validation error for a null byte in an imported condition" do+ csv = CSV.generate do |rows|+ rows << %w[name resource_type active effective_date conditions actions]+ rows << [+ "Invalid condition rule",+ "transaction",+ true,+ nil,+ [ { condition_type: "transaction_name", operator: "like", value: "bad\0value" } ].to_json,+ [ { action_type: "exclude_transaction" } ].to_json+ ]+ end++ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")+ import.generate_rows_from_csv++ error = assert_raises(ActiveRecord::RecordInvalid) { import.send(:import!) }+ assert_match(/value is invalid/i, error.message)+ assert_nil @family.rules.find_by(name: "Invalid condition rule")+ end++ test "rejects an imported name with a trailing null byte" do+ import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")+ import.generate_rows_from_csv+ row = import.rows.first+ row.name = "Invalid name\0"++ error = assert_raises(ActiveRecord::RecordInvalid) do+ import.send(:create_or_update_rule_from_row, row)+ end++ assert_match(/Name is invalid/, error.message)+ assert_nil @family.rules.find_by(name: "Invalid name")+ end++ test "rejects an imported resource type with a trailing null byte" do+ import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")+ import.generate_rows_from_csv+ row = import.rows.first+ row.resource_type = "transaction\0"++ error = assert_raises(ActiveRecord::RecordInvalid) do+ import.send(:create_or_update_rule_from_row, row)+ end++ assert_match(/Resource type is invalid/, error.message)+ end++ test "rejects null bytes in imported references before looking them up" do+ import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")+ counts = [ @family.categories.count, @family.merchants.count, @family.tags.count ]++ {+ resolve_import_condition_value: [ "transaction_category", "transaction_merchant", "transaction_tag" ],+ resolve_import_action_value: [ "set_transaction_category", "set_transaction_merchant", "set_transaction_tags" ]+ }.each do |resolver, types|+ type_key = resolver == :resolve_import_condition_value ? "condition_type" : "action_type"++ types.each do |type|+ error = assert_raises(ActiveRecord::RecordInvalid, type) do+ import.send(resolver, { type_key => type, "value" => "Bad\0reference" })+ end+ assert_match(/Value is invalid/, error.message)+ end+ end++ assert_equal counts, [ @family.categories.count, @family.merchants.count, @family.tags.count ]+ end++ test "rejects null bytes in imported operator and action type" do+ [+ [ "like\0", "exclude_transaction" ],+ [ "like", "exclude_transaction\0" ]+ ].each do |operator, action_type|+ csv = CSV.generate do |rows|+ rows << %w[name resource_type active effective_date conditions actions]+ rows << [+ "Invalid metadata rule", "transaction", true, nil,+ [ { condition_type: "transaction_name", operator: operator, value: "coffee" } ].to_json,+ [ { action_type: action_type } ].to_json+ ]+ end++ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")+ import.generate_rows_from_csv++ error = assert_raises(ActiveRecord::RecordInvalid) { import.send(:import!) }+ assert_match(/is invalid/, error.message)+ assert_nil @family.rules.find_by(name: "Invalid metadata rule")+ end+ end+test "imports valid JSON conditions whose values contain escaped quotes" docsv = CSV.generate do |out|out << %w[name resource_type active effective_date conditions actions]diff --git a/test/models/rule_test.rb b/test/models/rule_test.rbindex cc42564362..60b6b42f9e 100644--- a/test/models/rule_test.rb+++ b/test/models/rule_test.rb@@ -10,6 +10,101 @@ class RuleTest < ActiveSupport::TestCase@groceries_category = @family.categories.create!(name: "Groceries")end+ test "rejects a null byte in the rule name" do+ rule = @family.rules.build(name: "bad\0name", resource_type: "transaction")+ rule.actions.build(action_type: "exclude_transaction")++ assert_not rule.valid?+ assert rule.errors.of_kind?(:name, :invalid)++ rule.name = " \0 "+ assert_not rule.valid?+ assert rule.errors.of_kind?(:name, :invalid)++ rule.name = "\0"+ assert_not rule.valid?+ assert rule.errors.of_kind?(:name, :invalid)+ end++ test "rejects invalid text encoding in rule fields" do+ invalid_text = "bad\xFF".dup.force_encoding("UTF-8")+ rule = @family.rules.build(name: invalid_text, resource_type: "transaction")+ rule.actions.build(action_type: "exclude_transaction")++ assert_not rule.valid?+ assert rule.errors.of_kind?(:name, :invalid)++ rule.name = "Valid name"+ rule.resource_type = invalid_text+ assert_not rule.valid?+ assert rule.errors.of_kind?(:resource_type, :invalid)+ end++ test "rejects null bytes and invalid encoding in condition and action metadata" do+ invalid_text = "bad\xFF".dup.force_encoding("UTF-8")+ rule = @family.rules.build(resource_type: "transaction")+ condition = rule.conditions.build(condition_type: "transaction_name", operator: "like\0", value: "coffee")+ action = rule.actions.build(action_type: "exclude_transaction\0")++ assert_not rule.valid?+ assert condition.errors.of_kind?(:operator, :invalid)+ assert action.errors.of_kind?(:action_type, :invalid)++ condition.operator = "like"+ condition.value = invalid_text+ action.action_type = "set_transaction_name"+ action.value = invalid_text++ assert_not rule.valid?+ assert condition.errors.of_kind?(:value, :invalid)+ assert action.errors.of_kind?(:value, :invalid)++ condition.condition_type = invalid_text+ assert_not rule.valid?+ assert condition.errors.of_kind?(:condition_type, :invalid)+ end++ test "rejects invalid encoding in a multi-value action" do+ invalid_text = "bad\xFF".dup.force_encoding("UTF-8")+ rule = @family.rules.build(resource_type: "transaction")+ action = rule.actions.build(action_type: "set_transaction_tags", value: [ invalid_text ])++ assert_not rule.valid?+ assert action.errors.of_kind?(:value, :invalid)+ end++ test "rejects a null byte in a nested condition value" do+ rule = @family.rules.build(resource_type: "transaction")+ compound = rule.conditions.build(condition_type: "compound", operator: "and")+ condition = compound.sub_conditions.build(condition_type: "transaction_name", operator: "like", value: "bad\0value")+ rule.actions.build(action_type: "exclude_transaction")++ assert_not rule.valid?+ assert condition.errors.of_kind?(:value, :invalid)+ end++ test "rejects a null byte in an action value" do+ rule = @family.rules.build(resource_type: "transaction")+ action = rule.actions.build(action_type: "set_transaction_name", value: "bad\0value")++ assert_not rule.valid?+ assert action.errors.of_kind?(:value, :invalid)+ end++ test "allows other whitespace and Unicode in rule text" do+ rule = @family.rules.build(name: "咖啡\n提醒", resource_type: "transaction")+ rule.conditions.build(condition_type: "transaction_name", operator: "like", value: "café\tshop")+ rule.actions.build(action_type: "set_transaction_name", value: "Tea\nshop")++ assert rule.valid?+ end++ test "create_from_grouping returns nil for a null byte" do+ assert_no_difference "Rule.count" do+ assert_nil Rule.create_from_grouping(@family, "bad\0name", @groceries_category)+ end+ end+test "basic rule" dotransaction_entry = create_transaction(date: Date.current, account: @account, merchant: @whole_foods_merchant)