From 3ad2f7d7233673e1115426f2f4438e933bd7483e Mon Sep 17 00:00:00 2001 From: Selase Krakani <849886+s3lase@users.noreply.github.com> Date: Fri, 13 Jan 2023 01:47:44 +0000 Subject: [PATCH] FIX: Ensure poll extraction is not attempted if post body is absent (#19718) Since the poll post handler runs very early in the post creation process, it's possible to run the handler on an obiviously invalid post. This change ensures the post's `raw` value is present before proceeding. --- plugins/poll/lib/poll.rb | 4 +++ .../spec/requests/posts_controller_spec.rb | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 plugins/poll/spec/requests/posts_controller_spec.rb diff --git a/plugins/poll/lib/poll.rb b/plugins/poll/lib/poll.rb index fa34b0bf22..e29564a7eb 100644 --- a/plugins/poll/lib/poll.rb +++ b/plugins/poll/lib/poll.rb @@ -306,6 +306,10 @@ class DiscoursePoll::Poll end def self.extract(raw, topic_id, user_id = nil) + # Poll Post handlers get called very early in the post + # creation process. `raw` could be nil here. + return [] if raw.blank? + # TODO: we should fix the callback mess so that the cooked version is available # in the validators instead of cooking twice raw = raw.sub(%r{\[quote.+/quote\]}m, "") diff --git a/plugins/poll/spec/requests/posts_controller_spec.rb b/plugins/poll/spec/requests/posts_controller_spec.rb new file mode 100644 index 0000000000..8ec707779e --- /dev/null +++ b/plugins/poll/spec/requests/posts_controller_spec.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require "rails_helper" + +RSpec.describe PostsController do + let(:admin) { Fabricate(:admin) } + + describe "#create" do + it "fails gracefully without a post body" do + key = Fabricate(:api_key).key + + expect do + post "/posts.json", + params: { + title: "this is test body", + }, + headers: { + HTTP_API_USERNAME: admin.username, + HTTP_API_KEY: key, + } + end.not_to change { Topic.count } + + expect(response.status).to eq(422) + end + end +end