Add starts with, ends with and regex rule operators

Merged
JA
2mo ago
+1429-10

Closes #4080

Fork pre-flight: jaysbeekay/sure#366 (same branch, same commit). Model layer of drop 11.1 of jaysbeekay/sure#130. The branch merges main at 94c0a5d3e (no rebase), so the diff against main is this PR's change alone.

Merge order: after #4211, or together with it. If an email rule's switch-on baseline times out, this PR leaves the rule inactive. Without #4211, "Apply all" still runs inactive rules, so it would email that rule's historical matches. #4211 makes an inactive rule's email action do nothing.

Summary

Text rule conditions (transaction name, notes) gain three operators: Starts with, Ends with and Matches regex. They appear in the existing rule form's operator list wherever "Contains" does today, and in the assistant's rule tools (get_rule_options, preview_rule, create_rule, update_rule). Users see them as soon as this merges. There is no new screen.

Matches regex is the security-relevant part. A saved pattern runs on every sync, so Rule::SafeRegex bounds it against ReDoS and against patterns that would fail at run time. The limits and their tests are listed under Verification.

Rules run through Rule::Runner (#4013) in their set order, with stop processing. A pattern that times out fails its own rule's turn: the failure is recorded, it claims and stops nothing, and the rules below it still run.

What changed

  • Rule::ConditionFilter adds starts_with, ends_with and matches_regex to the text operator list.
    • Starts with and ends with are ILIKE, with the value passed through sanitize_sql_like, so % and _ match themselves.
    • Matches regex is ~* (case-insensitive), and its value is bound as written. The whitespace normalisation the other text operators apply would change what a pattern matches.
    • TransactionDetails and TransactionType keep their own operator lists and do not gain these.
  • Rule::SafeRegex (new). The pattern runs in PostgreSQL, whose regex engine does not backtrack, so nested quantifiers such as (a+)+$ stay linear. It guards four things:
    • Back-references \1 to \9 (exponential in PostgreSQL's engine) are refused. An escaped backslash before a digit (\\1) is not mistaken for one.
    • A pattern PostgreSQL will not compile (parentheses () not balanced, regular expression is too complex) is probed once at save under a 1 s statement_timeout. It becomes a validation error instead of a rule that fails on every sync. Only SQLSTATE 2201B counts as a bad pattern; any other database error is re-raised.
    • Patterns over 200 characters are refused.
    • with_timeout runs a block under SET LOCAL statement_timeout inside a savepoint, restores the previous value, and raises TimeoutError on QueryCanceled.
  • Rule::Condition adds regex?, uses_regex? (which looks into compound conditions) and a regex_value_is_safe validation.
    • The validation runs only when the value or operator changes, so toggling a rule does not probe its pattern again.
    • It skips a value that DatabaseTextValidator (#4109) rejects, such as a null byte or malformed UTF-8. That value is reported once, as "Value is invalid", and never probed, because the driver refuses to send it.
  • Rule#matching_scope handles rules with a regex condition. When any condition uses a regex, the matching ids are resolved under the 5 s execution timeout and returned as scope_for_transaction_ids(ids). That is one array parameter however many rows match.
    • Every reader goes through it: Rule::Runner, affected_resource_count, matching_transaction_ids, matches_transaction?, matching_resources (assistant preview), total_affected_resource_count and Rule#apply's default scope.
    • When the pattern times out, the display counts read 0, and matches_transaction? reads it as not covering the transaction, so the "create a rule?" prompt is still offered.
    • matches_transaction? passes only_id:, so its regex query runs on that one row.
    • Rule#apply resolves its scope once and hands it to every action, so a rule with several actions scans once.
  • RuleJob adds discard_on Rule::SafeRegex::TimeoutError beside retry_on Rule::Runner::LockBusy. The runner records the failed RuleRun, and the job re-raises the requested rule's error. For a timeout, a Sidekiq retry would time out again and re-run every active rule above, so the job is discarded instead. ApplyRulesJob and ApplyAllRulesJob do not raise for a failing rule; the runner carries on with the next one.
  • Email baseline on a timeout. Rule::Action handles a timeout when the action is created. If the email-notification baseline times out, the action is kept and the rule is switched off, because with no baseline its next run would email every past match.
  • Email baseline on switch-on. Rule gains after_update :seed_notification_baseline, if: :switched_on? (active going from false to true). This covers the toggle, the form, Apply and an import.
    • The callback records the rule's current matches as delivered when it has a send_email_notification action. It runs inside the save's transaction, after the nested conditions are written, so the baseline uses the saved conditions and commits together with active.
    • On a timeout the rule stays off, RulesController#apply queues no run, and the toggle, form and Apply show an alert (rules.notification_baseline_timed_out) instead of the success notice.
    • This deliberately also stops emails for matches that appeared while the rule was off.
  • Assistant rule tools (#3990):
    • RuleSupport#build_condition keeps a regex value as written; other values are still stripped. For example, " shop$" stripped to "shop$" would also match "Workshop".
    • get_rule_options reads the operator list from the filters, so it offers the new operators without a change, and preview_rule counts and samples regex matches through matching_scope.
    • apply_rule activates with update!(active: true), as Apply does. When the email baseline times out, it now returns a baseline_timed_out error and queues nothing, as RulesController#apply does. Before, it queued RuleJob, which runs the requested rule whether or not it is active, and reported the rule as activated.
  • Locales: operator labels and the timeout alert in views/rules/en.yml; the four validation messages in models/rule/en.yml.

Merged with main (13 Oct)

This was opened against main at 00dd977fb. Since then, #4013, #4163, #4109 and #3990 have merged. main (3e35aaa07) is merged into the branch, and the conflicts in Rule and RuleJob are resolved as follows:

  • #4013 (Rule::Runner): the regex timeout surfaces from matching_scope at the rule's turn in the runner. The runner's own rescue records the failed run, and the rule claims and stops nothing. The per-apply regex cache this PR had is removed, since nothing reads it any more. RuleJob keeps upstream's retry_on LockBusy and adds the discard_on.
  • #4163 (rename): the regex branch and only_id: live in matching_scope, which is now public; matching_resources delegates to it.
  • #4109 (null bytes): this PR's own NUL check in Rule::SafeRegex is removed in favour of DatabaseTextValidator. On the plain merge a null byte was reported twice ("is invalid" and "is not a valid regular expression"), and malformed UTF-8 raised ArgumentError from String#blank? in the regex validation. The tests for both now assert one "Value is invalid" error and no probe.
  • #3990 (assistant rule tools): covered by the build_condition and apply_rule changes above.

Merged with main again (15 and 16 Oct)

main was merged in twice more, at 962d91f88 (15 Oct) and 94c0a5d3e (16 Oct), both as merges, so earlier SHAs still apply. None of the upstream commits touch this PR's files, and the PR's own diff against main is byte-identical across both (git patch-id --stable).

At 5bf988b03 (Ruby 3.4.9, PostgreSQL 16, Redis): bin/rails test 11,967 runs, 55,740 assertions, 0 failures, 0 errors, 34 skips. bin/rubocop on the changed files: no offenses. bin/brakeman: 0 warnings.

The test_system failure on the 15 Oct head was AccountsTest#test_can_create_credit_card_account erroring on a Selenium stale-node race ("Node with given id does not belong to the document"). The PR touches no account, JS or layout files, and the same commit passed test_system on the fork pre-flight.

Overlap with open PRs

  • #4176 (create-time baseline) records the baseline when the email action is created, through one after_commit ... on: %i[create update] plus keep_notification_baseline.
    • It does not touch Rule, so it merges cleanly with the switch-on callback here. The two seeds are idempotent inserts.
    • This PR's baseline tests delete any create-time baseline in their helpers. Checked with #4176's Rule::Action applied: they pass (29 runs). Without the deletion, three tests fail.
  • #4150 (re-seed when the match criteria change) adds after_update :seed_notification_baseline, if: :match_criteria_changed? to Rule, with the same method name.
    • Rails keeps only the last callback registered for the same method, so a textual merge that keeps both lines would silently drop one.
    • Whichever lands second should merge them into one: after_update :seed_notification_baseline, if: -> { switched_on? || match_criteria_changed? }.
    • The method body should be this PR's, which adds the TimeoutError rescue that keeps the rule off.

Demo data

None. The demo generator's rules are unchanged; a regex rule can be created from the existing form.

Migration notes

None. No schema change. Existing rules keep their operators and match exactly as before.

Verification

  • bin/rails test at c9f239baf: 11,853 runs, 54,633 assertions, 0 failures, 0 errors, 34 skips.
  • bin/rubocop on the changed Ruby files: no offenses. bin/brakeman --no-pager -q: 0 warnings. No ERB or JavaScript changed.
  • Fail-first, re-run on the merged branch. This PR's tests were run against main's versions of the changed app files, with Rule::SafeRegex removed: 111 runs, 17 failures, 47 errors. Examples: UnsupportedOperatorError: Unsupported operator: starts_with, and NameError: Rule::SafeRegex.
  • Ordered run, timeout and email baseline together (regex_execution_test.rb):
    • An active, stop-processing email rule at the top whose pattern times out under ApplyRulesJob gets a failed run and is not raised. It emails nothing and records no delivery. The rule below it decides the category, and that rule's stop processing still holds for the one below.
    • RuleJob for a rule below a timed-out one records that failure and runs the requested rule.
    • An email rule left off by a timed-out switch-on baseline is skipped by the sync run, even once its pattern runs in time.
  • ReDoS and limits (safe_regex_test.rb, condition_regex_test.rb, regex_execution_test.rb):
    • Back-references are refused, and \\1 is accepted. Nested quantifiers are accepted, because PostgreSQL runs them linearly.
    • Length is capped at the boundary: 200 accepted, 201 refused.
    • Unbalanced and too-complex patterns are refused at save, and nothing is saved.
    • A non-regex database error is re-raised. A failed probe does not poison an open transaction.
    • with_timeout raises TimeoutError and restores the limit afterwards.
    • A match query that really sleeps in PostgreSQL is cancelled (no stub), in under 0.9 s against a 30 ms limit. A regex inside a compound condition is bounded too.
    • A null byte, a lone null byte and malformed UTF-8 are each rejected as invalid text without a probe.
    • Regex matches are bound as one parameter whatever the match count. Before the fix this showed 7 binds against 6.
  • Operators (condition_filter/text_operators_test.rb, preview_rule_test.rb):
    • Prefix and suffix match without mid-string hits, on name and on notes, and % and _ are literal.
    • The regex is case-insensitive, honours anchors, and its whitespace is not normalised.
    • The operators are offered on the right filters.
    • The assistant preview counts and samples all three. It keeps a regex's leading space (before the fix: expected 1 match, got 2), and it reports an uncompilable pattern as a problem.
    • apply_rule on an email rule whose baseline times out leaves it off and queues nothing (before the fix: 0 jobs expected, but 1 were enqueued).
  • Switch-on baseline (notification_baseline_on_enable_test.rb, rules_controller_test.rb):
    • Switching on records the matches without emailing them, and a later match is still emailed.
    • The baseline uses conditions changed, or removed, in the same submit.
    • Negatives: no email action, already on, switching off.
    • A timeout leaves the rule off and keeps the rest of the save. Apply then queues nothing and alerts, and the toggle alerts.
  • Mutations on the merged code. Each line below was broken on purpose and caught by the tests named:
    • Skipping the regex branch in matching_scope: 18 tests.
    • Removing the affected_resource_count rescue, the matches_transaction? rescue, the action-baseline rescue, or discard_on: one named test each.
    • Swallowing the timeout inside matching_scope: 11 tests, including both ordered-run tests.
    • Removing the switch-on callback: 10 tests. Leaving the rule on after a switch-on timeout: 4 tests.
    • Dropping starts_with from the operator list: 6 tests. Dropping matches_regex: 28 tests.
    • Dropping the only_id: narrowing: 2 tests.
    • Dropping the DatabaseTextValidator guard: the three invalid-text tests.
    • Binding with where(id: ids): the bind test.
    • Stripping the regex in build_condition, or removing apply_rule's timeout guard: one named test each.
    • The earlier 36 mutations, on 8c2a470ea, are in jaysbeekay/sure#366.

Blast radius

Who else hits this line, and what do they pass?

matching_scope is read by:

  • Rule::Runner#unstopped_scope, once per rule per run;
  • affected_resource_count (the rule confirmation page, the assistant's get_rules and apply_rule, and the auto-categorize cost estimate);
  • total_affected_resource_count (apply-all confirmation);
  • matching_transaction_ids (the email baseline, in Rule::Action and in Rule's switch-on callback);
  • matches_transaction? (Transaction::Ruleable#eligible_for_category_rule?, one transaction per call, so it passes only_id:);
  • matching_resources (the assistant's preview, which counts and samples);
  • Rule#apply's default scope.

For a rule with no regex condition the scope is returned unchanged. For a regex rule, each reader has its own answer to a timeout, listed above, and each has a test.

The assistant preview is the one reader without its own rescue. A timeout there falls to FunctionToolCaller's and McpController's generic rescue, so the tool fails and no preview token is issued.

What else reads what I just changed the reading of? grep -rn "OPERATORS_MAP\|def operators\|build_sanitized_where_condition" app/models/rule finds:

  • ConditionFilter#operators, which feeds the rule form through as_json (app/javascript/controllers/rule/conditions_controller.js), validate_operator, and the assistant's build_condition and get_rule_options;
  • TransactionName and TransactionNotes, which inherit the text list;
  • TransactionDetails and TransactionType, which override it and are deliberately unchanged.

The other writers of condition values:

  • RuleImport (CSV) and Family::DataImporter build conditions through Rule::Condition, so an imported regex is validated the same way.
  • The API (api/v1/rules) is read-only.
  • Writers of active (the switch-on callback) are the toggle, the form and Apply (RulesController), apply_rule (assistant, which now checks the timeout as Apply does), Rule.create_from_grouping (a create, with no email action), the importers (which rebuild the actions, so the action's own seed applies as well), and Rule::Action's timeout path (update_columns, which skips callbacks).

Summary by CodeRabbit

  • New Features
    • Added “Starts with,” “Ends with,” and “Matches regex” options for text-based rule conditions.
    • Added validation and clear feedback for invalid, overly complex, or unsupported regular expressions.
  • Bug Fixes
    • Rules that time out while checking matches remain inactive when enabled, and their application is skipped.
    • Timed-out rules no longer prevent subsequent rules from running.
    • Enabling email rules records existing matches as a notification baseline, preventing emails for transactions that already matched.
    • Preview and rule creation or update now report when matching times out.