Skip to content

A platform for community discussion. Free, open, simple.

FIX: silent failure when watched words contains invalid regex (#36132)

Régis Hanolf07137e4c6f4
diff --git a/app/assets/stylesheets/admin/staff_logs.scss b/app/assets/stylesheets/admin/staff_logs.scss
index 36161577840..c927c8416c9 100644
--- a/app/assets/stylesheets/admin/staff_logs.scss
+++ b/app/assets/stylesheets/admin/staff_logs.scss
@@ -307,6 +307,13 @@ table.screened-ip-addresses {
}
// Watched words
+.watched-word-regex-errors {
+ max-height: 200px;
+ overflow-y: auto;
+ list-style-type: disc;
+ padding-left: 20px;
+}
+
.watched-word-box {
display: inline-block;
width: 250px;
diff --git a/app/services/word_watcher.rb b/app/services/word_watcher.rb
index ab453bce8a7..119c8e71da2 100644
--- a/app/services/word_watcher.rb
+++ b/app/services/word_watcher.rb
@@ -79,8 +79,12 @@ class WordWatcher
r = word_to_regexp(word, match_word: SiteSetting.watched_words_regular_expressions?)
begin
r if Regexp.new(r)
- rescue RegexpError
+ rescue RegexpError => e
raise if raise_errors
+ Rails.logger.warn(
+ "Watched word '#{word}' has invalid regex '#{r}' for #{action}: #{e.message}",
+ )
+ nil
end
end
.select { |r| r.present? }
@@ -96,7 +100,15 @@ class WordWatcher
) if !SiteSetting.watched_words_regular_expressions?
# Add case insensitive flag if needed
- Regexp.new(regexp, group_key == :case_sensitive ? nil : Regexp::IGNORECASE)
+ begin
+ Regexp.new(regexp, group_key == :case_sensitive ? nil : Regexp::IGNORECASE)
+ rescue RegexpError => e
+ raise if raise_errors
+ Rails.logger.warn(
+ "Watched word compilation failed for #{action} (#{group_key}): #{e.message}. Regexp: #{regexp}",
+ )
+ nil
+ end
end
.compact
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 89c0df13a63..c18873d0c1d 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -7750,6 +7750,7 @@ en:
clear_all: Clear all
clear_all_confirm: "Are you sure you want to clear all watched words for the %{action} action?"
invalid_regex: 'The watched word "%{word}" is an invalid regular expression.'
+ invalid_regex_multiple: "Invalid Regular Expressions:"
regex_warning: '<a href="%{basePath}/admin/site_settings/category/all_results?filter=watched%20words%20regular%20expressions%20">Watched words are regular expressions</a> and they do not automatically include word boundaries. If you want the regular expression to match whole words, include <code>\b</code> at the start and end of your regular expression.'
actions:
block: "Block"
diff --git a/frontend/discourse/admin/components/modal/watched-word-testing.gjs b/frontend/discourse/admin/components/modal/watched-word-testing.gjs
index 51467574aa3..2d7f3190f15 100644
--- a/frontend/discourse/admin/components/modal/watched-word-testing.gjs
+++ b/frontend/discourse/admin/components/modal/watched-word-testing.gjs
@@ -1,5 +1,5 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
+import { cached, tracked } from "@glimmer/tracking";
import { Textarea } from "@ember/component";
import DModal from "discourse/components/d-modal";
import { or } from "discourse/truth-helpers";
@@ -20,70 +20,126 @@ export default class WatchedWordTesting extends Component {
return this.args.model.watchedWord.nameKey === "link";
}
- get matches() {
- if (
- !this.value ||
- this.args.model.watchedWord.compiledRegularExpression.length === 0
- ) {
- return [];
+ cleanErrorMessage(message) {
+ const parts = message.split(": ");
+ return parts[parts.length - 1];
+ }
+
+ @cached
+ get matchesAndErrors() {
+ const errors = {};
+
+ const addError = (word, message) => {
+ errors[word] ??= this.cleanErrorMessage(message);
+ };
+
+ const errorsToArray = () =>
+ Object.entries(errors).map(([word, error]) => ({ word, error }));
+
+ if (!this.value) {
+ return { matches: [], errors: [] };
}
if (this.isReplace || this.isLink) {
const matches = [];
this.args.model.watchedWord.words.forEach((word) => {
- const regexp = new RegExp(
- word.regexp,
- word.case_sensitive ? "gu" : "gui"
- );
- let match;
-
- while ((match = regexp.exec(this.value)) !== null) {
- matches.push({
- match: match[1],
- replacement: word.replacement,
- });
+ try {
+ const regexp = new RegExp(
+ word.regexp,
+ word.case_sensitive ? "gu" : "gui"
+ );
+ let match;
+
+ while ((match = regexp.exec(this.value)) !== null) {
+ matches.push({
+ match: match[1],
+ replacement: word.replacement,
+ });
+ }
+ } catch (e) {
+ addError(word.word, e.message);
}
});
- return matches;
+ return { matches, errors: errorsToArray() };
}
if (this.isTag) {
const matches = new Map();
this.args.model.watchedWord.words.forEach((word) => {
- const regexp = new RegExp(
- word.regexp,
- word.case_sensitive ? "gu" : "gui"
- );
- let match;
-
- while ((match = regexp.exec(this.value)) !== null) {
- if (!matches.has(match[1])) {
- matches.set(match[1], new Set());
+ try {
+ const regexp = new RegExp(
+ word.regexp,
+ word.case_sensitive ? "gu" : "gui"
+ );
+ let match;
+
+ while ((match = regexp.exec(this.value)) !== null) {
+ if (!matches.has(match[1])) {
+ matches.set(match[1], new Set());
+ }
+
+ const tags = matches.get(match[1]);
+ word.replacement.split(",").forEach((tag) => tags.add(tag));
}
-
- const tags = matches.get(match[1]);
- word.replacement.split(",").forEach((tag) => tags.add(tag));
+ } catch (e) {
+ addError(word.word, e.message);
}
});
- return Array.from(matches, ([match, tagsSet]) => ({
- match,
- tags: Array.from(tagsSet),
- }));
+ return {
+ matches: Array.from(matches, ([match, tagsSet]) => ({
+ match,
+ tags: Array.from(tagsSet),
+ })),
+ errors: errorsToArray(),
+ };
}
let matches = [];
+ let hasCompiledExpressionError = false;
+
this.args.model.watchedWord.compiledRegularExpression.forEach((entry) => {
- const [regexp, options] = Object.entries(entry)[0];
- const wordRegexp = new RegExp(
- regexp,
- options.case_sensitive ? "gu" : "gui"
- );
+ try {
+ const [regexp, options] = Object.entries(entry)[0];
+ const wordRegexp = new RegExp(
+ regexp,
+ options.case_sensitive ? "gu" : "gui"
+ );
- matches.push(...(this.value.match(wordRegexp) || []));
+ matches.push(...(this.value.match(wordRegexp) || []));
+ } catch {
+ hasCompiledExpressionError = true;
+ }
});
- return matches;
+ if (hasCompiledExpressionError) {
+ matches = [];
+ this.args.model.watchedWord.words.forEach((word) => {
+ try {
+ const regexp = new RegExp(
+ word.regexp,
+ word.case_sensitive ? "gu" : "gui"
+ );
+ let match;
+
+ while ((match = regexp.exec(this.value)) !== null) {
+ matches.push(match[1] || match[0]);
+ }
+ } catch (e) {
+ addError(word.word, e.message);
+ }
+ });
+ }
+
+ return { matches, errors: errorsToArray() };
+ }
+
+ get matches() {
+ return this.matchesAndErrors.matches;
+ }
+
+ get regexErrors() {
+ return this.matchesAndErrors.errors;
}
<template>
diff --git a/frontend/discourse/admin/controllers/admin-watched-words/action.js b/frontend/discourse/admin/controllers/admin-watched-words/action.js
index db2e5b29dae..23cd7670dc7 100644
--- a/frontend/discourse/admin/controllers/admin-watched-words/action.js
+++ b/frontend/discourse/admin/controllers/admin-watched-words/action.js
@@ -1,4 +1,4 @@
-import { tracked } from "@glimmer/tracking";
+import { cached, tracked } from "@glimmer/tracking";
import Controller, { inject as controller } from "@ember/controller";
import { action } from "@ember/object";
import { or } from "@ember/object/computed";
@@ -34,14 +34,35 @@ export default class AdminWatchedWordsActionController extends Controller {
);
}
- get regexpError() {
- for (const { regexp, word } of this.currentAction.words) {
+ @cached
+ get regexpErrors() {
+ const errors = [];
+ const seen = new Set();
+
+ if (!this.currentAction?.words) {
+ return errors;
+ }
+
+ for (const { regexp, word, id } of this.currentAction.words) {
+ if (!regexp) {
+ continue;
+ }
+
try {
- RegExp(regexp);
- } catch {
- return i18n("admin.watched_words.invalid_regex", { word });
+ // eslint-disable-next-line no-new
+ new RegExp(regexp, "u");
+ } catch (e) {
+ const key = `${id}:${word}:${e.message}`;
+ if (!seen.has(key)) {
+ seen.add(key);
+ const parts = e.message.split(": ");
+ const cleanError = parts[parts.length - 1];
+ errors.push({ word, error: cleanError });
+ }
}
}
+
+ return errors;
}
get actionDescription() {
diff --git a/frontend/discourse/admin/templates/admin-watched-words/action.gjs b/frontend/discourse/admin/templates/admin-watched-words/action.gjs
index 4fe4ba86d29..f99bada19e0 100644
--- a/frontend/discourse/admin/templates/admin-watched-words/action.gjs
+++ b/frontend/discourse/admin/templates/admin-watched-words/action.gjs
@@ -8,8 +8,18 @@ import basePath from "discourse/helpers/base-path";
import { i18n } from "discourse-i18n";
export default <template>
- {{#if @controller.regexpError}}
- <div class="alert alert-error">{{@controller.regexpError}}</div>
+ {{#if @controller.regexpErrors.length}}
+ <div class="alert alert-error">
+ <strong>{{i18n "admin.watched_words.invalid_regex_multiple"}}</strong>
+ <ul class="watched-word-regex-errors">
+ {{#each @controller.regexpErrors as |error|}}
+ <li>
+ <strong>{{error.word}}</strong>:
+ {{error.error}}
+ </li>
+ {{/each}}
+ </ul>
+ </div>
{{/if}}
<div class="watched-word-controls">
diff --git a/frontend/discourse/tests/acceptance/admin-watched-words-test.js b/frontend/discourse/tests/acceptance/admin-watched-words-test.js
index c06750b1e09..9f20ae3e049 100644
--- a/frontend/discourse/tests/acceptance/admin-watched-words-test.js
+++ b/frontend/discourse/tests/acceptance/admin-watched-words-test.js
@@ -215,3 +215,207 @@ acceptance("Admin - Watched Words - Bad regular expressions", function (needs) {
assert.dom(".admin-watched-words .alert-error").exists({ count: 1 });
});
});
+
+acceptance(
+ "Admin - Watched Words - Mixed valid and invalid regex",
+ function (needs) {
+ needs.user();
+ needs.pretender((server, helper) => {
+ server.get("/admin/customize/watched_words.json", () => {
+ return helper.response({
+ actions: ["block", "censor", "require_approval", "flag", "replace"],
+ words: [
+ {
+ id: 1,
+ word: "Hi",
+ regexp: "(\\W|^)(Hi)(?=\\W|$)",
+ replacement: "hello",
+ action: "replace",
+ },
+ {
+ id: 2,
+ word: "test[[",
+ regexp: "(test[[)",
+ replacement: "broken",
+ action: "replace",
+ },
+ {
+ id: 3,
+ word: "bye",
+ regexp: "(\\W|^)(bye)(?=\\W|$)",
+ replacement: "goodbye",
+ action: "replace",
+ },
+ ],
+ compiled_regular_expressions: {
+ block: [],
+ censor: [],
+ require_approval: [],
+ flag: [],
+ replace: [],
+ },
+ });
+ });
+ });
+
+ test("test modal works with replace action when invalid regex present", async function (assert) {
+ await visit("/admin/customize/watched_words/action/replace");
+ await click(".watched-word-test");
+ await fillIn(".d-modal__body textarea", "Hi there, bye!");
+
+ assert
+ .dom(".d-modal__body ul li")
+ .exists(
+ { count: 2 },
+ "Should find matches for both valid words 'Hi' and 'bye'"
+ );
+ });
+ }
+);
+
+acceptance(
+ "Admin - Watched Words - Block action with invalid compiled expression",
+ function (needs) {
+ needs.user();
+ needs.pretender((server, helper) => {
+ server.get("/admin/customize/watched_words.json", () => {
+ return helper.response({
+ actions: ["block", "censor", "require_approval", "flag", "replace"],
+ words: [
+ {
+ id: 1,
+ word: "foo",
+ regexp: "(\\W|^)(foo)(?=\\W|$)",
+ action: "block",
+ },
+ {
+ id: 2,
+ word: "test[[",
+ regexp: "(test[[)",
+ action: "block",
+ },
+ {
+ id: 3,
+ word: "bar",
+ regexp: "(\\W|^)(bar)(?=\\W|$)",
+ action: "block",
+ },
+ ],
+ compiled_regular_expressions: {
+ // Simulate a broken compiled expression that includes valid and invalid regexes
+ block: [
+ {
+ "(\\W|^)(foo|test[[|bar)(?=\\W|$)": { case_sensitive: false },
+ },
+ ],
+ censor: [],
+ require_approval: [],
+ flag: [],
+ replace: [],
+ },
+ });
+ });
+ });
+
+ test("shows error for invalid regex on main page", async function (assert) {
+ await visit("/admin/customize/watched_words/action/block");
+
+ assert.dom(".admin-watched-words .alert-error").exists({ count: 1 });
+ assert
+ .dom(".admin-watched-words .alert-error")
+ .containsText("test[[", "Shows the invalid word in error message");
+ assert
+ .dom(".admin-watched-words .alert-error")
+ .containsText(
+ "Unterminated character class",
+ "Shows the error description"
+ );
+ });
+
+ test("test modal falls back to individual words when compiled expression fails", async function (assert) {
+ await visit("/admin/customize/watched_words/action/block");
+ await click(".watched-word-test");
+ await fillIn(".d-modal__body textarea", "this foo and bar text");
+
+ assert
+ .dom(".d-modal__body")
+ .doesNotContainText(
+ "No matches found",
+ "Should find matches via individual word fallback"
+ );
+
+ assert
+ .dom(".d-modal__body")
+ .containsText("Found matches:", "Should show matches");
+
+ assert
+ .dom(".d-modal__body ul li")
+ .exists({ count: 2 }, "Should find both foo and bar");
+ });
+ }
+);
+
+acceptance("Admin - Watched Words - Unicode flag validation", function (needs) {
+ needs.user();
+ needs.pretender((server, helper) => {
+ server.get("/admin/customize/watched_words.json", () => {
+ return helper.response({
+ actions: ["block", "censor", "require_approval", "flag", "replace"],
+ words: [
+ {
+ id: 1,
+ word: "pattern1",
+ regexp: "(pattern[[nested]])",
+ action: "block",
+ },
+ {
+ id: 2,
+ word: "pattern2",
+ regexp: "(test{incomplete)",
+ action: "block",
+ },
+ ],
+ compiled_regular_expressions: {
+ block: [],
+ censor: [],
+ require_approval: [],
+ flag: [],
+ replace: [],
+ },
+ });
+ });
+ });
+
+ test("detects invalid patterns with unicode flag validation", async function (assert) {
+ await visit("/admin/customize/watched_words/action/block");
+
+ assert
+ .dom(".admin-watched-words .alert-error ul li")
+ .exists(
+ { count: 2 },
+ "Shows errors for both patterns with unicode validation"
+ );
+
+ assert
+ .dom(".admin-watched-words .alert-error")
+ .containsText("pattern1", "Shows first invalid pattern");
+
+ assert
+ .dom(".admin-watched-words .alert-error")
+ .containsText("pattern2", "Shows second invalid pattern");
+
+ assert
+ .dom(".admin-watched-words .alert-error")
+ .containsText(
+ "Lone quantifier brackets",
+ "Shows error for nested brackets"
+ );
+
+ assert
+ .dom(".admin-watched-words .alert-error")
+ .containsText(
+ "Incomplete quantifier",
+ "Shows error for incomplete quantifier"
+ );
+ });
+});
diff --git a/spec/services/word_watcher_spec.rb b/spec/services/word_watcher_spec.rb
index 6ae66ec4a32..0867d2d2b4f 100644
--- a/spec/services/word_watcher_spec.rb
+++ b/spec/services/word_watcher_spec.rb
@@ -137,6 +137,42 @@ RSpec.describe WordWatcher do
expect(regexps).to be_empty
end
end
+
+ context "when there's an invalid regex that causes compilation to fail" do
+ before do
+ SiteSetting.watched_words_regular_expressions = true
+ WatchedWord.where(action: WatchedWord.actions[:block]).delete_all
+ Fabricate(:watched_word, word: "test[[", action: WatchedWord.actions[:block])
+ Fabricate(:watched_word, word: "bad", action: WatchedWord.actions[:block])
+ Fabricate(:watched_word, word: "word", action: WatchedWord.actions[:block])
+ end
+
+ it "does not raise an exception and still compiles valid words" do
+ expect { described_class.compiled_regexps_for_action(:block) }.not_to raise_error
+ regexps = described_class.compiled_regexps_for_action(:block)
+ expect(regexps).to be_an(Array)
+ expect(regexps).not_to be_empty
+ expect(regexps.first.inspect).to match(/bad.*word/i)
+ end
+
+ it "still detects matches for valid words even with invalid regex present" do
+ watcher = described_class.new("This is a bad word")
+ expect(watcher.should_block?).to be_truthy
+ expect(watcher.word_matches_for_action?(:block, all_matches: true)).to include(
+ "bad",
+ "word",
+ )
+ end
+
+ it "does not break serialized_regexps_for_action" do
+ expect {
+ described_class.serialized_regexps_for_action(:block, engine: :js)
+ }.not_to raise_error
+ serialized = described_class.serialized_regexps_for_action(:block, engine: :js)
+ expect(serialized).to be_an(Array)
+ expect(serialized).not_to be_empty
+ end
+ end
end
describe "#word_matches_for_action?" do