The personal finance app for everyone (by everyone)
Ruby
Validate rule action and resource types against known types (#4175)
jaysbeekay4c7bf8e39741
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rbindex b60a93a806..dfd427b616 100644--- a/app/controllers/rules_controller.rb+++ b/app/controllers/rules_controller.rb@@ -21,7 +21,7 @@ class RulesController < ApplicationControllerdef new@rule = Current.family.rules.build(- resource_type: params[:resource_type] || "transaction",+ resource_type: params[:resource_type].presence_in(Rule::SUPPORTED_RESOURCE_TYPES) || "transaction",)if params[:name].present?@@ -33,7 +33,7 @@ class RulesController < ApplicationController)end- if params[:action_type].present? && params[:action_value].present?+ if params[:action_type].in?(Rule::Action::SUPPORTED_ACTION_TYPES) && params[:action_value].present?@rule.actions.build(action_type: params[:action_type],value: params[:action_value]@@ -121,9 +121,10 @@ class RulesController < ApplicationControllerprivatedef render_invalid_rule(template)- # A native select cannot preserve an invalid option on resubmission.+ # A native select cannot preserve an invalid option on resubmission. An+ # action marked for destruction is not validated, but is still rendered.invalid_selector = @rule.errors[:resource_type].any? ||- @rule.actions.any? { |action| action.errors[:action_type].any? } ||+ @rule.actions.any? { |action| action.errors[:action_type].any? || !action.action_type.in?(Rule::Action::SUPPORTED_ACTION_TYPES) } ||@rule.conditions.any? { |condition| invalid_condition_selector?(condition) }if invalid_selectordiff --git a/app/models/rule.rb b/app/models/rule.rbindex 965bfc5e4b..9ae2218398 100644--- a/app/models/rule.rb+++ b/app/models/rule.rb@@ -3,6 +3,7 @@ class Rule < ApplicationRecordPOSITION_LOCK_NAMESPACE = 4013UnsupportedResourceTypeError = Class.new(StandardError)+ SUPPORTED_RESOURCE_TYPES = %w[transaction].freezebelongs_to :familyhas_many :conditions, dependent: :destroy@@ -20,6 +21,9 @@ class Rule < ApplicationRecordscope :ordered, -> { order(:position, :created_at, :id) }validates :resource_type, presence: true, if: -> { resource_type.to_s.valid_encoding? }+ # A NUL or invalid encoding is reported by DatabaseTextValidator instead.+ validates :resource_type, inclusion: { in: SUPPORTED_RESOURCE_TYPES, allow_blank: true },+ if: -> { DatabaseTextValidator.acceptable?(resource_type) }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_conditionsdiff --git a/app/models/rule/action.rb b/app/models/rule/action.rbindex ecaf5eabdc..30d48e902f 100644--- a/app/models/rule/action.rb+++ b/app/models/rule/action.rb@@ -1,7 +1,12 @@class Rule::Action < ApplicationRecordbelongs_to :rule, touch: true+ SUPPORTED_ACTION_TYPES = Rule::Registry::TransactionResource.action_executor_keys.freeze+validates :action_type, presence: true, if: -> { action_type.to_s.valid_encoding? }+ # A NUL or invalid encoding is reported by DatabaseTextValidator instead.+ validates :action_type, inclusion: { in: SUPPORTED_ACTION_TYPES, allow_blank: true },+ if: -> { DatabaseTextValidator.acceptable?(action_type) }validates_with DatabaseTextValidator, attributes: %i[action_type value]# Pre-seed (watermark): when a send_email_notification action is created — on adiff --git a/app/models/rule/action_executor.rb b/app/models/rule/action_executor.rbindex 4a4f0ba5ed..52a1cfa1f3 100644--- a/app/models/rule/action_executor.rb+++ b/app/models/rule/action_executor.rb@@ -5,8 +5,12 @@ class Rule::ActionExecutor@rule = ruleend+ def self.key+ name.demodulize.underscore+ end+def key- self.class.name.demodulize.underscore+ self.class.keyenddef labeldiff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rbindex 598e5c6b9e..394751a3c6 100644--- a/app/models/rule/registry/transaction_resource.rb+++ b/app/models/rule/registry/transaction_resource.rb@@ -11,10 +11,30 @@ class Rule::Registry::TransactionResource < Rule::RegistryRule::ConditionFilter::TransactionAccount].freeze+ # Every action this resource knows, whether or not it is offered right now:+ # the AI actions are listed only while a provider is configured (or the rule+ # already has one), but stay valid when it is not.+ ACTION_EXECUTOR_CLASSES = [+ Rule::ActionExecutor::SetTransactionCategory,+ Rule::ActionExecutor::SetTransactionTags,+ Rule::ActionExecutor::SetTransactionMerchant,+ Rule::ActionExecutor::SetTransactionName,+ Rule::ActionExecutor::SetInvestmentActivityLabel,+ Rule::ActionExecutor::ExcludeTransaction,+ Rule::ActionExecutor::SetAsTransferOrPayment,+ Rule::ActionExecutor::SendEmailNotification,+ Rule::ActionExecutor::AutoCategorize,+ Rule::ActionExecutor::AutoDetectMerchants+ ].freeze+def self.condition_filter_keysCONDITION_FILTER_CLASSES.map(&:key)end+ def self.action_executor_keys+ ACTION_EXECUTOR_CLASSES.map(&:key)+ end+def resource_scopefamily.transactions.visible.with_entry.merge(Entry.excluding_split_parents).where(entry: { date: rule.effective_date.. })end@@ -24,29 +44,23 @@ class Rule::Registry::TransactionResource < Rule::Registryenddef action_executors- enabled_executors = [- Rule::ActionExecutor::SetTransactionCategory.new(rule),- Rule::ActionExecutor::SetTransactionTags.new(rule),- Rule::ActionExecutor::SetTransactionMerchant.new(rule),- Rule::ActionExecutor::SetTransactionName.new(rule),- Rule::ActionExecutor::SetInvestmentActivityLabel.new(rule),- Rule::ActionExecutor::ExcludeTransaction.new(rule),- Rule::ActionExecutor::SetAsTransferOrPayment.new(rule),- Rule::ActionExecutor::SendEmailNotification.new(rule)- ]-- if auto_categorization_enabled? || existing_action?("auto_categorize")- enabled_executors << Rule::ActionExecutor::AutoCategorize.new(rule)+ ACTION_EXECUTOR_CLASSES.filter_map do |executor_class|+ executor_class.new(rule) if offered?(executor_class)end-- if auto_merchant_detection_enabled? || existing_action?("auto_detect_merchants")- enabled_executors << Rule::ActionExecutor::AutoDetectMerchants.new(rule)- end-- enabled_executorsendprivate+ def offered?(executor_class)+ case executor_class.key+ when "auto_categorize"+ auto_categorization_enabled? || existing_action?("auto_categorize")+ when "auto_detect_merchants"+ auto_merchant_detection_enabled? || existing_action?("auto_detect_merchants")+ else+ true+ end+ end+def auto_categorization_enabled?family.resolved_categorization_provider.present?enddiff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rbindex 53a5a79e1c..dc7c99f79a 100644--- a/test/controllers/rules_controller_test.rb+++ b/test/controllers/rules_controller_test.rb@@ -228,6 +228,70 @@ class RulesControllerTest < ActionDispatch::IntegrationTestassert_match(/resource type is invalid/i, response.body)end+ test "rejects unknown action and resource types on create without saving or failing to render" do+ {+ "one unknown action" => { resource_type: "transaction", actions_attributes: { "0" => { action_type: "garbage" } } },+ "two unknown actions" => { resource_type: "transaction",+ actions_attributes: { "0" => { action_type: "garbage" }, "1" => { action_type: "garbage" } } },+ "unknown resource type" => { resource_type: "account", actions_attributes: { "0" => { action_type: "exclude_transaction" } } },+ "unknown resource type, no action" => { resource_type: "account" }+ }.each do |label, rule_params|+ assert_no_difference [ "Rule.count", "Rule::Action.count" ], label do+ post rules_url, params: { rule: rule_params }+ end++ assert_response :unprocessable_entity, label+ assert_equal "text/plain", response.media_type, label+ assert_match(/type is not included in the list/i, response.body, label)+ end+ end++ test "rejects an unknown action type on update" 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: "garbage" } } } }++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_equal original_type, action.reload.action_type+ end++ test "rejects an unknown resource type on update" do+ rule = rules(:one)++ patch rule_url(rule), params: { rule: { resource_type: "account" } }++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_equal "transaction", rule.reload.resource_type+ end++ test "does not render an unknown action type that is marked for destruction" 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: "garbage", _destroy: "1" } } }+ }++ assert_response :unprocessable_entity+ assert_equal "text/plain", response.media_type+ assert_equal original_type, action.reload.action_type+ end++ test "new ignores an unknown resource type or action type" do+ get new_rule_url(resource_type: "account")+ assert_response :success+ assert_select "input[name='rule[resource_type]'][value='transaction']"++ get new_rule_url(resource_type: "transaction", action_type: "garbage", action_value: "x")+ assert_response :success+ assert_select "ul[data-rules-target='actionsList'] li", 0+ 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 22a251231f..727412ca8a 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -1928,6 +1928,27 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert_equal category.id, action.valueend+ test "rejects a rule with an unknown resource type or action type" do+ [+ [ "account", "exclude_transaction" ],+ [ "transaction", "garbage" ]+ ].each do |resource_type, action_type|+ ndjson = build_ndjson([ {+ type: "Rule", version: 1,+ data: { id: "unknown-type-rule", name: "Unknown type", resource_type: resource_type,+ conditions: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ],+ actions: [ { action_type: action_type } ] }+ } ])++ error = assert_raises(ActiveRecord::RecordInvalid, action_type) do+ Family::DataImporter.new(@family, ndjson).import!+ end++ assert_match(/is not included in the list/, error.message)+ assert_nil @family.rules.find_by(name: "Unknown type")+ end+ end+test "rejects invalid rule references before creating related records" dovalid_condition = { condition_type: "transaction_name", operator: "like", value: "coffee" }cases = [diff --git a/test/models/rule_import_test.rb b/test/models/rule_import_test.rbindex 04aea7e18d..dd7522e818 100644--- a/test/models/rule_import_test.rb+++ b/test/models/rule_import_test.rb@@ -442,6 +442,24 @@ class RuleImportTest < ActiveSupport::TestCaseendend+ test "rejects an unknown imported action type" do+ csv = CSV.generate do |rows|+ rows << %w[name resource_type active effective_date conditions actions]+ rows << [+ "Unknown action rule", "transaction", true, nil,+ [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ].to_json,+ [ { action_type: "garbage" } ].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 not included in the list/, error.message)+ assert_nil @family.rules.find_by(name: "Unknown action rule")+ 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 3f74fc9da6..11a3c34aea 100644--- a/test/models/rule_test.rb+++ b/test/models/rule_test.rb@@ -105,6 +105,59 @@ class RuleTest < ActiveSupport::TestCaseendend+ test "rejects an unknown action type" do+ rule = @family.rules.build(resource_type: "transaction")+ action = rule.actions.build(action_type: "garbage")++ assert_not rule.valid?+ assert action.errors.of_kind?(:action_type, :inclusion)+ end++ test "accepts every action executor as an action type" do+ keys = Dir[Rails.root.join("app/models/rule/action_executor/*.rb")].map { |path| File.basename(path, ".rb") }+ assert_includes keys, "auto_categorize"++ keys.each do |key|+ rule = @family.rules.build(resource_type: "transaction")+ action = rule.actions.build(action_type: key)++ assert rule.valid?, "#{key}: #{rule.errors.full_messages.to_sentence}"+ assert_empty action.errors[:action_type], key+ end+ end++ test "rejects an unknown resource type without raising or flagging its actions" do+ rule = @family.rules.build(resource_type: "account")+ action = rule.actions.build(action_type: "exclude_transaction")++ assert_nothing_raised { assert_not rule.valid? }+ assert rule.errors.of_kind?(:resource_type, :inclusion)+ assert_empty action.errors[:action_type]++ rule.resource_type = "transaction"+ assert rule.valid?+ end++ test "keeps reporting a null byte in a type as invalid text" do+ rule = @family.rules.build(resource_type: "transaction\0")+ action = rule.actions.build(action_type: "exclude_transaction\0")++ assert_not rule.valid?+ assert rule.errors.of_kind?(:resource_type, :invalid)+ assert action.errors.of_kind?(:action_type, :invalid)+ assert_not rule.errors.of_kind?(:resource_type, :inclusion)+ assert_not action.errors.of_kind?(:action_type, :inclusion)+ end++ test "an untouched saved action with an unknown type does not block an unrelated edit" do+ rule = @family.rules.create!(resource_type: "transaction", actions_attributes: [ { action_type: "exclude_transaction" } ])+ rule.actions.first.update_column(:action_type, "retired_action")++ rule = Rule.find(rule.id)+ assert rule.update(name: "Renamed"), rule.errors.full_messages.to_sentence+ assert_equal "Renamed", rule.reload.name+ end+test "basic rule" dotransaction_entry = create_transaction(date: Date.current, account: @account, merchant: @whole_foods_merchant)