A platform for community discussion. Free, open, simple.
DEV: Add CanCreateBoard policy class to board service (#45488)
Martin Brennanf70a51b89d6a
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rbindex 35c14003717..0740a02de5c 100644--- a/app/controllers/application_controller.rb+++ b/app/controllers/application_controller.rb@@ -669,6 +669,7 @@ class ApplicationController < ActionController::Base# type - a machine-readable description of the error# status - HTTP status code to return# headers - extra headers for the response+ # skip_error_prefix - display a single error without the client's generic prefixdef render_json_error(obj, opts = {})opts = { status: opts } if opts.is_a?(Integer)opts.fetch(:headers, {}).each { |name, value| headers[name.to_s] = value }diff --git a/frontend/discourse/app/lib/ajax-error.js b/frontend/discourse/app/lib/ajax-error.jsindex 92ee33e2e7b..c2128b93d04 100644--- a/frontend/discourse/app/lib/ajax-error.js+++ b/frontend/discourse/app/lib/ajax-error.js@@ -65,9 +65,11 @@ export function extractErrorInfo(errors: errors.map((e, i) => `${i + 1}) ${e}`).join(" "),});} else if (errors?.length > 0) {- parsedError = i18n("generic_error_with_reason", {- error: errors[0],- });+ parsedError = parsedJSON.skip_error_prefix+ ? errors[0]+ : i18n("generic_error_with_reason", {+ error: errors[0],+ });} else if (parsedJSON.error) {parsedError = parsedJSON.error;} else if (parsedJSON.message) {diff --git a/frontend/discourse/tests/unit/lib/ajax-error-test.js b/frontend/discourse/tests/unit/lib/ajax-error-test.jsindex bc135e0b275..07eada00bbf 100644--- a/frontend/discourse/tests/unit/lib/ajax-error-test.js+++ b/frontend/discourse/tests/unit/lib/ajax-error-test.js@@ -4,6 +4,7 @@ import sinon from "sinon";import { ajax } from "discourse/lib/ajax";import {extractError,+ extractErrorInfo,isRateLimitError,rateLimitWaitSeconds,} from "discourse/lib/ajax-error";@@ -157,6 +158,39 @@ module("Unit | Lib | ajax-error", function (hooks) {);});+ test("extractErrorInfo skips the prefix when requested by the server", async function (assert) {+ const message = "You've reached the maximum of <strong>1 boards</strong>.";+ pretender.get("/board-limit", () =>+ response(403, {+ errors: [message],+ html_message: true,+ skip_error_prefix: true,+ })+ );++ const error = extractErrorInfo(await ajaxError("/board-limit"));++ assert.strictEqual(+ error.message,+ message,+ "shows the server message directly"+ );+ assert.true(error.html, "preserves HTML rendering");+ });++ test("extractError keeps multiple errors when skipping the prefix", async function (assert) {+ const errors = ["First error", "Second error"];+ pretender.get("/multiple-errors", () =>+ response(422, { errors, skip_error_prefix: true })+ );++ assert.strictEqual(+ extractError(await ajaxError("/multiple-errors")),+ i18n("multiple_errors", { errors: "1) First error 2) Second error" }),+ "keeps all error messages"+ );+ });+test("extractError reads the detail of a JSON:API error object", async function (assert) {pretender.get("/json-api-forbidden", () =>response(403, {diff --git a/lib/json_error.rb b/lib/json_error.rbindex 384efe336b2..3be2fcbb886 100644--- a/lib/json_error.rb+++ b/lib/json_error.rb@@ -8,6 +8,7 @@ module JsonErrorerrors[:error_type] = opts[:type] if opts[:type]errors[:extras] = opts[:extras] if opts[:extras]errors[:html_message] = true if opts[:html_message]+ errors[:skip_error_prefix] = true if opts[:skip_error_prefix]errorsenddiff --git a/plugins/boards/app/controllers/boards/api/boards_controller.rb b/plugins/boards/app/controllers/boards/api/boards_controller.rbindex e3101755d6d..aa203815ad8 100644--- a/plugins/boards/app/controllers/boards/api/boards_controller.rb+++ b/plugins/boards/app/controllers/boards/api/boards_controller.rb@@ -135,7 +135,14 @@ module Boardsservice_params.deep_merge(params: raw, raw_board_params: raw),) do |result|on_success { |board:| render json: { board: serialize_board(board) }, status: :created }- on_failed_policy(:can_manage) { raise Discourse::InvalidAccess }+ on_failed_policy(:can_create_board) do |policy|+ render_json_error(+ policy.reason,+ status: :forbidden,+ html_message: true,+ skip_error_prefix: true,+ )+ endon_failed_contract do |contract|render json: failed_json.merge(errors: contract.errors.full_messages),status: :bad_requestdiff --git a/plugins/boards/app/services/boards/create_board.rb b/plugins/boards/app/services/boards/create_board.rbindex 6f541351832..ac547a39b37 100644--- a/plugins/boards/app/services/boards/create_board.rb+++ b/plugins/boards/app/services/boards/create_board.rb@@ -10,7 +10,7 @@ module Boardsvalidates :name, presence: trueend- policy :can_manage+ policy :can_create_board, class_name: Boards::Policy::CanCreateBoardtransaction domodel :board, :create_board@@ -21,10 +21,6 @@ module Boardsprivate- def can_manage(guardian:)- guardian.can_create_board?- end-def create_board(guardian:)raw = context[:raw_board_params]&.dup || {}if raw.key?("tag_names")diff --git a/plugins/boards/app/services/boards/policy/can_create_board.rb b/plugins/boards/app/services/boards/policy/can_create_board.rbnew file mode 100644index 00000000000..a068d337810--- /dev/null+++ b/plugins/boards/app/services/boards/policy/can_create_board.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class Boards::Policy::CanCreateBoard < Service::PolicyBase+ def call+ guardian.can_create_board?+ end++ def reason+ I18n.t("boards.errors.board_create_forbidden")+ end+enddiff --git a/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-page.gjsindex 551ccf19d16..65f60a4c848 100644--- a/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs+++ b/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs@@ -3,6 +3,8 @@ import { array, hash } from "@ember/helper";import { action } from "@ember/object";import { LinkTo } from "@ember/routing";import { service } from "@ember/service";+import PluginOutlet from "discourse/components/plugin-outlet";+import lazyHash from "discourse/helpers/lazy-hash";import { ajax } from "discourse/lib/ajax";import DAsyncContent from "discourse/ui-kit/d-async-content";import DButton from "discourse/ui-kit/d-button";@@ -85,12 +87,17 @@ export default class BoardsPage extends Component {><:actions as |actions|>{{#if @canManageBoards}}- <actions.Primary- class="btn-primary discourse-boards-manage__new-board"- @action={{this.openNewBoardModal}}- @icon="plus"- @label="boards.manage.new"- />+ <PluginOutlet+ @name="board-new-button"+ @outletArgs={{lazyHash actions=actions}}+ >+ <actions.Primary+ class="btn-primary discourse-boards-manage__new-board"+ @action={{this.openNewBoardModal}}+ @icon="plus"+ @label="boards.manage.new"+ />+ </PluginOutlet>{{/if}}</:actions></DPageHeader>diff --git a/plugins/boards/config/locales/server.en.yml b/plugins/boards/config/locales/server.en.ymlindex ff32915354e..712594a88d4 100644--- a/plugins/boards/config/locales/server.en.yml+++ b/plugins/boards/config/locales/server.en.yml@@ -7,7 +7,7 @@ en:invalid_params: "Could not create board column: %{errors}"failed: "Could not create the board column."create_board:- forbidden: "The workflow execution user does not have permission to create boards."+ forbidden: "Could not create board: %{policy_reason}"invalid_params: "Could not create board: %{errors}"acl_failed: "Could not create the board's access permissions. Check the selected groups and permissions."failed: "Could not create the board."@@ -27,6 +27,7 @@ en:slug_unavailable: "That board slug is already in use. Please choose another slug."board_not_found: "Board not found"board_read_forbidden: "You do not have permission to view this board"+ board_create_forbidden: "You do not have permission to create boards"board_write_forbidden: "You do not have permission to modify this board"board_manage_forbidden: "You do not have permission to manage this board"column_not_found: "Column not found"diff --git a/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb b/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rbindex 8a2d371a6b1..d5ec303f487 100644--- a/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb+++ b/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb@@ -93,8 +93,13 @@ if defined?(DiscourseWorkflows)"unicode_name" => board.unicode_name,}end- on_failed_policy(:can_manage) do- raise_node_error!(I18n.t("discourse_workflows.errors.create_board.forbidden"))+ on_failed_policy(:can_create_board) do |policy|+ raise_node_error!(+ I18n.t(+ "discourse_workflows.errors.create_board.forbidden",+ policy_reason: policy.reason,+ ),+ )endon_failed_contract do |contract|invalid_parameters!(contract.errors.full_messages.join(", "))diff --git a/plugins/boards/spec/lib/discourse_workflows/nodes/create_board/v1_spec.rb b/plugins/boards/spec/lib/discourse_workflows/nodes/create_board/v1_spec.rbindex 5a5f4654f8d..6574262ca15 100644--- a/plugins/boards/spec/lib/discourse_workflows/nodes/create_board/v1_spec.rb+++ b/plugins/boards/spec/lib/discourse_workflows/nodes/create_board/v1_spec.rb@@ -211,7 +211,10 @@ RSpec.describe DiscourseWorkflows::Nodes::CreateBoard::V1 doexecute_node(configuration.merge("actor_username" => user.username))}.to raise_error(DiscourseWorkflows::NodeError,- I18n.t("discourse_workflows.errors.create_board.forbidden"),+ I18n.t(+ "discourse_workflows.errors.create_board.forbidden",+ policy_reason: I18n.t("boards.errors.board_create_forbidden"),+ ),)end.not_to change { Boards::Board.count }enddiff --git a/plugins/boards/spec/requests/boards/boards_controller_spec.rb b/plugins/boards/spec/requests/boards/boards_controller_spec.rbindex 2b879f257c2..42bca424e58 100644--- a/plugins/boards/spec/requests/boards/boards_controller_spec.rb+++ b/plugins/boards/spec/requests/boards/boards_controller_spec.rb@@ -739,6 +739,22 @@ RSpec.describe Boards::Api::BoardsController dopost "/boards/api/boards.json", params: { board: { name: "Nope", slug: "nope" } }expect(response.status).to eq(403)+ expect(response.parsed_body["errors"]).to eq([I18n.t("boards.errors.board_create_forbidden")])+ end++ it "returns the creation policy's custom failure reason" do+ sign_in(manager)+ reason = "The account has reached its board limit."+ Boards::Policy::CanCreateBoard.any_instance.stubs(:call).returns(false)+ Boards::Policy::CanCreateBoard.any_instance.stubs(:reason).returns(reason)++ expect do+ post "/boards/api/boards.json", params: { board: { name: "Nope", slug: "nope" } }+ end.not_to change { Boards::Board.count }++ expect(response.status).to eq(403)+ expect(response.parsed_body["errors"]).to eq([reason])+ expect(response.parsed_body["skip_error_prefix"]).to eq(true)endenddiff --git a/plugins/boards/spec/services/boards/create_board_spec.rb b/plugins/boards/spec/services/boards/create_board_spec.rbindex 582e9fd1064..bfafda2a3bf 100644--- a/plugins/boards/spec/services/boards/create_board_spec.rb+++ b/plugins/boards/spec/services/boards/create_board_spec.rb@@ -28,10 +28,16 @@ RSpec.describe Boards::CreateBoard doit { is_expected.to fail_a_contract }end- context "when user cannot manage boards" do+ context "when user cannot create boards" dolet(:dependencies) { { guardian: outsider.guardian } }- it { is_expected.to fail_a_policy(:can_manage) }+ it "fails the creation policy without creating a board" do+ expect { result }.not_to change { Boards::Board.count }+ expect(result).to fail_a_policy(:can_create_board)+ expect(result["result.policy.can_create_board"].reason).to eq(+ I18n.t("boards.errors.board_create_forbidden"),+ )+ endendcontext "when everything is valid" dodiff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjsindex 796e8a252ac..a261edd8c7e 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs@@ -5,6 +5,7 @@ import { action } from "@ember/object";import didInsert from "@ember/render-modifiers/modifiers/did-insert";import didUpdate from "@ember/render-modifiers/modifiers/did-update";import { service } from "@ember/service";+import { trustHTML } from "@ember/template";import { ajax } from "discourse/lib/ajax";import DButton from "discourse/ui-kit/d-button";import DFlashMessage from "discourse/ui-kit/d-flash-message";@@ -678,7 +679,11 @@ export default class ExecutionDetail extends Component {{{#if (stepSummary step)}}<div class="workflows-execution-detail__step-summary">- {{stepSummary step}}+ {{#if step.error_html}}+ {{trustHTML step.error_html}}+ {{else}}+ {{stepSummary step}}+ {{/if}}</div>{{/if}}diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rbindex 035130e8716..d1a4cfb8772 100644--- a/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rb+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rb@@ -40,6 +40,7 @@ module DiscourseWorkflowsinputoutputerror+ error_htmlmetadatastarted_atfinished_atdiff --git a/plugins/discourse-workflows/lib/discourse_workflows/execution_progress_publisher.rb b/plugins/discourse-workflows/lib/discourse_workflows/execution_progress_publisher.rbindex c82f84ab230..5ef1dfb7e29 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/execution_progress_publisher.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/execution_progress_publisher.rb@@ -13,6 +13,7 @@ module DiscourseWorkflowspositionstatuserror+ error_htmlstarted_atfinished_at].freeze@@ -48,7 +49,10 @@ module DiscourseWorkflowsexecution: execution_progress(execution),refresh: refresh,}- payload[:step] = step.to_h.slice(*STEP_FIELDS).merge("error" => step.error) if step+ payload[:step] = step+ .to_h+ .slice(*STEP_FIELDS)+ .merge("error" => step.error, "error_html" => step.error_html) if stepMessageBus.publish(execution_channel(execution.id), payload, **publish_options)publish_list_update(execution) unless stepdiff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rbindex f31de1a1c1d..d135a539e6a 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb@@ -186,7 +186,7 @@ module DiscourseWorkflowsclear_waiting!route_downstream(waiting_node, handled_outputs)else- step&.fail!(error.message)+ step&.fail!(error.message, error_html: error.is_a?(NodeError) ? error.html : nil)@store.publish_progress(step:) if stepraise errorend@@ -445,7 +445,7 @@ module DiscourseWorkflowsattach_step_log(step, collect_step_log(exec_ctx, resolver))end- step.fail!(e.message) unless step.error?+ step.fail!(e.message, error_html: e.is_a?(NodeError) ? e.html : nil) unless step.error?raiseensureresolver&.disposediff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/step.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/step.rbindex 1efa20b1618..c82bb7edd1a 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/step.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/step.rb@@ -19,6 +19,7 @@ module DiscourseWorkflows:started_at,:output,:error,+ :error_html,:finished_atattr_accessor :metadata@@ -31,6 +32,7 @@ module DiscourseWorkflowsstatus: RUNNING,output: nil,error: nil,+ error_html: nil,started_at: nil,finished_at: nil,metadata: nil@@ -43,6 +45,7 @@ module DiscourseWorkflows@status = status@output = output@error = error+ @error_html = error_html@started_at = started_at || Time.current.iso8601(3)@finished_at = finished_at || (status != RUNNING ? @started_at : nil)@metadata = metadata@@ -67,9 +70,10 @@ module DiscourseWorkflows@finished_at = Time.current.iso8601(3)end- def fail!(message)+ def fail!(message, error_html: nil)@status = ERROR@error = message+ @error_html = error_html@finished_at = Time.current.iso8601(3)end@@ -89,6 +93,8 @@ module DiscourseWorkflows@output = updates["output"] if updates.key?("output")@finished_at = updates["finished_at"] if updates.key?("finished_at")@error = updates["error"] if updates.key?("error")+ @error_html = nil if updates.key?("error")+ @error_html = updates["error_html"] if updates.key?("error_html")enddef add_metadata(key, value)@@ -109,6 +115,7 @@ module DiscourseWorkflowsh["output"] = output if outputh["finished_at"] = finished_at if finished_ath["error"] = error if error+ h["error_html"] = error_html if error_htmlh["metadata"] = metadata if metadatahend@@ -123,6 +130,7 @@ module DiscourseWorkflowsstatus: hash["status"] || RUNNING,output: hash["output"],error: hash["error"],+ error_html: hash["error_html"],started_at: hash["started_at"],finished_at: hash["finished_at"],metadata: hash["metadata"],diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_error.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_error.rbindex d0f4ab50b28..f2ed029177d 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/node_error.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_error.rb@@ -2,9 +2,24 @@module DiscourseWorkflowsclass NodeError < StandardError- def initialize(message = nil, summary: nil)+ HTML_SANITIZE_CONFIG = {+ elements: %w[a br code em strong],+ attributes: {+ "a" => %w[href title],+ },+ protocols: {+ "a" => {+ "href" => ["http", "https", :relative],+ },+ },+ }.freeze++ attr_reader :html++ def initialize(message = nil, summary: nil, html: nil)super(message)@summary = summary+ @html = Sanitize.fragment(html.to_s, HTML_SANITIZE_CONFIG).presence if htmlend# The message without its item or line location, so per-item failures can be grouped.diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_error_handling.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_error_handling.rbindex 375e075ff4b..b682ef1ae20 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/node_error_handling.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_error_handling.rb@@ -4,7 +4,9 @@ module DiscourseWorkflowsmodule NodeErrorHandlingprivate- def raise_node_error!(message, description: nil, item_index: nil, line_number: nil)+ # html is an optional full-message replacement, sanitized by NodeError. Keep a plain-text+ # message for logs, exports, and per-item or continued errors; escape dynamic HTML values.+ def raise_node_error!(message, description: nil, item_index: nil, line_number: nil, html: nil)suffix = +""suffix << " [line #{line_number}" if line_numbersuffix << (line_number ? ", for item #{item_index}" : " [item #{item_index}") if item_index@@ -15,6 +17,7 @@ module DiscourseWorkflowsraise DiscourseWorkflows::NodeError.new("#{message}#{suffix}#{details}",summary: "#{message}#{details}",+ html: html,)endenddiff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_spec.rbindex ddd15c555a2..3683cee6f7f 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_spec.rb@@ -95,6 +95,24 @@ RSpec.describe DiscourseWorkflows::Executor::Step doexpect(step.finished_at).to be_presentend+ it "preserves rich errors through storage and clears them on a plain failure" do+ step.fail!("Failure", error_html: "<strong>Failure</strong>")++ restored = described_class.from_h(step.to_h)+ expect(restored.error).to eq("Failure")+ expect(restored.error_html).to eq("<strong>Failure</strong>")++ restored.fail!("Another failure")+ expect(restored.to_h).not_to have_key("error_html")+ end++ it "clears rich errors when an error is cleared" do+ step.fail!("Failure", error_html: "<strong>Failure</strong>")+ step.apply_updates!("error" => nil)++ expect(step.error_html).to be_nil+ end+it "#mark_waiting! transitions to waiting without finishing" dostep.mark_waiting!diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rbindex 76988cf6daa..88eafde8e63 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb@@ -465,6 +465,54 @@ RSpec.describe DiscourseWorkflows::Executor doexpect(run_data.dig(set_fields_step["node_name"], 0, "inputs", 0, "item_count")).to eq(1)end+ context "with a rich node error" do+ let(:node_class) do+ Class.new(DiscourseWorkflows::NodeType) do+ description(name: "action:rich_error_test", version: "1.0")++ def execute(exec_ctx)+ raise_node_error!("Failure", html: '<strong onclick="alert(1)">Failure</strong>')+ end+ end+ end++ before do+ DiscoursePluginRegistry.register_discourse_workflows_node(node_class, Plugin::Instance.new)+ DiscourseWorkflows::Registry.reset_indexes!+ end++ after { unregister_workflow_nodes(node_class) }++ it "stores and publishes sanitized HTML alongside the plain error" do+ graph =+ build_workflow_graph do |g|+ g.node "trigger-1", "trigger:topic_closed"+ g.node "action-1", "action:rich_error_test"+ g.chain "trigger-1", "action-1"+ end+ workflow =+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)+ execution = nil++ messages =+ MessageBus.track_publish do+ execution = described_class.new(workflow, "trigger-1", { topic_id: topic.id }).run+ end++ expect(execution.reload.status).to eq("error")+ expect(execution.error).to eq("Failure")+ step = execution.execution_data.find_step(node_id: "action-1")+ expect(step).to include("error" => "Failure", "error_html" => "<strong>Failure</strong>")+ expect(messages.filter_map { |message| message.data[:step] }).to include(+ include("error" => "Failure", "error_html" => "<strong>Failure</strong>"),+ )+ serialized = DiscourseWorkflows::ExecutionSerializer.new(execution, root: false).as_json+ expect(serialized[:steps]).to include(+ include(error: "Failure", error_html: "<strong>Failure</strong>"),+ )+ end+ end+it "fails the step when expression errors are logged" dograph =build_workflow_graph do |g|diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_error_handling_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_error_handling_spec.rbindex 586bec29882..c3b9b4f07e3 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_error_handling_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_error_handling_spec.rb@@ -17,4 +17,46 @@ RSpec.describe DiscourseWorkflows::NodeErrorHandling doexpect(error.summary).to eq("Boom: details")}end++ it "sanitizes explicitly rich errors without changing their plain message or summary" do+ html =+ '<strong onclick="alert(1)">Failure</strong><br><em>Try</em> <code>again</code>' \+ '<a href="/admin" title="Settings" target="_blank">Settings</a>' \+ '<a href="https://example.com">Help</a><a href="http://example.com">Docs</a>' \+ '<a href="javascript:alert(1)">Unsafe</a><a href="data:text/html,evil">Data</a>' \+ '<img src="x" onerror="alert(1)"><script>alert(1)</script><style>body { color: red }</style>'++ expect {+ handler.send(:raise_node_error!, "Failure", description: "Try again", item_index: 2, html:)+ }.to raise_error(DiscourseWorkflows::NodeError) { |error|+ expect(error.message).to eq("Failure [item 2]: Try again")+ expect(error.summary).to eq("Failure: Try again")+ expect(error.html).to eq(+ "<strong>Failure</strong><br><em>Try</em> <code>again</code>" \+ '<a href="/admin" title="Settings">Settings</a>' \+ '<a href="https://example.com">Help</a><a href="http://example.com">Docs</a>' \+ "<a>Unsafe</a><a>Data</a>",+ )+ }+ end++ it "keeps ordinary error markup as plain text" do+ body = '<img src="x" onerror="alert(1)">'++ expect {+ handler.send(:raise_node_error!, "HTTP request failed", description: body)+ }.to raise_error(DiscourseWorkflows::NodeError) { |error|+ expect(error.message).to eq("HTTP request failed: #{body}")+ expect(error.html).to be_nil+ }+ end++ it "falls back to plain text when sanitization removes all HTML content" do+ expect {+ handler.send(:raise_node_error!, "Failure", html: '<img src="x" onerror="alert(1)">')+ }.to raise_error(DiscourseWorkflows::NodeError) { |error|+ expect(error.message).to eq("Failure")+ expect(error.html).to be_nil+ }+ endenddiff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request_spec.rbindex 84970c8a54d..69dfc6e1a4a 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request_spec.rb@@ -155,6 +155,19 @@ RSpec.describe DiscourseWorkflows::Nodes::HttpRequest::V1 do)end+ it "keeps HTML response bodies in the plain error only" do+ body = '<img src="x" onerror="alert(1)"><strong>Not found</strong>'+ stub_request(:get, "https://api.example.com/fail").to_return(status: 404, body:)+ config = { "method" => "GET", "url" => "https://api.example.com/fail" }++ expect { execute_node(configuration: config, item:) }.to raise_error(+ DiscourseWorkflows::NodeError,+ ) do |error|+ expect(error.message).to end_with(": #{body}")+ expect(error.html).to be_nil+ end+ end+it "raises an error for server errors" dostub_request(:post, "https://api.example.com/error").to_return(status: 500,diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjsindex 55dc1c4f659..1ae1ad07551 100644--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs@@ -151,6 +151,47 @@ module(.hasText("{}", "the empty item remains distinguishable from no items");});+ test("escapes ordinary step errors", async function (assert) {+ this.execution = executionWithOutput([]);+ const error =+ '<img src="x" onerror="alert(1)"><strong>HTTP failure</strong>';+ Object.assign(this.execution.steps[0], { status: "error", error });++ await render(+ <template><ExecutionDetail @execution={{this.execution}} /></template>+ );++ assert+ .dom(".workflows-execution-detail__step-summary")+ .hasText(error, "the response body remains literal text");+ assert+ .dom(+ ".workflows-execution-detail__step-summary img, .workflows-execution-detail__step-summary strong"+ )+ .doesNotExist("ordinary errors cannot inject markup");+ });++ test("renders explicitly rich step errors", async function (assert) {+ this.execution = executionWithOutput([]);+ Object.assign(this.execution.steps[0], {+ status: "error",+ error: "Failure: See settings",+ error_html:+ '<strong>Failure</strong>: <a href="/admin">See settings</a>',+ });++ await render(+ <template><ExecutionDetail @execution={{this.execution}} /></template>+ );++ assert+ .dom(".workflows-execution-detail__step-summary strong")+ .hasText("Failure", "rich errors preserve emphasis");+ assert+ .dom(".workflows-execution-detail__step-summary a")+ .hasAttribute("href", "/admin", "rich errors preserve links");+ });+test("renders execution hints and handled errors for any node", async function (assert) {this.execution = executionWithOutput([{ json: { value: 1 } }]);this.execution.steps[0].metadata = {@@ -624,6 +665,27 @@ module(assert.dom(".workflows-execution-detail__step-section").doesNotExist("input and output are not part of progress messages");++ this.owner.lookup("service:message-bus").publish(+ "/discourse-workflows/execution/11473",+ {+ type: "execution_progress",+ execution: { id: 11473, status: "running" },+ refresh: false,+ step: {+ position: 0,+ status: "error",+ error: "Failure",+ error_html: "<strong>Failure</strong>",+ },+ },+ 42+ );+ await settled();++ assert+ .dom(".workflows-execution-detail__step-summary strong")+ .hasText("Failure", "live updates preserve rich errors");});});diff --git a/spec/lib/json_error_spec.rb b/spec/lib/json_error_spec.rbindex f47527ef1d2..872cffde988 100644--- a/spec/lib/json_error_spec.rb+++ b/spec/lib/json_error_spec.rb@@ -37,6 +37,13 @@ RSpec.describe JsonError doit "returns the string in the error format" doexpect(creator.create_errors_json("test error")).to eq(errors: ["test error"])end++ it "preserves the errors array when skipping the client error prefix" do+ expect(creator.create_errors_json("test error", skip_error_prefix: true)).to eq(+ errors: ["test error"],+ skip_error_prefix: true,+ )+ endenddescribe "an activerecord object with errors" do