A platform for community discussion. Free, open, simple.
FIX: Preserve safe formatting in reviewable reasons (#42164)
Régis Hanol97c241a71878
diff --git a/app/serializers/reviewable_score_serializer.rb b/app/serializers/reviewable_score_serializer.rbindex 870ca4ea915..b8cbb681383 100644--- a/app/serializers/reviewable_score_serializer.rb+++ b/app/serializers/reviewable_score_serializer.rb@@ -1,6 +1,27 @@# frozen_string_literal: trueclass ReviewableScoreSerializer < ApplicationSerializer+ REASON_COOK_OPTIONS = {+ features_override: [].freeze,+ markdown_it_rules: %w[+ autolink+ list+ backticks+ newline+ code+ fence+ linkify+ link+ strikethrough+ blockquote+ emphasis+ escape+ entity+ html_block+ html_inline+ ].freeze,+ }.freeze+REASONS_AND_SETTINGS = {post_count: "approve_post_count",trust_level: "approve_unless_trust_level",@@ -47,6 +68,7 @@ class ReviewableScoreSerializer < ApplicationSerializerenddef reason+ return @reason if defined?(@reason)return unless object.reasonlink_text = setting_name_for_reason(object.reason)@@ -56,15 +78,15 @@ class ReviewableScoreSerializer < ApplicationSerializerlink = build_link_for(object.reason, link_text)if object.reason == "watched_word"- text = watched_word_reason(link)- else- text = I18n.t("reviewables.reasons.#{object.reason}", link: link, default: object.reason)+ return @reason = PrettyText.sanitize("<p>#{watched_word_reason(link)}</p>")end++ text = I18n.t("reviewables.reasons.#{object.reason}", link:, default: object.reason)elsetext = I18n.t("reviewables.reasons.#{object.reason}", default: object.reason)end- text+ @reason = PrettyText.cook(text, REASON_COOK_OPTIONS)enddef reason_type@@ -96,16 +118,17 @@ class ReviewableScoreSerializer < ApplicationSerializerdef watched_word_reason(link)words = watched_words_found+ default = "watched_word"if words.nil? || words.empty?- I18n.t("reviewables.reasons.no_context.watched_word", link: link, default: "watched_word")+ I18n.t("reviewables.reasons.no_context.watched_word", link:, default:)elseI18n.t("reviewables.reasons.watched_word",- link: link,- words: words.map { |w| CGI.escapeHTML(w) }.join(", "),- count: words.length,- default: "watched_word",+ link:,+ words: words.map { |word| CGI.escapeHTML(word) }.join(", "),+ count: words.size,+ default:,)endenddiff --git a/frontend/discourse/app/components/reviewable/timeline.gjs b/frontend/discourse/app/components/reviewable/timeline.gjsindex 0f6b3fb9c50..94c5a45da79 100644--- a/frontend/discourse/app/components/reviewable/timeline.gjs+++ b/frontend/discourse/app/components/reviewable/timeline.gjs@@ -84,7 +84,7 @@ export default class ReviewableTimeline extends Component {let flaggedDescription = "";if (score.reason) {// generated by the server- flaggedDescription += `<p>${score.reason}</p>`;+ flaggedDescription += score.reason;}if (score.context) {// user inputdiff --git a/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs b/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjsindex d0539ad0050..dab53501804 100644--- a/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs+++ b/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs@@ -21,7 +21,7 @@ module("Integration | Component | Reviewable | Timeline", function (hooks) {test("sanitizes dangerous markup in a flag reason but preserves safe links", async function (assert) {const reviewable = reviewableWithReason(- `Spam detected <img src=x onerror=alert(1)> <a href="javascript:alert(2)">phish</a> <a href="/admin">see settings</a>`+ `<p>Spam detected <img src=x onerror=alert(1)> <a href="javascript:alert(2)">phish</a> <a href="/admin">see settings</a></p>`);await render(@@ -35,4 +35,21 @@ module("Integration | Component | Reviewable | Timeline", function (hooks) {"renders the sanitized flag reason");});++ test("renders a cooked flag reason without altering its structure", async function (assert) {+ const reviewable = reviewableWithReason(+ "<p>First line<br>Second line</p><p>Fourth line</p>"+ );++ await render(+ <template><ReviewableTimeline @reviewable={{reviewable}} /></template>+ );++ assert+ .dom(".timeline-event__description")+ .hasHtml(+ "<p>First line<br>Second line</p><p>Fourth line</p>",+ "renders the cooked HTML directly"+ );+ });});diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 28d82678a95..90318a5e18a 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -39,8 +39,7 @@ en:flagged_post: |%{score_reason}%{response}- flagged_post_response: |- <p>Response from the model: %{llm_response}</p>+ flagged_post_response: "Response from the model: %{llm_response}"flagged_post_score_reason: |<b>Triggered by the <a href="%{base_path}/admin/plugins/automation/%{automation_id}">%{automation_name}</a> rule.</b>notify_author_pm:diff --git a/plugins/discourse-ai/lib/automation.rb b/plugins/discourse-ai/lib/automation.rbindex 9b8689c79a4..cd30a31f833 100644--- a/plugins/discourse-ai/lib/automation.rb+++ b/plugins/discourse-ai/lib/automation.rb@@ -69,7 +69,7 @@ module DiscourseAidef self.flag_post_response(reason:, llm_response: nil)I18n.t("discourse_automation.scriptables.llm_triage.flagged_post_response",- llm_response: ERB::Util.html_escape(llm_response.presence || reason),+ llm_response: llm_response.presence || reason,)enddiff --git a/plugins/discourse-ai/spec/lib/agents/tools/flag_post_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/flag_post_spec.rbindex 9402f1ec0c1..ea4a6b2d4db 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/flag_post_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/flag_post_spec.rb@@ -93,13 +93,14 @@ RSpec.describe DiscourseAi::Agents::Tools::FlagPost doexpect(post.reload).to be_hiddenend- it "escapes llm response and automation name in automation flag reasons" do+ it "sanitizes the llm response and renders the automation name literally" do+ automation_name = %(rule"><img src=x onerror=1>)context =DiscourseAi::Agents::BotContext.new(- post: post,+ post:,feature_context: {automation_id: "123",- automation_name: %(rule"><img src=x onerror=1>),+ automation_name:,llm_response: "<img src=x onerror=alert(1)>",base_path: Discourse.base_path,},@@ -117,10 +118,19 @@ RSpec.describe DiscourseAi::Agents::Tools::FlagPost doexpect(result[:status]).to eq("flagged")- score_reason = ReviewablePost.last.reviewable_scores.first.reason- expect(score_reason).to include("<img src=x onerror=alert(1)>")- expect(score_reason).to include("rule"><img src=x onerror=1>")- expect(score_reason).not_to include("<img src=x onerror=alert(1)>")- expect(score_reason).not_to include(%(rule"><img src=x onerror=1>))+ score = ReviewablePost.last.reviewable_scores.first+ serialized =+ ReviewableScoreSerializer.new(score, scope: Discourse.system_user.guardian, root: nil)++ expect(serialized.reason).to match_html(<<~HTML)+ <p>+ <b>+ Triggered by the+ <a href="/admin/plugins/automation/123">#{CGI.escapeHTML(automation_name)}</a>+ rule.+ </b>+ </p>+ <p>Response from the model: <img src=""></p>+ HTMLendenddiff --git a/plugins/discourse-ai/spec/lib/discourse_automation/automation_spec.rb b/plugins/discourse-ai/spec/lib/discourse_automation/automation_spec.rbindex 7050d6d982b..0a80d673a69 100644--- a/plugins/discourse-ai/spec/lib/discourse_automation/automation_spec.rb+++ b/plugins/discourse-ai/spec/lib/discourse_automation/automation_spec.rb@@ -3,6 +3,33 @@RSpec.describe DiscourseAi::Automation dobefore { enable_current_plugin }+ describe ".flag_post_reason" do+ it "produces a Markdown-compatible reason" do+ reason =+ described_class.flag_post_reason(+ reason:+ "**Details**\n\n- first\n- second\n\n> quoted evidence\n\n<script>alert(1)</script>",+ automation_id: "1",+ automation_name: "Test",+ )+ score = ReviewableScore.new(reviewable: ReviewableFlaggedPost.new, reason:)+ serialized =+ ReviewableScoreSerializer.new(score, scope: Discourse.system_user.guardian, root: nil)++ expect(serialized.reason).to match_html(<<~HTML)+ <p><b>Triggered by the <a href="/admin/plugins/automation/1">Test</a> rule.</b></p>+ <p>Response from the model: <strong>Details</strong></p>+ <ul>+ <li>first</li>+ <li>second</li>+ </ul>+ <blockquote>+ <p>quoted evidence</p>+ </blockquote>+ HTML+ end+ end+describe "manually configured model" dolet!(:llm_model) { Fabricate(:llm_model) }it "returns a list of available models for automation" dodiff --git a/plugins/discourse-ai/spec/lib/modules/automation/llm_triage_spec.rb b/plugins/discourse-ai/spec/lib/modules/automation/llm_triage_spec.rbindex dddb2211a82..52b513e454c 100644--- a/plugins/discourse-ai/spec/lib/modules/automation/llm_triage_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/automation/llm_triage_spec.rb@@ -517,7 +517,7 @@ describe DiscourseAi::Automation::LlmTriage do)end- it "escapes llm response and automation name in the flagged post message" do+ it "sanitizes the llm response and renders the automation name literally" doautomation = Fabricate(:automation, script: "llm_triage", name: %(rule"><img src=x onerror=1>))DiscourseAi::Completions::Llm.with_prepared_responses(["<img src=x onerror=alert(1)>"]) do@@ -530,12 +530,22 @@ describe DiscourseAi::Automation::LlmTriage do)end- score_reason = ReviewablePost.last.reviewable_scores.first.reason-- expect(score_reason).to include("<img src=x onerror=alert(1)>")- expect(score_reason).to include("rule"><img src=x onerror=1>")- expect(score_reason).not_to include("<img src=x onerror=alert(1)>")- expect(score_reason).not_to include(%(rule"><img src=x onerror=1>))+ score = ReviewablePost.last.reviewable_scores.first+ serialized =+ ReviewableScoreSerializer.new(score, scope: Discourse.system_user.guardian, root: nil)++ expect(serialized.reason).to match_html(<<~HTML)+ <p>+ <b>+ Triggered by the+ <a href="/admin/plugins/automation/#{automation.id}">+ #{CGI.escapeHTML(automation.name)}+ </a>+ rule.+ </b>+ </p>+ <p>Response from the model: <img src=""></p>+ HTMLendit "only sends one PM when multiple rules flag the same post" dodiff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rbindex 7cc5042c028..247ebbb7acf 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb@@ -142,7 +142,7 @@ module DiscourseWorkflowsdef score_reason_for(exec_ctx, custom_reason)parts = [attribution_for(exec_ctx, escape: true)]custom_reason = custom_reason.to_s.strip- parts << ERB::Util.html_escape(custom_reason) if custom_reason.present?+ parts << custom_reason if custom_reason.present?parts.join("<br>")enddiff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/flag_post_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/flag_post_spec.rbindex 1c8a02e6952..814a739fdce 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/flag_post_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/flag_post_spec.rb@@ -42,20 +42,29 @@ RSpec.describe DiscourseWorkflows::Nodes::FlagPost::V1 do)end- it "appends the configured reason to the moderator-facing score reason, escaping HTML" do+ it "appends the configured Markdown and sanitizes it when rendered" doexecute_node(configuration: {"post_id" => post.id.to_s,"flag_type" => "review",- "reason" => "Contains suspicious <script>alert(1)</script> links",+ "reason" =>+ "Contains **suspicious** links\n\n> quoted evidence\n\n<script>alert(1)</script>",},workflow: workflow,)score = ReviewablePost.pending.find_by(target: post).reviewable_scores.lastexpect(score.reason).to eq(- "#{attribution}<br>Contains suspicious <script>alert(1)</script> links",+ "#{attribution}<br>Contains **suspicious** links\n\n> quoted evidence\n\n<script>alert(1)</script>",)++ serialized = ReviewableScoreSerializer.new(score, scope: moderator.guardian, root: nil)+ expect(serialized.reason).to match_html(<<~HTML)+ <p>#{attribution}<br>Contains <strong>suspicious</strong> links</p>+ <blockquote>+ <p>quoted evidence</p>+ </blockquote>+ HTMLendit "reuses a pending flagged post reviewable instead of creating a second review item",diff --git a/spec/serializers/reviewable_score_serializer_spec.rb b/spec/serializers/reviewable_score_serializer_spec.rbindex 2b64ca87f94..c8c9107a0a7 100644--- a/spec/serializers/reviewable_score_serializer_spec.rb+++ b/spec/serializers/reviewable_score_serializer_spec.rb@@ -63,7 +63,34 @@ RSpec.describe ReviewableScoreSerializer docustom = "completely custom flag reason"serialized = serialized_score(custom)- expect(serialized.reason).to eq(custom)+ expect(serialized.reason).to match_html("<p>#{custom}</p>")+ end++ it "cooks and sanitizes basic Markdown without post-specific transformations" do+ custom = <<~MARKDOWN+ **Details**++ - first+ - second++ first<br>second++ @#{admin.username} :smile:++ <script>alert("unsafe")</script>+ MARKDOWN++ serialized = serialized_score(custom)++ expect(serialized.reason).to match_html(<<~HTML)+ <p><strong>Details</strong></p>+ <ul>+ <li>first</li>+ <li>second</li>+ </ul>+ <p>first<br>second</p>+ <p>@#{admin.username} :smile:</p>+ HTMLendend@@ -99,20 +126,28 @@ RSpec.describe ReviewableScoreSerializer doexpect(queued_reviewable.payload["raw"]).to eq(raw)end- it "HTML-escapes matched words so angle brackets can't break the rendered reason" do+ it "renders matched words containing HTML and Markdown syntax literally" do+ words = [+ "<[email protected]>",+ "[urgent](https://example.com)",+ "**spam**",+ ]score =ReviewableScore.new(reviewable: reviewable,reason: "watched_word",- context: "<[email protected]>,plain",+ context: words.join(","),+ )+ serialized = described_class.new(score, scope: admin.guardian, root: nil)+ reason =+ I18n.t(+ "reviewables.reasons.watched_word",+ link: link,+ words: CGI.escapeHTML(words.join(", ")),+ count: words.length,)- serialized = described_class.new(score, scope: Guardian.new(admin), root: nil)- expect(serialized.reason).to include(- "<[email protected]>",- "plain",- )- expect(serialized.reason).not_to include("<notifications@")+ expect(serialized.reason).to match_html("<p>#{reason}</p>")endit "uses the no-context message if the post has no watched words" do@@ -122,13 +157,10 @@ RSpec.describe ReviewableScoreSerializer doFabricate(:watched_word, action: WatchedWord.actions[:flag], word: "superbad")- expect(score.reason).to eq(- I18n.t(- "reviewables.reasons.no_context.watched_word",- link: link,- default: "watched_word",- ),- )+ reason =+ I18n.t("reviewables.reasons.no_context.watched_word", link:, default: "watched_word")++ expect(score.reason).to match_html("<p>#{reason}</p>")endendend