A platform for community discussion. Free, open, simple.
FIX: Watched word with invalid regex crashes markdown cook (#40107)
Alan Guo Xiang Tana0a86b014e6b
diff --git a/app/services/word_watcher.rb b/app/services/word_watcher.rbindex 46282e0e8b9..9364097f120 100644--- a/app/services/word_watcher.rb+++ b/app/services/word_watcher.rb@@ -54,7 +54,20 @@ class WordWatcherenddef self.regexps_for_action(action)- cached_words_for_action(action)&.to_h { |_, attrs| [word_to_regexp(attrs[:word]), attrs] }+ words = cached_words_for_action(action)+ return if words.blank?++ words.each_with_object({}) do |(_, attrs), hash|+ regexp = word_to_regexp(attrs[:word])+ begin+ Regexp.new(regexp)+ hash[regexp] = attrs+ rescue RegexpError => e+ Rails.logger.warn(+ "Watched word '#{attrs[:word]}' has invalid regex '#{regexp}' for #{action}: #{e.message}",+ )+ end+ endend# This regexp is run in miniracer, and the client JS appdiff --git a/spec/services/word_watcher_spec.rb b/spec/services/word_watcher_spec.rbindex a2cf184366b..d30e4561556 100644--- a/spec/services/word_watcher_spec.rb+++ b/spec/services/word_watcher_spec.rb@@ -52,6 +52,34 @@ RSpec.describe WordWatcher doendend+ describe ".regexps_for_action" do+ before { SiteSetting.watched_words_regular_expressions = true }++ it "maps valid words to their attrs and drops words whose regex is invalid" do+ Fabricate(+ :watched_word,+ action: WatchedWord.actions[:replace],+ word: "hello",+ replacement: "hi",+ )+ Fabricate(:watched_word, action: WatchedWord.actions[:replace], word: "+1")++ result = nil+ fake_logger = track_log_messages { result = described_class.regexps_for_action(:replace) }++ expect(result).to eq("(hello)" => { word: "hello", replacement: "hi", case_sensitive: false })+ expect(fake_logger.warnings).to eq(+ [+ "Watched word '+1' has invalid regex '(+1)' for replace: target of repeat operator is not specified: /(+1)/",+ ],+ )+ end++ it "returns nil when no watched words exist for the action" do+ expect(described_class.regexps_for_action(:replace)).to be_nil+ end+ end+describe ".compiled_regexps_for_action" dolet!(:word1) { Fabricate(:watched_word, action: WatchedWord.actions[:block]).word }let!(:word2) { Fabricate(:watched_word, action: WatchedWord.actions[:block]).word }