Skip to content

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

175 KB
Raw Blame
# frozen_string_literal: true

RSpec.shared_examples "finding and showing post" do
  let!(:post) { post_by_user }

  it "ensures the user can't see the post" do
    topic = post.topic
    topic.convert_to_private_message(Discourse.system_user)
    topic.remove_allowed_user(Discourse.system_user, user.username)
    get url
    expect(response.status).to eq(404)
  end

  it "returns 200 for an accessible post" do
    get url
    expect(response.status).to eq(200)
  end

  it "returns 404 when post's topic is deleted" do
    post.topic.destroy!
    get url
    expect(response.status).to eq(404)
  end

  context "with deleted post" do
    before { post.trash!(user) }

    it "can't find deleted posts as an anonymous user" do
      get url
      expect(response.status).to eq(404)
    end

    it "can't find deleted posts as a regular user" do
      sign_in(user)
      get url
      expect(response.status).to eq(404)
    end

    it "can find posts as a moderator" do
      sign_in(moderator)
      get url
      expect(response.status).to eq(200)
    end

    it "can find posts as a admin" do
      sign_in(admin)
      get url
      expect(response.status).to eq(200)
    end

    context "with category group moderator" do
      fab!(:group_user)
      let(:user_gm) { group_user.user }
      let(:group) { group_user.group }

      before do
        SiteSetting.enable_category_group_moderation = true
        sign_in(user_gm)
      end

      it "can find posts in the allowed category" do
        post.topic.category.update!(topic_id: topic.id)
        Fabricate(:category_moderation_group, category: post.topic.category, group:)
        get url
        expect(response.status).to eq(200)
      end

      it "can't find posts outside of the allowed category" do
        get url
        expect(response.status).to eq(404)
      end
    end
  end
end

RSpec.shared_examples "action requires login" do |method, url, params = {}|
  it "raises an exception when not logged in" do
    public_send(method, url, **params)
    expect(response.status).to eq(403)
  end
end

RSpec.describe PostsController do
  fab!(:admin)
  fab!(:moderator) { Fabricate(:moderator, refresh_auto_groups: true) }
  fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
  fab!(:user_trust_level_0, :trust_level_0)
  fab!(:user_trust_level_1, :trust_level_1)
  fab!(:category)
  fab!(:topic)
  fab!(:post_by_user) { Fabricate(:post, user: user) }
  let(:public_post) { Fabricate(:post, user: user, topic: topic) }
  let(:topicless_post) { Fabricate(:post, user: user, raw: "<p>Car 54, where are you?</p>") }

  let(:private_topic) { Fabricate(:topic, archetype: Archetype.private_message, category_id: nil) }
  let(:private_post) { Fabricate(:post, user: user, topic: private_topic) }

  describe "#show" do
    include_examples "finding and showing post" do
      let(:url) { "/posts/#{post.id}.json" }
    end

    it "does not reveal private post existence to anonymous users" do
      get "/posts/#{private_post.id}.json"

      expect(response.status).to eq(404)
      expect(response.body).not_to include(private_post.raw)

      get "/posts/#{Post.maximum(:id) + 1}.json"

      expect(response.status).to eq(404)
    end

    it "gets all the expected fields" do
      # non fabricated test
      new_post = create_post

      get "/posts/#{new_post.id}.json"
      parsed = response.parsed_body

      expect(parsed["topic_slug"]).to eq(new_post.topic.slug)
      expect(parsed["moderator"]).to eq(false)
      expect(parsed["username"]).to eq(new_post.user.username)
      expect(parsed["cooked"]).to eq(new_post.cooked)
    end

    it "localizes posts from Accept-Language for clients classified as crawlers" do
      SiteSetting.allow_user_locale = true
      SiteSetting.set_locale_from_param = true
      SiteSetting.set_locale_from_accept_language_header = true
      SiteSetting.content_localization_enabled = true
      SiteSetting.content_localization_crawler_param = true
      SiteSetting.content_localization_supported_locales = "ja"
      localized_post = Fabricate(:post, raw: "Original post body", locale: "en")
      Fabricate(:post_localization, post: localized_post, locale: "ja", cooked: "<p>翻訳された本文</p>")

      get "/posts/#{localized_post.id}",
          headers: {
            "HTTP_USER_AGENT" => "curl/8.0",
            "HTTP_ACCEPT" => "*/*",
            "HTTP_ACCEPT_LANGUAGE" => "ja",
          }

      expect(response.status).to eq(200)
      expect(response.parsed_body["cooked"]).to eq("<p>翻訳された本文</p>")
    end

    context "with version parameter" do
      let(:post_with_revisions) { Fabricate(:post, user: user, version: 2) }
      let(:post_revision) { Fabricate(:post_revision, post: post_with_revisions) }

      it "returns the reverted content for a visible revision" do
        post_revision
        sign_in(user)
        get "/posts/#{post_with_revisions.id}.json?version=1"
        expect(response.status).to eq(200)
        expect(response.parsed_body["cooked"]).to eq("<p>BEFORE</p>")
      end

      it "rejects a version restored from a hidden revision" do
        hidden_raw = "hidden moderator-redacted secret"
        hidden_cooked = "<p>#{hidden_raw}</p>"
        post_with_hidden_revision =
          Fabricate(:post, user: user, version: 3, raw: "public current version")
        Fabricate(
          :post_revision,
          post: post_with_hidden_revision,
          number: 2,
          hidden: true,
          modifications: {
            "cooked" => ["<p>public first version</p>", hidden_cooked],
            "raw" => ["public first version", hidden_raw],
          },
        )
        Fabricate(
          :post_revision,
          post: post_with_hidden_revision,
          number: 3,
          modifications: {
            "cooked" => [hidden_cooked, "<p>public current version</p>"],
            "raw" => [hidden_raw, "public current version"],
          },
        )

        get "/posts/#{post_with_hidden_revision.id}.json", params: { version: 2 }

        aggregate_failures do
          expect(response).to be_forbidden
          expect(response.body).not_to include(hidden_raw)
        end
      end

      context "when the revision is hidden" do
        before { post_revision.update!(hidden: true) }

        it "rejects access for a regular user" do
          sign_in(user)
          get "/posts/#{post_with_revisions.id}.json?version=1"
          expect(response).to be_forbidden
        end

        it "rejects access for an anonymous user" do
          get "/posts/#{post_with_revisions.id}.json?version=1"
          expect(response).to be_forbidden
        end

        it "rejects access for a category group moderator" do
          SiteSetting.enable_category_group_moderation = true
          group = Fabricate(:group)
          category_moderator = Fabricate(:user, groups: [group])
          Fabricate(
            :category_moderation_group,
            category: post_with_revisions.topic.category,
            group:,
          )

          sign_in(category_moderator)
          get "/posts/#{post_with_revisions.id}.json?version=1"
          expect(response).to be_forbidden
        end

        it "allows access for staff" do
          sign_in(admin)
          get "/posts/#{post_with_revisions.id}.json?version=1"
          expect(response.status).to eq(200)
          expect(response.parsed_body["cooked"]).to eq("<p>BEFORE</p>")
        end
      end

      context "when edit history is not visible to the public" do
        before { SiteSetting.edit_history_visible_to_public = false }

        it "rejects access for an anonymous user" do
          post_revision
          get "/posts/#{post_with_revisions.id}.json?version=1"
          expect(response).to be_forbidden
        end

        it "rejects access for a regular user who is not the poster" do
          other_user = Fabricate(:user)
          sign_in(other_user)
          post_revision
          get "/posts/#{post_with_revisions.id}.json?version=1"
          expect(response).to be_forbidden
        end

        it "allows access for staff" do
          post_revision
          sign_in(admin)
          get "/posts/#{post_with_revisions.id}.json?version=1"
          expect(response.status).to eq(200)
        end
      end
    end
  end

  describe "#by_number" do
    include_examples "finding and showing post" do
      let(:url) { "/posts/by_number/#{post.topic_id}/#{post.post_number}.json" }
    end
  end

  describe "whisper visibility" do
    it "blocks removed whisperers from their own whisper", :aggregate_failures do
      whisper_group = Fabricate(:group)
      whisper_author = Fabricate(:user, trust_level: TrustLevel[1])
      topic = Fabricate(:topic)
      Fabricate(:post, topic: topic)
      original_raw = "staff-only whisper body"
      edited_raw = "edited whisper body"
      whisper =
        Fabricate(
          :post,
          topic: topic,
          user: whisper_author,
          post_type: Post.types[:whisper],
          raw: original_raw,
        )

      SiteSetting.whispers_allowed_groups = whisper_group.id.to_s
      whisper_group.add(whisper_author)
      whisper_group.remove(whisper_author)
      sign_in(User.find(whisper_author.id))

      get "/posts/#{whisper.id}.json"
      expect(response.status).to eq(404)
      expect(response.body).not_to include(whisper.raw)

      get "/posts/by_number/#{topic.id}/#{whisper.post_number}.json"
      expect(response.status).to eq(404)
      expect(response.body).not_to include(whisper.raw)

      get "/raw/#{topic.id}/#{whisper.post_number}"
      expect(response.status).to eq(404)
      expect(response.body).not_to include(whisper.raw)

      put "/posts/#{whisper.id}.json", params: { post: { raw: edited_raw } }
      expect(response).to be_forbidden
      expect(response.body).not_to include(edited_raw)
      expect(whisper.reload.raw).to eq(original_raw)
    end
  end

  describe "#by_date" do
    include_examples "finding and showing post" do
      let(:url) { "/posts/by-date/#{post.topic_id}/#{post.created_at.strftime("%Y-%m-%d")}.json" }
    end

    it "returns the expected post" do
      first_post = Fabricate(:post, created_at: 10.days.ago)
      second_post = Fabricate(:post, topic: first_post.topic, created_at: 4.days.ago)
      _third_post = Fabricate(:post, topic: first_post.topic, created_at: 3.days.ago)

      get "/posts/by-date/#{second_post.topic_id}/#{(second_post.created_at - 2.days).strftime("%Y-%m-%d")}.json"
      json = response.parsed_body

      expect(response.status).to eq(200)
      expect(json["id"]).to eq(second_post.id)
    end

    it "returns no post if date is > at last created post" do
      get "/posts/by-date/#{post.topic_id}/2245-11-11.json"
      _json = response.parsed_body
      expect(response.status).to eq(404)
    end
  end

  describe "#reply_history" do
    include_examples "finding and showing post" do
      let(:url) { "/posts/#{post.id}/reply-history.json" }
    end

    it "returns the replies with allowlisted user custom fields" do
      parent = Fabricate(:post)
      child = Fabricate(:post, topic: parent.topic, reply_to_post_number: parent.post_number)

      parent.user.upsert_custom_fields(hello: "world", hidden: "dontshow")
      SiteSetting.public_user_custom_fields = "hello"

      get "/posts/#{child.id}/reply-history.json"
      expect(response.status).to eq(200)

      json = response.parsed_body
      expect(json[0]["id"]).to eq(parent.id)
      expect(json[0]["user_custom_fields"]["hello"]).to eq("world")
      expect(json[0]["user_custom_fields"]["hidden"]).to be_blank
    end
  end

  describe "#reply_ids" do
    include_examples "finding and showing post" do
      let(:url) { "/posts/#{post.id}/reply-ids.json" }
    end

    it "returns ids of post's replies" do
      post = Fabricate(:post)
      reply1 = Fabricate(:post, topic: post.topic, reply_to_post_number: post.post_number)
      reply2 = Fabricate(:post, topic: post.topic, reply_to_post_number: post.post_number)
      PostReply.create(post_id: post.id, reply_post_id: reply1.id)
      PostReply.create(post_id: post.id, reply_post_id: reply2.id)

      get "/posts/#{post.id}/reply-ids.json"

      expect(response.status).to eq(200)
      expect(response.parsed_body).to eq(
        [{ "id" => reply1.id, "level" => 1 }, { "id" => reply2.id, "level" => 1 }],
      )
    end
  end

  describe "#replies" do
    include_examples "finding and showing post" do
      let(:url) { "/posts/#{post.id}/replies.json" }
    end

    it "asks post for replies" do
      parent = Fabricate(:post)
      child = Fabricate(:post, topic: parent.topic, reply_to_post_number: parent.post_number)
      PostReply.create!(post: parent, reply: child)

      child.user.upsert_custom_fields(hello: "world", hidden: "dontshow")
      SiteSetting.public_user_custom_fields = "hello"

      get "/posts/#{parent.id}/replies.json"
      expect(response.status).to eq(200)

      json = response.parsed_body
      expect(json[0]["id"]).to eq(child.id)
      expect(json[0]["user_custom_fields"]["hello"]).to eq("world")
      expect(json[0]["user_custom_fields"]["hidden"]).to be_blank
    end

    it "supports pagination" do
      parent = Fabricate(:post)

      child_posts = []

      30.times do
        reply = Fabricate(:post, topic: parent.topic, reply_to_post_number: parent.post_number)
        PostReply.create!(post: parent, reply:)
        child_posts << reply
      end

      get "/posts/#{parent.id}/replies.json", params: { after: parent.post_number }
      expect(response.status).to eq(200)
      replies = response.parsed_body

      expect(replies.map { |reply| reply["id"] }).to eq(child_posts[0..19].map(&:id))

      after = replies.last["post_number"]

      get "/posts/#{parent.id}/replies.json", params: { after: }
      expect(response.status).to eq(200)
      replies = response.parsed_body

      expect(replies.map { |reply| reply["id"] }).to eq(child_posts[20..-1].map(&:id))
      expect(replies[0][:post_number]).to eq(after + 1)

      get "/posts/#{parent.id}/replies.json", params: { after: 999_999 }

      expect(response.status).to eq(200)
      expect(response.parsed_body.size).to eq(0)
    end
  end

  describe "#destroy" do
    include_examples "action requires login", :delete, "/posts/123.json"

    describe "when logged in" do
      let(:topic) { Fabricate(:topic) }

      it "raises an error when the user doesn't have permission to see the post" do
        pm = Fabricate(:private_message_topic)
        post = Fabricate(:post, topic: pm, post_number: 3)

        sign_in(user)

        delete "/posts/#{post.id}.json"
        expect(response.status).to eq(404)
      end

      it "raises an error when the self deletions are disabled" do
        SiteSetting.max_post_deletions_per_day = 0
        post = Fabricate(:post, user: user, topic: topic, post_number: 3)
        sign_in(user)

        delete "/posts/#{post.id}.json"
        expect(response).to be_forbidden
      end

      it "deletes another user's post for a member of delete_all_posts_and_topics_allowed_groups" do
        group = Fabricate(:group)
        group.add(user)
        SiteSetting.delete_all_posts_and_topics_allowed_groups = "1|2|#{group.id}"
        post = Fabricate(:post, topic: topic, post_number: 3)
        sign_in(user)

        delete "/posts/#{post.id}.json"

        expect(response.status).to eq(200)
        expect(post.reload.deleted_at).to be_present
      end

      it "uses a PostDestroyer" do
        post = Fabricate(:post, topic_id: topic.id, post_number: 3)
        sign_in(moderator)

        destroyer = mock
        PostDestroyer.expects(:new).returns(destroyer)
        destroyer.expects(:destroy)

        delete "/posts/#{post.id}.json"
      end

      context "with permanently destroy" do
        let!(:post) { Fabricate(:post, topic_id: topic.id, post_number: 3) }

        before { SiteSetting.can_permanently_delete = true }

        it "does not work for a post that was not deleted yet" do
          sign_in(admin)

          delete "/posts/#{post.id}.json", params: { force_destroy: true }
          expect(response.status).to eq(403)
        end

        it "needs some time to pass to permanently delete a topic" do
          sign_in(admin)

          delete "/posts/#{post.id}.json"
          expect(response.status).to eq(200)
          expect(post.reload.deleted_by_id).to eq(admin.id)

          delete "/posts/#{post.id}.json", params: { force_destroy: true }
          expect(response.status).to eq(403)

          post.update!(deleted_at: 10.minutes.ago)

          delete "/posts/#{post.id}.json", params: { force_destroy: true }
          expect(response.status).to eq(200)
          expect { post.reload }.to raise_error(ActiveRecord::RecordNotFound)
        end

        it "needs two users to permanently delete a topic" do
          sign_in(admin)

          delete "/posts/#{post.id}.json"
          expect(response.status).to eq(200)
          expect(post.reload.deleted_by_id).to eq(admin.id)

          sign_in(Fabricate(:admin))

          delete "/posts/#{post.id}.json", params: { force_destroy: true }
          expect(response.status).to eq(200)
          expect { post.reload }.to raise_error(ActiveRecord::RecordNotFound)
        end

        it "moderators cannot permanently delete topics" do
          sign_in(admin)

          delete "/posts/#{post.id}.json"
          expect(response.status).to eq(200)
          expect(post.reload.deleted_by_id).to eq(admin.id)

          sign_in(moderator)

          delete "/posts/#{post.id}.json", params: { force_destroy: true }
          expect(response.status).to eq(403)
        end

        it "creates a log and clean up previously recorded sensitive information" do
          sign_in(admin)

          delete "/posts/#{post.id}.json"
          expect(response.status).to eq(200)
          expect(post.reload.deleted_by_id).to eq(admin.id)

          post.update!(deleted_at: 10.minutes.ago)

          delete "/posts/#{post.id}.json", params: { force_destroy: true }
          expect(response.status).to eq(200)

          expect(UserHistory.last).to have_attributes(
            action: UserHistory.actions[:delete_post_permanently],
            acting_user_id: admin.id,
          )

          expect(UserHistory.where(post_id: post.id, details: "(permanently deleted)").count).to eq(
            2,
          )
        end
      end
    end
  end

  describe "#destroy_many" do
    it_behaves_like "action requires login",
                    :delete,
                    "/posts/destroy_many.json",
                    params: {
                      post_ids: [123, 345],
                    }

    context "when logged in" do
      fab!(:poster, :moderator)
      fab!(:post1) { Fabricate(:post, user: poster, post_number: 1) }
      fab!(:post2) do
        Fabricate(
          :post,
          topic: post1.topic,
          user: poster,
          post_number: 2,
          reply_to_post_number: post1.post_number,
        )
      end

      it "raises invalid parameters no post_ids" do
        sign_in(poster)
        delete "/posts/destroy_many.json"
        expect(response.status).to eq(400)
        expect(response.message.downcase).to eq("bad request")
      end

      it "raises invalid parameters with missing ids" do
        sign_in(poster)
        delete "/posts/destroy_many.json", params: { post_ids: [12_345] }
        expect(response.status).to eq(400)
      end

      it "raises an error when the user doesn't have permission to delete the posts" do
        sign_in(user)
        delete "/posts/destroy_many.json", params: { post_ids: [post1.id, post2.id] }
        expect(response).to be_forbidden
      end

      it "deletes the post" do
        sign_in(poster)
        PostDestroyer.any_instance.expects(:destroy).twice
        delete "/posts/destroy_many.json", params: { post_ids: [post1.id, post2.id] }
        expect(response.status).to eq(200)
      end

      it "deletes the posts for a member of delete_all_posts_and_topics_allowed_groups" do
        group = Fabricate(:group)
        group.add(user)
        SiteSetting.delete_all_posts_and_topics_allowed_groups = "1|2|#{group.id}"
        sign_in(user)

        delete "/posts/destroy_many.json", params: { post_ids: [post1.id, post2.id] }

        expect(response.status).to eq(200)
        expect(post1.reload.deleted_at).to be_present
        expect(post2.reload.deleted_at).to be_present
      end

      # bookmark
      it "triggers DiscourseEvent with :posts_destroyed and correct params" do
        sign_in(poster)
        events =
          DiscourseEvent.track_events do
            delete "/posts/destroy_many.json", params: { post_ids: [post1.id, post2.id] }
          end
        event = events.find { |e| e[:event_name] == :posts_destroyed }
        expect(event).to be_present
        expect(event[:params][0].length).to eq(2)
        expect(event[:params][1]).to eq(poster)
      end

      it "updates the highest read data for the forum" do
        sign_in(poster)
        Topic.expects(:reset_highest).twice
        delete "/posts/destroy_many.json", params: { post_ids: [post1.id, post2.id] }
      end

      context "with replies" do
        fab!(:post_reply) { PostReply.create(post: post1, reply: post2) }

        before { sign_in(poster) }

        it "deletes the post and the reply to it" do
          expect do
            delete "/posts/destroy_many.json",
                   params: {
                     post_ids: [post1.id],
                     reply_post_ids: [post1.id],
                   }
          end.to change { Post.count }.by(-2).and change { Topic.count }.by(-1)
        end
      end

      context "when deleting flagged posts" do
        before do
          sign_in(moderator)
          PostActionCreator.off_topic(moderator, post1)
          PostActionCreator.off_topic(moderator, post2)
          Jobs::SendSystemMessage.clear
        end

        it "defers the child posts by default" do
          expect(ReviewableFlaggedPost.pending.count).to eq(2)
          delete "/posts/destroy_many.json", params: { post_ids: [post1.id, post2.id] }
          expect(Jobs::SendSystemMessage.jobs.size).to eq(1)
          expect(ReviewableFlaggedPost.pending.count).to eq(0)
        end

        it "can defer all posts based on `agree_with_first_reply_flag` param" do
          expect(ReviewableFlaggedPost.pending.count).to eq(2)
          delete "/posts/destroy_many.json",
                 params: {
                   post_ids: [post1.id, post2.id],
                   agree_with_first_reply_flag: false,
                 }
          PostActionCreator.off_topic(moderator, post1)
          PostActionCreator.off_topic(moderator, post2)
          Jobs::SendSystemMessage.clear
        end
      end
    end
  end

  describe "#recover" do
    include_examples "action requires login", :put, "/posts/123/recover.json"

    describe "when logged in" do
      it "raises an error when the user doesn't have permission to see the post" do
        post = Fabricate(:post, topic: Fabricate(:private_message_topic), post_number: 3)
        sign_in(user)

        put "/posts/#{post.id}/recover.json"
        expect(response.status).to eq(404)
      end

      it "raises an error when self deletion/recovery is disabled" do
        SiteSetting.max_post_deletions_per_day = 0
        post = Fabricate(:post, user: user, topic: topic, post_number: 3)
        sign_in(user)

        put "/posts/#{post.id}/recover.json"
        expect(response).to be_forbidden
      end

      it "recovers a post correctly" do
        topic_id = create_post.topic_id
        post = create_post(topic_id: topic_id)
        sign_in(user)

        PostDestroyer.new(user, post).destroy
        put "/posts/#{post.id}/recover.json"
        post.reload
        expect(post.trashed?).to be_falsey
      end
    end
  end

  describe "#update" do
    include_examples "action requires login", :put, "/posts/2.json"

    let!(:post) { post_by_user }
    let(:update_params) do
      {
        post: {
          raw: "edited body",
          edit_reason: "typo",
        },
        image_sizes: {
          "http://image.com/image.jpg" => {
            "width" => 123,
            "height" => 456,
          },
        },
      }
    end

    context "when a trust level 1 user edits a public wiki post" do
      it "does not publish a hidden new user profile onebox" do
        author = Fabricate(:user, trust_level: TrustLevel[3], refresh_auto_groups: true)
        editor = Fabricate(:user, trust_level: TrustLevel[1], refresh_auto_groups: true)
        profile_user = Fabricate(:user, trust_level: TrustLevel[1])
        profile_user.user_stat.update!(post_count: 0)
        profile_user.user_profile.update!(
          bio_raw: "private new user biography",
          location: "private new user location",
          website: "https://private-new-user.example.com",
        )
        wiki_post = create_post(user: author, raw: "public wiki post")
        wiki_post.update!(wiki: true)
        Group[:trust_level_1].add(editor)
        editor.reload
        SiteSetting.edit_wiki_post_allowed_groups = Group::AUTO_GROUPS[:trust_level_1]
        SiteSetting.hide_new_user_profiles = true
        CookedPostProcessor.any_instance.stubs(:get_size).returns([100, 100])
        Jobs.run_immediately!

        sign_in(editor)
        put "/posts/#{wiki_post.id}.json",
            params: {
              post: {
                raw: "#{Discourse.base_url}/u/#{profile_user.username}",
              },
            }

        expect(response.status).to eq(200), response.body

        sign_out
        get "/posts/#{wiki_post.id}.json"

        expect(response.status).to eq(200)
        expect(response.body).not_to include(profile_user.user_profile.bio_raw)
        expect(response.body).not_to include(profile_user.user_profile.location)
        expect(response.body).not_to include(profile_user.user_profile.website)
      end
    end

    context "when a wiki editor changes another user's topic title" do
      fab!(:author) { Fabricate(:user, trust_level: TrustLevel[3], refresh_auto_groups: true) }
      fab!(:editor) { Fabricate(:user, trust_level: TrustLevel[1], refresh_auto_groups: true) }
      fab!(:wiki_post) do
        create_post(
          user: author,
          title: "Original topic title",
          raw: "Original wiki body",
        ).tap { |post| post.update!(wiki: true) }
      end

      before do
        Group[:trust_level_1].add(editor)
        SiteSetting.edit_wiki_post_allowed_groups = Group::AUTO_GROUPS[:trust_level_1]
        sign_in(editor)
      end

      it "prevents title changes while allowing wiki body edits" do
        put "/posts/#{wiki_post.id}.json",
            params: {
              title: "Unauthorized topic title",
              post: {
                raw: "Unauthorized wiki body",
              },
            }

        expect(response).to be_forbidden
        expect(response.parsed_body["errors"]).to be_present
        expect(wiki_post.reload.topic.title).to eq("Original topic title")
        expect(wiki_post.raw).to eq("Original wiki body")

        put "/posts/#{wiki_post.id}.json", params: { post: { raw: "Authorized wiki body" } }

        expect(response.status).to eq(200), response.body
        expect(response.parsed_body.dig("post", "raw")).to eq("Authorized wiki body")
        expect(wiki_post.reload.topic.title).to eq("Original topic title")
      end
    end

    context "with default wiki-edit settings" do
      fab!(:private_group, :group)
      fab!(:author) do
        Fabricate(:user, trust_level: TrustLevel[3], refresh_auto_groups: true).tap do |user|
          private_group.add(user)
        end
      end
      fab!(:editor) { Fabricate(:user, trust_level: TrustLevel[1], refresh_auto_groups: true) }
      fab!(:outsider) { Fabricate(:user, trust_level: TrustLevel[1], refresh_auto_groups: true) }
      fab!(:private_category) { Fabricate(:private_category, group: private_group) }
      fab!(:public_category, :category)
      fab!(:wiki_post) do
        create_post(
          user: author,
          category: private_category,
          title: "Restricted topic title",
          raw: "Restricted wiki body",
        ).tap { |post| post.update!(wiki: true) }
      end

      before do
        private_group.add(editor)
        sign_in(editor)
      end

      it "does not let a trust level 1 wiki editor move another user's restricted topic to a public category" do
        expect(SiteSetting.edit_wiki_post_allowed_groups_map).to include(
          Group::AUTO_GROUPS[:trust_level_1],
        )

        put "/posts/#{wiki_post.id}.json",
            params: {
              post: {
                category_id: public_category.id,
                raw: "Restricted wiki body",
              },
            }

        expect(response).to be_forbidden
        expect(response.parsed_body["errors"]).to be_present
        expect(wiki_post.reload.topic.category_id).to eq(private_category.id)

        sign_in(outsider)
        get "/t/#{wiki_post.topic.id}.json"

        expect(response).to be_not_found
        expect(response.body).not_to include(wiki_post.reload.raw)
      end
    end

    describe "when logged in as a regular user" do
      before { sign_in(user) }

      it "does not allow TL0 or TL1 to update when edit time limit expired" do
        SiteSetting.post_edit_time_limit = 5
        SiteSetting.tl2_post_edit_time_limit = 30

        post = Fabricate(:post, created_at: 10.minutes.ago, user: user)

        user.update_columns(trust_level: 1)

        put "/posts/#{post.id}.json", params: update_params

        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"]).to include(I18n.t("too_late_to_edit"))
      end

      it "does not allow TL2 to update when edit time limit expired" do
        SiteSetting.post_edit_time_limit = 12
        SiteSetting.tl2_post_edit_time_limit = 8

        user.update_columns(trust_level: 2)

        post = Fabricate(:post, created_at: 10.minutes.ago, user: user)

        put "/posts/#{post.id}.json", params: update_params

        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"]).to include(I18n.t("too_late_to_edit"))
      end

      it "passes the image sizes through" do
        Post.any_instance.expects(:image_sizes=)
        put "/posts/#{post.id}.json", params: update_params
      end

      it "passes the edit reason through" do
        put "/posts/#{post.id}.json", params: update_params
        expect(response.status).to eq(200)
        post.reload
        expect(post.edit_reason).to eq("typo")
        expect(post.raw).to eq("edited body")
      end

      it "checks for an edit conflict" do
        update_params[:post][:original_text] = "old body"
        put "/posts/#{post.id}.json", params: update_params

        expect(response.status).to eq(409)
      end

      it "raises an error when the post parameter is missing" do
        update_params.delete(:post)
        put "/posts/#{post.id}.json", params: update_params
        expect(response.status).to eq(400)
        expect(response.message.downcase).to eq("bad request")
      end

      it "raises an error when the user doesn't have permission to see the post" do
        post = Fabricate(:private_message_post, post_number: 3)
        put "/posts/#{post.id}.json", params: update_params
        expect(response).to be_forbidden
      end

      it "raises an error when user is OP but can no longer see the post" do
        post = Fabricate(:private_message_post, user: user)
        post.topic.remove_allowed_user(admin, user)
        put "/posts/#{post.id}.json", params: update_params
        expect(response).to be_forbidden
      end

      it "updates post's raw attribute" do
        put "/posts/#{post.id}.json", params: { post: { raw: "edited body   " } }

        expect(response.status).to eq(200)
        expect(response.parsed_body["post"]["raw"]).to eq("edited body")
        expect(post.reload.raw).to eq("edited body")
      end

      it "extracts links from the new body" do
        param = update_params
        param[:post][:raw] = "I just visited this https://google.com so many cool links"

        put "/posts/#{post.id}.json", params: param

        expect(response.status).to eq(200)
        expect(TopicLink.count).to eq(1)
      end

      it "doesn't allow updating of deleted posts" do
        first_post = post.topic.ordered_posts.first
        PostDestroyer.new(moderator, first_post).destroy

        put "/posts/#{first_post.id}.json", params: update_params
        expect(response).not_to be_successful
      end
    end

    describe "when logged in as staff" do
      before { sign_in(moderator) }

      it "limits edit reasons while allowing staff to edit small action content" do
        small_action = Fabricate(:small_action, user: user)
        oversized_edit_reason = "a" * 1001

        put "/posts/#{small_action.id}.json",
            params: {
              post: {
                raw: "x",
                edit_reason: oversized_edit_reason,
              },
            }

        aggregate_failures do
          expect(response.status).to eq(422)
          expect(response.parsed_body["errors"]).to include(
            "Edit reason is too long (maximum is 1000 characters)",
          )
          expect(small_action.reload.edit_reason).not_to eq(oversized_edit_reason)
        end

        put "/posts/#{small_action.id}.json",
            params: {
              post: {
                raw: "x",
                edit_reason: "a" * 1000,
              },
            }

        expect(response.status).to eq(200), response.body
        expect(response.parsed_body["post"]["raw"]).to eq("x")
        expect(small_action.reload.edit_reason).to eq("a" * 1000)
      end

      it "supports updating posts in deleted topics" do
        first_post = post.topic.ordered_posts.first
        PostDestroyer.new(moderator, first_post).destroy

        put "/posts/#{first_post.id}.json", params: update_params
        expect(response.status).to eq(200)

        post.reload
        expect(post.raw).to eq("edited body")
      end

      it "rolls back post changes when a first-post title edit is invalid" do
        Fabricate(:watched_word, action: WatchedWord.actions[:censor], word: "blockedword")

        first_post = create_post(user:, title: "Original topic title", raw: "Original topic body")
        original_title = first_post.topic.title
        original_raw = first_post.raw

        put "/posts/#{first_post.id}.json",
            params: {
              title: "A blockedword topic title",
              post: {
                raw: "Body from failed title edit",
                edit_reason: "moderator edit",
              },
            }

        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"].join).to include("blockedword")
        expect(first_post.reload.raw).to eq(original_raw)
        expect(first_post.version).to eq(1)
        expect(PostRevision.where(post_id: first_post.id).pluck(:number)).to eq([])

        put "/posts/#{first_post.id}.json",
            params: {
              title: original_title,
              post: {
                raw: "Body from valid title edit",
                edit_reason: "moderator edit",
              },
            }

        expect(response.status).to eq(200)
        expect(first_post.reload.raw).to eq("Body from valid title edit")
        expect(first_post.version).to eq(2)
        expect(PostRevision.where(post_id: first_post.id).pluck(:number)).to eq([2])

        get "/posts/#{first_post.id}/revisions/2.json"

        expect(response.status).to eq(200)
        expect(response.parsed_body["current_revision"]).to eq(2)
      end

      it "does not update the bump date for whispers" do
        created_at = freeze_time 1.day.ago
        post = Fabricate(:post, post_type: Post.types[:whisper], user: user)

        unfreeze_time
        put "/posts/#{post.id}.json", params: update_params

        expect(response.status).to eq(200)
        expect(post.topic.reload.bumped_at).to eq_time(created_at)
      end

      describe "bypass_bump parameter" do
        fab!(:wiki_post) { Fabricate(:post, user:, wiki: true) }

        before { wiki_post.topic.update!(bumped_at: 1.day.ago) }

        it "prevents bumping when bypass_bump=true" do
          expect {
            put "/posts/#{wiki_post.id}.json",
                params: {
                  bypass_bump: true,
                  post: {
                    raw: "updated content",
                  },
                }
          }.not_to change { wiki_post.topic.reload.bumped_at }
          expect(response.status).to eq(200)
        end

        it "accepts bypass_bump nested under post param" do
          expect {
            put "/posts/#{wiki_post.id}.json",
                params: {
                  post: {
                    raw: "updated content",
                    bypass_bump: true,
                  },
                }
          }.not_to change { wiki_post.topic.reload.bumped_at }
          expect(response.status).to eq(200)
        end

        it "respects top-level bypass_bump=false over nested bypass_bump=true" do
          expect {
            put "/posts/#{wiki_post.id}.json",
                params: {
                  bypass_bump: false,
                  post: {
                    raw: "updated content",
                    bypass_bump: true,
                  },
                },
                as: :json
          }.to change { wiki_post.topic.reload.bumped_at }
          expect(response.status).to eq(200)
        end

        it "bumps the topic when bypass_bump is not provided" do
          expect {
            put "/posts/#{wiki_post.id}.json", params: { post: { raw: "updated content" } }
          }.to change { wiki_post.topic.reload.bumped_at }
          expect(response.status).to eq(200)
        end

        context "as TL4 user" do
          fab!(:tl4_user, :trust_level_4)
          before { sign_in(tl4_user) }

          it "prevents bumping when bypass_bump=true" do
            expect {
              put "/posts/#{wiki_post.id}.json",
                  params: {
                    bypass_bump: true,
                    post: {
                      raw: "updated content",
                    },
                  }
            }.not_to change { wiki_post.topic.reload.bumped_at }
            expect(response.status).to eq(200)
          end
        end

        context "as regular user" do
          fab!(:old_wiki_post) do
            Fabricate(:post, user:, wiki: true, last_version_at: 10.minutes.ago)
          end

          before do
            sign_in(user)
            old_wiki_post.topic.update!(bumped_at: 1.day.ago)
          end

          it "ignores bypass_bump (topic still bumps)" do
            expect {
              put "/posts/#{old_wiki_post.id}.json",
                  params: {
                    bypass_bump: true,
                    post: {
                      raw: "updated content",
                    },
                  }
            }.to change { old_wiki_post.topic.reload.bumped_at }
            expect(response.status).to eq(200)
          end
        end
      end
    end

    describe "when logged in as group moderator" do
      fab!(:topic) { Fabricate(:topic, category: category) }
      fab!(:post) { Fabricate(:post, user: user, topic: topic) }
      fab!(:group_user)
      let(:user_gm) { group_user.user }
      let(:group) { group_user.group }

      before do
        SiteSetting.enable_category_group_moderation = true
        Fabricate(:category_moderation_group, category: post.topic.category, group:)
        post.topic.category.update!(topic_id: topic.id)
        sign_in(user_gm)
      end

      it "allows updating the category description" do
        put "/posts/#{post.id}.json", params: update_params
        expect(response.status).to eq(200)

        post.reload
        expect(post.raw).to eq("edited body")
        expect(UserHistory.where(action: UserHistory.actions[:post_edit]).count).to eq(1)
      end

      it "can not update category descriptions in other categories" do
        second_category = Fabricate(:category)
        topic.update!(category: second_category)

        put "/posts/#{post.id}.json", params: update_params
        expect(response.status).to eq(403)
      end
    end

    context "when logged in as a category group moderator who cannot see the topic" do
      fab!(:mod_group, :group)
      fab!(:cat_mod_user, :user)
      fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
      fab!(:private_topic) { Fabricate(:topic, category: private_category) }
      fab!(:private_post) { Fabricate(:post, topic: private_topic) }

      before do
        SiteSetting.enable_category_group_moderation = true
        Fabricate(:category_moderation_group, category: private_category, group: mod_group)
        mod_group.add(cat_mod_user)
        sign_in(cat_mod_user)
      end

      it "prevents editing a post in a topic the user cannot see" do
        put "/posts/#{private_post.id}.json", params: { post: { raw: "edited body" } }

        expect(response.status).to eq(403)
        expect(private_post.reload.raw).not_to eq("edited body")
      end
    end

    context "when logged in as a category group moderator who can see the topic" do
      fab!(:mod_group, :group)
      fab!(:cat_mod_user, :user)
      fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
      fab!(:private_topic) { Fabricate(:topic, category: private_category) }
      fab!(:private_post) { Fabricate(:post, topic: private_topic) }

      before do
        SiteSetting.enable_category_group_moderation = true
        private_category.set_permissions(mod_group => :full)
        private_category.save!
        Fabricate(:category_moderation_group, category: private_category, group: mod_group)
        mod_group.add(cat_mod_user)
        sign_in(cat_mod_user)
      end

      it "allows editing a post in a topic the user can see" do
        put "/posts/#{private_post.id}.json", params: { post: { raw: "edited body" } }

        expect(response.status).to eq(200)
        expect(private_post.reload.raw).to eq("edited body")
      end
    end

    it "can not change category to a disallowed category" do
      post = create_post
      sign_in(post.user)

      category = Fabricate(:category)
      category.set_permissions(staff: :full)
      category.save!

      put "/posts/#{post.id}.json",
          params: {
            post: {
              category_id: category.id,
              raw: "this is a test edit to post",
            },
          }

      expect(response.status).not_to eq(200)
      expect(post.topic.category_id).not_to eq(category.id)
    end

    it "can not move to a category that requires topic approval" do
      post = create_post
      sign_in(post.user)

      category = Fabricate(:category)
      category.require_topic_approval = true
      category.save!

      put "/posts/#{post.id}.json",
          params: {
            post: {
              category_id: category.id,
              raw: "this is a test edit to post",
            },
          }

      expect(response.status).to eq(403)
      expect(post.topic.reload.category_id).not_to eq(category.id)
    end

    describe "trying to add a link without permission" do
      it "returns an error message if links are added to posts when not allowed" do
        post = create_post
        sign_in(post.user)
        SiteSetting.post_links_allowed_groups = Group::AUTO_GROUPS[:admins]

        put "/posts/#{post.id}",
            params: {
              post: {
                raw: "I'm editing this post to add www.linkhere.com",
              },
            }

        expect(response.status).to eq(422)
        expect(response.body).to include("Sorry, you can't include links in your posts.")
      end
    end

    describe "with Post.plugin_permitted_update_params" do
      before do
        plugin = Plugin::Instance.new
        plugin.add_permitted_post_update_param(:random_number) do |post, value|
          post.custom_fields[:random_number] = value
          post.save
        end
      end

      after { DiscoursePluginRegistry.reset! }

      it "calls blocks passed into `add_permitted_post_update_param`" do
        sign_in(post.user)
        put "/posts/#{post.id}.json",
            params: {
              post: {
                raw: "this is a random post",
                random_number: 244,
              },
            }

        expect(response.status).to eq(200)
        expect(post.reload.custom_fields[:random_number]).to eq("244")
      end
    end

    describe "reply_to_post_number" do
      fab!(:topic)
      fab!(:op) { Fabricate(:post, topic: topic, user: Fabricate(:user)) }
      fab!(:first_reply) do
        Fabricate(:post, topic: topic, user: Fabricate(:user), reply_to_post_number: op.post_number)
      end
      fab!(:editable_post) do
        Fabricate(
          :post,
          topic: topic,
          user: user,
          reply_to_post_number: op.post_number,
          reply_to_user_id: op.user_id,
        )
      end

      before { sign_in(user) }

      it "reparents the post to another earlier post" do
        put "/posts/#{editable_post.id}.json",
            params: {
              post: {
                raw: editable_post.raw,
                reply_to_post_number: first_reply.post_number,
              },
            }

        expect(response.status).to eq(200)
        editable_post.reload
        expect(editable_post.reply_to_post_number).to eq(first_reply.post_number)
        expect(editable_post.reply_to_user_id).to eq(first_reply.user_id)
      end

      it "clears the reply relationship when set to null" do
        put "/posts/#{editable_post.id}.json",
            params: {
              post: {
                raw: editable_post.raw,
                reply_to_post_number: nil,
              },
            }

        expect(response.status).to eq(200)
        editable_post.reload
        expect(editable_post.reply_to_post_number).to be_nil
        expect(editable_post.reply_to_user_id).to be_nil
      end

      it "returns an error when the target is invalid" do
        put "/posts/#{editable_post.id}.json",
            params: {
              post: {
                raw: editable_post.raw,
                reply_to_post_number: editable_post.post_number,
              },
            }

        expect(response.status).to eq(422)
        expect(editable_post.reload.reply_to_post_number).to eq(op.post_number)
      end
    end
  end

  describe "#destroy_bookmark" do
    fab!(:post)
    fab!(:bookmark) { Fabricate(:bookmark, user: user, bookmarkable: post) }

    before { sign_in(user) }

    it "deletes the bookmark" do
      bookmark_id = bookmark.id
      delete "/posts/#{post.id}/bookmark.json"
      expect(Bookmark.find_by(id: bookmark_id)).to eq(nil)
    end

    context "when the user still has bookmarks in the topic" do
      before { Fabricate(:bookmark, user: user, bookmarkable: Fabricate(:post, topic: post.topic)) }

      it "marks topic_bookmarked as true" do
        delete "/posts/#{post.id}/bookmark.json"
        expect(response.parsed_body["topic_bookmarked"]).to eq(true)
      end
    end
  end

  describe "#wiki" do
    include_examples "action requires login", :put, "/posts/2/wiki.json"

    describe "when logged in" do
      before { sign_in(user) }

      let!(:post) { post_by_user }

      it "returns 400 when wiki parameter is not present" do
        sign_in(admin)

        put "/posts/#{post.id}/wiki.json", params: {}

        expect(response.status).to eq(400)
      end

      it "raises an error if the user doesn't have permission to wiki the post" do
        put "/posts/#{post.id}/wiki.json", params: { wiki: "true" }
        expect(response).to be_forbidden
      end

      it "toggle wiki status should create a new version" do
        sign_in(admin)
        another_user = Fabricate(:user)
        another_post = Fabricate(:post, user: another_user)

        expect do
          put "/posts/#{another_post.id}/wiki.json", params: { wiki: "true" }
        end.to change { another_post.reload.version }.by(1)

        expect do
          put "/posts/#{another_post.id}/wiki.json", params: { wiki: "false" }
        end.to change { another_post.reload.version }.by(-1)

        sign_in(Fabricate(:admin))

        expect do
          put "/posts/#{another_post.id}/wiki.json", params: { wiki: "true" }
        end.to change { another_post.reload.version }.by(1)
      end

      it "can wiki a post" do
        sign_in(admin)
        put "/posts/#{post.id}/wiki.json", params: { wiki: "true" }

        post.reload
        expect(post.wiki).to eq(true)
      end

      it "can unwiki a post" do
        wikied_post = Fabricate(:post, user: user, wiki: true)
        sign_in(admin)

        put "/posts/#{wikied_post.id}/wiki.json", params: { wiki: "false" }

        wikied_post.reload
        expect(wikied_post.wiki).to eq(false)
      end
    end
  end

  describe "#post_type" do
    include_examples "action requires login", :put, "/posts/2/post_type.json"

    describe "when logged in" do
      before { sign_in(moderator) }

      let!(:post) { post_by_user }

      it "raises an error if the user doesn't have permission to change the post type" do
        sign_in(user)

        put "/posts/#{post.id}/post_type.json", params: { post_type: 2 }
        expect(response).to be_forbidden
      end

      it "returns 400 if post_type parameter is not present" do
        put "/posts/#{post.id}/post_type.json", params: {}

        expect(response.status).to eq(400)
      end

      it "returns 400 if post_type parameters is invalid" do
        put "/posts/#{post.id}/post_type.json", params: { post_type: -1 }

        expect(response.status).to eq(400)
      end

      it "rejects changing a reply to a small action" do
        put "/posts/#{post.id}/post_type.json", params: { post_type: Post.types[:small_action] }

        expect(response).to be_bad_request
        expect(post.reload.post_type).to eq(Post.types[:regular])
      end

      it "prevents moderators outside whisper groups from converting public replies to whispers" do
        whisper_group = Fabricate(:group)
        SiteSetting.whispers_allowed_groups = whisper_group.id.to_s
        topic = Fabricate(:topic)
        Fabricate(:post, topic:)
        public_reply = Fabricate(:post, topic:, raw: "public reply that must remain visible")

        put "/posts/#{public_reply.id}/post_type.json", params: { post_type: Post.types[:whisper] }

        aggregate_failures do
          expect(response).to be_forbidden
          expect(response.body).to include(I18n.t("invalid_whisper_access"))
          expect(public_reply.reload.post_type).to eq(Post.types[:regular])
        end
      end

      it "rejects changing an opening post to a whisper" do
        opening_post = Fabricate(:post)

        put "/posts/#{opening_post.id}/post_type.json", params: { post_type: Post.types[:whisper] }

        expect(response).to be_bad_request
        expect(opening_post.reload.post_type).to eq(Post.types[:regular])
      end

      it "rejects changing a nested topic's opening post to a small action" do
        nested_view_topic = Fabricate(:topic, user: user)
        opening_post = Fabricate(:post, topic: nested_view_topic, user: user, post_number: 1)
        Fabricate(:nested_topic, topic: nested_view_topic)
        SiteSetting.nested_replies_enabled = true

        put "/posts/#{opening_post.id}/post_type.json",
            params: {
              post_type: Post.types[:small_action],
            }

        aggregate_failures do
          expect(response).to be_bad_request
          expect(response.body).to include("post_type")
          expect(opening_post.reload.post_type).to eq(Post.types[:regular])

          sign_out
          get "/n/#{nested_view_topic.slug}/#{nested_view_topic.id}.json"

          expect(response).to be_ok
          expect(response.parsed_body.dig("op_post", "id")).to eq(opening_post.id)
        end
      end

      it "can change the post type" do
        put "/posts/#{post.id}/post_type.json", params: { post_type: 2 }

        post.reload
        expect(post.post_type).to eq(2)
      end
    end
  end

  describe "#rebake" do
    include_examples "action requires login", :put, "/posts/2/rebake.json"

    describe "when logged in" do
      let!(:post) { post_by_user }

      it "raises an error if the user doesn't have permission to rebake the post" do
        sign_in(user)
        put "/posts/#{post.id}/rebake.json"
        expect(response).to be_forbidden
      end

      it "can rebake the post" do
        sign_in(moderator)
        put "/posts/#{post.id}/rebake.json"
        expect(response.status).to eq(200)
      end

      it "invalidates the broken images cache" do
        sign_in(moderator)
        PostHotlinkedMedia.create!(
          url: "https://example.com/image.jpg",
          post: post,
          status: "download_failed",
        )
        put "/posts/#{post.id}/rebake.json"
        post.reload
        expect(post.post_hotlinked_media).to eq([])
      end
    end
  end

  describe "#create" do
    include_examples "action requires login", :post, "/posts.json"

    before do
      SiteSetting.fast_typing_threshold = "disabled"
      SiteSetting.whispers_allowed_groups = "#{Group::AUTO_GROUPS[:staff]}"
    end

    it "prevents regular users from publishing a global banner while creating a topic" do
      ApplicationLayoutPreloader.banner_json_cache.clear
      sign_in(user_trust_level_1)

      post "/posts.json",
           params: {
             raw: "this is a test banner topic body",
             title: "this is a test banner topic title",
             category: category.id,
             archetype: Archetype.banner,
           }

      creation_status = response.status
      creation_body = response.parsed_body
      created_topic = Topic.find(creation_body["topic_id"])

      sign_in(user)
      get "/site/banner.json"
      banner_status = response.status
      banner_body = response.parsed_body
      ApplicationLayoutPreloader.banner_json_cache.clear

      aggregate_failures do
        expect(creation_status).to eq(200)
        expect(creation_body["topic_id"]).to eq(created_topic.id)
        expect(created_topic.archetype).to eq(Archetype.default)
        expect(banner_status).to eq(200)
        expect(banner_body).to eq({})
      end
    end

    it "creates a regular topic when an unregistered archetype is supplied" do
      sign_in(user_trust_level_1)

      post "/posts.json",
           params: {
             raw: "this is a test topic body",
             title: "this is a test topic title",
             category: category.id,
             archetype: "unknown",
           }

      expect(response.status).to eq(200)
      expect(Topic.find(response.parsed_body["topic_id"]).archetype).to eq(Archetype.default)
    end

    context "with api" do
      it "memoizes duplicate requests" do
        raw = "this is a test post 123 #{SecureRandom.hash}"
        title = "this is a title #{SecureRandom.hash}"

        master_key = Fabricate(:api_key).key

        post "/posts.json",
             params: {
               raw: raw,
               title: title,
               wpid: 1,
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(200)
        original = response.body

        post "/posts.json",
             params: {
               raw: raw,
               title: title,
               wpid: 2,
             },
             headers: {
               HTTP_API_USERNAME: user.username_lower,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(200)
        expect(response.body).to eq(original)
      end

      it "returns a valid JSON response when the post is enqueued" do
        SiteSetting.approve_unless_allowed_groups = Group::AUTO_GROUPS[:trust_level_4]

        master_key = Fabricate(:api_key).key

        post "/posts.json",
             params: {
               raw: "this is test post #{SecureRandom.alphanumeric}",
               title: "this is a test title #{SecureRandom.alphanumeric}",
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(200)
        expect(response.parsed_body["action"]).to eq("enqueued")
      end

      it "allows to create posts in import_mode" do
        Jobs.run_immediately!
        NotificationEmailer.enable
        post_1 = Fabricate(:post)
        master_key = Fabricate(:api_key).key

        post "/posts.json",
             params: {
               raw: "this is test reply 1",
               topic_id: post_1.topic.id,
               reply_to_post_number: 1,
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(200)
        expect(post_1.topic.user.notifications.count).to eq(1)
        post_1.topic.user.notifications.destroy_all

        post "/posts.json",
             params: {
               raw: "this is test reply 2",
               topic_id: post_1.topic.id,
               reply_to_post_number: 1,
               import_mode: true,
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(200)
        expect(post_1.topic.user.notifications.count).to eq(0)

        post "/posts.json",
             params: {
               raw: "this is test reply 3",
               topic_id: post_1.topic.id,
               reply_to_post_number: 1,
               import_mode: false,
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(200)
        expect(post_1.topic.user.notifications.count).to eq(1)
      end

      it "allows a topic to be created with an external_id" do
        master_key = Fabricate(:api_key).key
        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is some post",
               external_id: "external_id",
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(200)

        new_topic = Topic.last

        expect(new_topic.external_id).to eq("external_id")
      end

      it "blocks email private message recipients that disabled private messages" do
        SiteSetting.enable_staged_users = true
        SiteSetting.personal_message_enabled_groups = Group::AUTO_GROUPS[:trust_level_4]
        SiteSetting.send_email_messages_allowed_groups = Group::AUTO_GROUPS[:trust_level_4]
        sender = Fabricate(:trust_level_4, refresh_auto_groups: true)
        recipient = Fabricate(:user)
        recipient.user_option.update!(allow_private_messages: false)
        api_key = ApiKey.create!(user: sender).key

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is some post",
               archetype: Archetype.private_message,
               target_recipients: recipient.email,
             },
             headers: {
               HTTP_API_USERNAME: sender.username,
               HTTP_API_KEY: api_key,
             }

        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"]).to include(
          I18n.t("activerecord.errors.models.topic.attributes.base.cant_send_pm"),
        )
        expect(TopicAllowedUser.exists?(user: recipient)).to eq(false)
      end

      it "prevents whispers for regular users" do
        post_1 = Fabricate(:post)
        user_key = ApiKey.create!(user: user).key

        post "/posts.json",
             params: {
               raw: "this is test whisper",
               topic_id: post_1.topic.id,
               reply_to_post_number: 1,
               whisper: true,
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: user_key,
             }

        expect(response.status).to eq(403)
      end

      it "allows staff to create whispers with boolean parameter" do
        post_1 = Fabricate(:post)
        staff_key = ApiKey.create!(user: admin).key

        post "/posts.json",
             params: {
               raw: "this is a staff whisper",
               topic_id: post_1.topic.id,
               reply_to_post_number: 1,
               whisper: true,
             }.to_json,
             headers: {
               "CONTENT_TYPE" => "application/json",
               "HTTP_API_USERNAME" => admin.username,
               "HTTP_API_KEY" => staff_key,
             }

        expect(response.status).to eq(200)
        expect(Post.last.post_type).to eq(Post.types[:whisper])
      end

      it "allows staff to create whispers with string 'true' parameter" do
        post_1 = Fabricate(:post)
        staff_key = ApiKey.create!(user: admin).key

        post "/posts.json",
             params: {
               raw: "this is a staff whisper with string param",
               topic_id: post_1.topic.id,
               reply_to_post_number: 1,
               whisper: "true",
             },
             headers: {
               HTTP_API_USERNAME: admin.username,
               HTTP_API_KEY: staff_key,
             }

        expect(response.status).to eq(200)
        expect(Post.last.post_type).to eq(Post.types[:whisper])
      end

      it "does not advance draft" do
        Draft.set(user, Draft::NEW_TOPIC, 0, "test")
        user_key = ApiKey.create!(user: user).key

        post "/posts.json",
             params: {
               title: "this is a test topic",
               raw: "this is test whisper",
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: user_key,
             }

        expect(response.status).to eq(200)
        expect(Draft.get(user, Draft::NEW_TOPIC, 0)).to eq("test")
      end

      it "returns an error when the specified category does not exist" do
        user = Fabricate(:admin)
        master_key = Fabricate(:api_key).key

        post "/posts.json",
             params: {
               title: "this is a test title",
               raw: "this is test body",
               category: "invalid",
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(400)

        expect(response.parsed_body["errors"]).to include(
          I18n.t("invalid_params", message: "category"),
        )
      end

      it "returns an error when embed_url is invalid" do
        user = Fabricate(:admin)
        master_key = Fabricate(:api_key).key

        post "/posts.json",
             params: {
               title: "this is a test title",
               raw: "this is test body",
               embed_url: "/test.txt",
             },
             headers: {
               HTTP_API_USERNAME: user.username,
               HTTP_API_KEY: master_key,
             }

        expect(response.status).to eq(422)
      end

      it "creates unlisted topic with admin master key" do
        master_key = Fabricate(:api_key).key

        expect do
          post "/posts.json",
               params: {
                 raw: "this is a test title",
                 title: "this is test body",
                 unlist_topic: true,
               },
               headers: {
                 HTTP_API_USERNAME: admin.username,
                 HTTP_API_KEY: master_key,
               }
        end.to change { Topic.count }.by(1)

        expect(response.status).to eq(200)
        expect(Topic.find(response.parsed_body["topic_id"]).visible).to eq(false)
      end

      it "prevents creation of unlisted topic with non-admin key" do
        user_key = ApiKey.create!(user: user).key

        expect do
          post "/posts.json",
               params: {
                 raw: "this is a test title",
                 title: "this is test body",
                 unlist_topic: true,
               },
               headers: {
                 HTTP_API_USERNAME: user.username,
                 HTTP_API_KEY: user_key,
               }
        end.not_to change { Topic.count }

        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"]).to include(
          I18n.t("activerecord.errors.models.topic.attributes.base.unable_to_unlist"),
        )
      end
    end

    describe "when logged in" do
      fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }

      before { sign_in(user) }

      it "rejects scalar tags before queuing a post" do
        SiteSetting.tagging_enabled = true
        SiteSetting.approve_post_count = 1

        expect do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 tags: "macos",
               }
        end.not_to change(ReviewableQueuedPost, :count)

        expect(response.status).to eq(400)
        expect(response.parsed_body["errors"]).to include(I18n.t("invalid_params", message: "tags"))
      end

      it "queues and approves a topic with blank tags" do
        SiteSetting.tagging_enabled = true
        SiteSetting.approve_post_count = 1

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is the test title for the topic",
               tags: "",
             }

        expect(response.status).to eq(200)
        expect(response.parsed_body["action"]).to eq("enqueued")
        queued_post = ReviewableQueuedPost.find_by!(target_created_by: user)

        sign_in(admin)
        put "/review/#{queued_post.id}/perform/approve_post.json",
            params: {
              version: queued_post.version,
            }

        expect(response.status).to eq(200)
        expect(queued_post.reload).to be_approved
        expect(queued_post.target.topic.tags).to be_empty
      end

      context "when fast typing" do
        before do
          SiteSetting.fast_typing_threshold = "standard"
          SiteSetting.auto_silence_fast_typers_max_trust_level = 1
        end

        it "queues the post if fast_typing_threshold is not met" do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 composer_open_duration_msecs: 204,
                 typing_duration_msecs: 100,
                 reply_to_post_number: 123,
               }

          expect(response.status).to eq(200)
          parsed = response.parsed_body

          expect(parsed["action"]).to eq("enqueued")

          user.reload
          expect(user).to be_silenced

          rp = ReviewableQueuedPost.find_by(target_created_by: user)
          expect(rp.payload["typing_duration_msecs"]).to eq(100)
          expect(rp.payload["composer_open_duration_msecs"]).to eq(204)
          expect(rp.payload["reply_to_post_number"]).to eq(123)
          expect(rp.reviewable_scores.first.reason).to eq("fast_typer")

          expect(parsed["pending_post"]).to be_present
          expect(parsed["pending_post"]["id"]).to eq(rp.id)
          expect(parsed["pending_post"]["raw"]).to eq("this is the test content")

          mod = moderator
          rp.perform(mod, :approve_post)

          user.reload
          expect(user).not_to be_silenced
        end

        it "does not silence when the post cannot be queued" do
          SiteSetting.newuser_max_embedded_media = 1
          topic = Fabricate(:topic)
          user.change_trust_level!(TrustLevel[0])

          post "/posts.json",
               params: {
                 raw:
                   "this is the test content\n\n<img src='https://example.com/first.png'>\n\n<img src='https://example.com/second.png'>",
                 topic_id: topic.id,
                 composer_open_duration_msecs: 204,
                 typing_duration_msecs: 100,
               }

          expect(response).not_to be_successful
          expect(response.parsed_body["errors"]).to be_present
          expect(ReviewableQueuedPost.find_by(target_created_by: user)).to be_blank

          user.reload
          expect(user).not_to be_silenced
        end

        it "doesn't enqueue posts when user first creates a topic" do
          topic = Fabricate(:post, user: user).topic

          Draft.set(user, "should_clear", 0, "{'a' : 'b'}")

          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 composer_open_duration_msecs: 204,
                 typing_duration_msecs: 100,
                 topic_id: topic.id,
                 draft_key: "should_clear",
               }

          expect(response.status).to eq(200)
          parsed = response.parsed_body

          expect(parsed["action"]).not_to be_present

          expect { Draft.get(user, "should_clear", 0) }.to raise_error(Draft::OutOfSequence)
        end

        it "doesn't enqueue replies when the topic is closed" do
          topic = Fabricate(:closed_topic)

          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 topic_id: topic.id,
               }

          expect(response).not_to be_successful
          parsed = response.parsed_body
          expect(parsed["action"]).not_to eq("enqueued")
        end

        it "doesn't enqueue replies when the post is too long" do
          SiteSetting.max_post_length = 10

          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
               }

          expect(response).not_to be_successful
          parsed = response.parsed_body
          expect(parsed["action"]).not_to eq("enqueued")
        end

        it "doesn't enqueue replies when the post is too long (including a html comment)" do
          SiteSetting.max_post_length = 10
          raw = "A post <!-- " + ("a" * 3000) + "-->"

          post "/posts.json", params: { raw: raw, title: "this is the test title for the topic" }

          expect(response).not_to be_successful
          parsed = response.parsed_body
          expect(parsed["action"]).not_to eq("enqueued")
        end
      end

      it "prevents category-Y reviewers from approving a queued reply in category X" do
        SiteSetting.enable_category_group_moderation = true
        topic_category = Fabricate(:category)
        topic_category.update!(require_reply_approval: true)
        review_category = Fabricate(:category)
        topic = Fabricate(:topic, category: topic_category)
        review_group = Fabricate(:group)
        reviewer = Fabricate(:user, refresh_auto_groups: true)
        review_group.add(reviewer)
        Fabricate(:category_moderation_group, category: review_category, group: review_group)

        raw = "queued reply in category X"
        post "/posts.json", params: { raw: raw, topic_id: topic.id, category: review_category.id }

        expect(response.status).to eq(200)
        expect(response.parsed_body["action"]).to eq("enqueued")
        reviewable = ReviewableQueuedPost.find_by!(target_created_by: user)

        sign_in(reviewer)
        expect do
          put "/review/#{reviewable.id}/perform/approve_post.json?version=#{reviewable.version}"
        end.not_to change(Post, :count)

        expect(response.status).to eq(403)
        expect(response.body).not_to include(raw)
        expect(reviewable.reload).to be_pending
      end

      it "silences correctly based on auto_silence_first_post_regex" do
        SiteSetting.auto_silence_first_post_regex = "I love candy|i eat s[1-5]"

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "when I eat s3 sometimes when not looking",
             }

        expect(response.status).to eq(200)
        parsed = response.parsed_body

        expect(parsed["action"]).to eq("enqueued")
        reviewable = ReviewableQueuedPost.find_by(target_created_by: user)
        score = reviewable.reviewable_scores.first
        expect(score.reason).to eq("auto_silence_regex")

        user.reload
        expect(user).to be_silenced
      end

      it "silences correctly based on silence watched words" do
        SiteSetting.watched_words_regular_expressions = true
        WatchedWord.create!(action: WatchedWord.actions[:silence], word: "I love candy")
        WatchedWord.create!(action: WatchedWord.actions[:silence], word: "i eat s[1-5]")

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "when I eat s3 sometimes when not looking",
             }

        expect(response.status).to eq(200)
        parsed = response.parsed_body

        expect(parsed["action"]).to eq("enqueued")
        reviewable = ReviewableQueuedPost.find_by(target_created_by: user)
        score = reviewable.reviewable_scores.first
        expect(score.reason).to eq("auto_silence_regex")

        user.reload
        expect(user).to be_silenced
      end

      it "can send a message to a group" do
        group = Group.create(name: "test_group", messageable_level: Group::ALIAS_LEVELS[:nobody])
        user1 = user
        group.add(user1)

        post "/posts.json",
             params: {
               raw: "I can haz a test",
               title: "I loves my test",
               target_recipients: group.name,
               archetype: Archetype.private_message,
             }

        expect(response).not_to be_successful

        # allow pm to this group
        group.update_columns(messageable_level: Group::ALIAS_LEVELS[:everyone])

        post "/posts.json",
             params: {
               raw: "I can haz a test",
               title: "I loves my test",
               target_recipients: "test_Group",
               archetype: Archetype.private_message,
             }

        expect(response.status).to eq(200)

        parsed = response.parsed_body
        post = Post.find(parsed["id"])

        expect(post.topic.topic_allowed_users.length).to eq(1)
        expect(post.topic.topic_allowed_groups.length).to eq(1)
      end

      it "can send a message to a group with caps" do
        group = Group.create(name: "Test_group", messageable_level: Group::ALIAS_LEVELS[:nobody])
        user1 = user
        group.add(user1)

        # allow pm to this group
        group.update_columns(messageable_level: Group::ALIAS_LEVELS[:everyone])

        post "/posts.json",
             params: {
               raw: "I can haz a test",
               title: "I loves my test",
               target_recipients: "test_Group",
               archetype: Archetype.private_message,
             }

        expect(response.status).to eq(200)

        parsed = response.parsed_body
        post = Post.find(parsed["id"])

        expect(post.topic.topic_allowed_users.length).to eq(1)
        expect(post.topic.topic_allowed_groups.length).to eq(1)
      end

      it "returns the nested post with a param" do
        post "/posts.json",
             params: {
               raw: "this is the test content  ",
               title: "this is the test title for the topic",
               nested_post: true,
             }

        expect(response.status).to eq(200)
        parsed = response.parsed_body
        expect(parsed["post"]).to be_present
        expect(parsed["post"]["raw"]).to eq("this is the test content")
        expect(parsed["post"]["cooked"]).to be_present
      end

      it "protects against dupes" do
        raw = "this is a test post 123 #{SecureRandom.hash}"
        title = "this is a title #{SecureRandom.hash}"

        expect do post "/posts.json", params: { raw: raw, title: title, wpid: 1 } end.to change {
          Post.count
        }

        expect(response.status).to eq(200)

        expect do
          post "/posts.json", params: { raw: raw, title: title, wpid: 2 }
        end.to_not change { Post.count }

        expect(response.status).to eq(422)
      end

      it "cannot create a post in a disallowed category" do
        category.set_permissions(staff: :full)
        category.save!

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is the test title for the topic",
               category: category.id,
             }

        expect(response.status).to eq(403)
      end

      it "cannot create a post with a tag that is restricted" do
        SiteSetting.tagging_enabled = true
        tag = Fabricate(:tag)
        category.allowed_tags = [tag.name]
        category.save!

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is the test title for the topic",
               tags: [tag.name],
             }

        expect(response.status).to eq(422)
        json = response.parsed_body
        expect(json["errors"]).to be_present
      end

      it "cannot create a post with a tag when tagging is disabled" do
        SiteSetting.tagging_enabled = false
        tag = Fabricate(:tag)

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is the test title for the topic",
               tags: [tag.name],
             }

        expect(response.status).to eq(422)
        json = response.parsed_body
        expect(json["errors"]).to be_present
      end

      it "cannot create a post with a tag without tagging permission" do
        SiteSetting.tagging_enabled = true
        SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:trust_level_4]
        tag = Fabricate(:tag)

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is the test title for the topic",
               tags: [tag.name],
             }

        expect(response.status).to eq(422)
        json = response.parsed_body
        expect(json["errors"]).to be_present
      end

      describe "tagging by name" do
        it "can create a post with a tag when tagging is enabled" do
          SiteSetting.tagging_enabled = true
          tag = Fabricate(:tag)

          logger =
            track_log_messages do
              post "/posts.json",
                   params: {
                     raw: "this is the test content",
                     title: "this is the test title for the topic",
                     tags: [tag.name],
                   }
            end

          expect(response.status).to eq(200)
          expect(Post.last.topic.tags.count).to eq(1)
          expect(logger.warnings.join("\n")).to include("tag names as strings")
        end
      end

      it "can create a post with a tag when tagging is enabled" do
        SiteSetting.tagging_enabled = true
        tag = Fabricate(:tag)

        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is the test title for the topic",
               tags: [{ id: tag.id, name: tag.name }],
             }

        expect(response.status).to eq(200)
        expect(Post.last.topic.tags).to contain_exactly(tag)
      end

      it "rejects tag arrays exceeding the configured per-topic limit" do
        SiteSetting.tagging_enabled = true
        SiteSetting.max_tags_per_topic = 5
        tags = 25.times.map { |index| Fabricate(:tag, name: "tag-#{index}") }

        expect do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 tags: tags.map { |tag| { id: tag.id, name: tag.name } },
               }
        end.not_to change { Post.count }

        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"]).to contain_exactly(
          I18n.t("tags.too_many_tags_for_topic", count: 5),
        )
      end

      context "with content localization enabled" do
        fab!(:japanese_user) { Fabricate(:user, locale: "ja", refresh_auto_groups: true) }
        fab!(:localized_tag) { Fabricate(:tag, name: "strategy", locale: "en") }
        fab!(:tag_localization) do
          Fabricate(:tag_localization, tag: localized_tag, locale: "ja", name: "戦略")
        end

        before do
          SiteSetting.tagging_enabled = true
          SiteSetting.content_localization_enabled = true
          SiteSetting.content_localization_supported_locales = "en|ja"
          sign_in(japanese_user)
        end

        it "creates a topic with localized tags" do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 tags: [{ id: localized_tag.id, name: "戦略" }],
               }

          expect(response.status).to eq(200)
          expect(Post.last.topic.tags).to contain_exactly(localized_tag)
        end

        it "creates a topic with tags sent as strings" do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 tags: ["strategy"],
               }

          expect(response.status).to eq(200)
          expect(Post.last.topic.tags).to contain_exactly(localized_tag)
        end
      end

      it "does not persist an iframe whose encoded userinfo points to an unallowlisted host" do
        iframe_source = "https://www.instagram.com%[email protected]/"

        post "/posts.json",
             params: {
               raw: %(User content <iframe src="#{iframe_source}"></iframe>),
               title: "Iframe allowlist bypass",
             }

        created_post = Post.find(response.parsed_body["id"])

        aggregate_failures do
          expect(response.status).to eq(200)
          expect(response.body).to include(%("id":#{created_post.id}))
          expect(created_post.cooked).not_to include(iframe_source)
          expect(Nokogiri::HTML5.fragment(created_post.cooked).at_css("iframe")).to be_nil
        end
      end

      it "does not persist HTML from an untrusted oEmbed provider" do
        Jobs.run_immediately!
        url = "https://attacker.example.com/onebox"
        malicious_html =
          '<div class="onebox-attack" style="position: fixed; inset: 0; z-index: 9999">overlay</div>'

        stub_request(:head, url).to_return(status: 200)
        stub_request(:get, url).to_return(
          status: 200,
          body:
            '<html><head><link type="application/json+oembed" href="https://attacker.example.com/oembed"></head></html>',
        )
        stub_request(:get, "https://attacker.example.com/oembed").to_return(
          status: 200,
          body: {
            title: "Attacker onebox",
            type: "rich",
            provider_name: "Flickr",
            html: malicious_html,
          }.to_json,
        )

        post "/posts.json", params: { raw: url, title: "Untrusted oEmbed provider" }

        expect(response.status).to eq(200)
        cooked = Nokogiri::HTML5.fragment(Post.find(response.parsed_body["id"]).cooked)
        expect(cooked.at_css(".onebox-attack")).to be_nil
      end

      it "does not persist sibling HTML from oEmbed with an allowed iframe" do
        Jobs.run_immediately!
        url = "https://attacker.example.com/onebox"
        iframe_source = "https://www.youtube.com/embed/dQw4w9WgXcQ"

        stub_request(:head, url).to_return(status: 200)
        stub_request(:get, url).to_return(
          status: 200,
          body:
            '<html><head><link type="application/json+oembed" href="https://attacker.example.com/oembed"></head></html>',
        )
        stub_request(:get, "https://attacker.example.com/oembed").to_return(
          status: 200,
          body: {
            title: "Attacker onebox",
            type: "rich",
            html:
              "<iframe src=\"#{iframe_source}\"></iframe><style>.onebox-attack { position: fixed; inset: 0; z-index: 9999; }</style><div class=\"onebox-attack\">overlay</div>",
          }.to_json,
        )

        post "/posts.json", params: { raw: url, title: "Allowed iframe oEmbed" }

        expect(response.status).to eq(200)
        expect(response.body).to include(%("id":#{response.parsed_body["id"]}))

        cooked = Nokogiri::HTML5.fragment(Post.find(response.parsed_body["id"]).cooked)
        expect(cooked.at_css("iframe")["src"]).to eq(iframe_source)
        expect(cooked.at_css("style")).to be_nil
        expect(cooked.at_css(".onebox-attack")).to be_nil
      end

      it "does not persist a backslash-bypassed wildcard iframe origin from oEmbed" do
        Jobs.run_immediately!
        url = "https://attacker.example.com/onebox"
        iframe_origin = "https://evil.example\\@sub.typeform.com/to/abc"

        stub_request(:head, url).to_return(status: 200)
        stub_request(:get, url).to_return(
          status: 200,
          body:
            '<html><head><link type="application/json+oembed" href="https://attacker.example.com/oembed"></head></html>',
        )
        stub_request(:get, "https://attacker.example.com/oembed").to_return(
          status: 200,
          body: {
            title: "Attacker onebox",
            type: "rich",
            html: "<iframe src=\"#{iframe_origin}\"></iframe>",
          }.to_json,
        )

        post "/posts.json", params: { raw: url, title: "Backslash iframe origin" }

        expect(response.status).to eq(200)
        expect(response.parsed_body["id"]).to be_present

        cooked = Nokogiri::HTML5.fragment(Post.find(response.parsed_body["id"]).cooked)
        expect(cooked.at_css("iframe")).to be_nil
      end

      it "creates the topic and post with the right attributes" do
        post "/posts.json",
             params: {
               raw: "this is the test content",
               title: "this is the test title for the topic",
               category: category.id,
             }

        expect(response.status).to eq(200)

        new_post = Post.last
        topic = new_post.topic

        expect(new_post.user).to eq(user)
        expect(new_post.raw).to eq("this is the test content")
        expect(topic.title).to eq("This is the test title for the topic")
        expect(topic.category).to eq(category)
        expect(topic.visible).to eq(true)
      end

      it "prevents regular users from replying to whispers" do
        sign_in(admin)
        post "/posts.json",
             params: {
               raw: "this is the first post with enough words",
               title: "this is a topic title for whispers",
             }
        expect(response.status).to eq(200)

        topic_id = response.parsed_body["topic_id"]
        post "/posts.json",
             params: {
               raw: "this is a staff-only whisper",
               topic_id: topic_id,
               reply_to_post_number: 1,
               whisper: true,
             }
        expect(response.status).to eq(200)

        whisper_post_number = response.parsed_body["post_number"]
        sign_in(user)

        expect do
          post "/posts.json",
               params: {
                 raw: "replying to a whisper over http",
                 topic_id: topic_id,
                 reply_to_post_number: whisper_post_number,
               }
        end.not_to change { Post.count }

        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"]).to include(I18n.t(:topic_not_found))
      end

      describe "posts_controller_create_user modifier" do
        fab!(:different_user, :admin)

        let!(:plugin) { Plugin::Instance.new }
        let!(:modifier) { :posts_controller_create_user }
        let!(:block) { Proc.new { different_user } }

        before { DiscoursePluginRegistry.register_modifier(plugin, modifier, &block) }
        after { DiscoursePluginRegistry.unregister_modifier(plugin, modifier, &block) }

        it "can alter the user used to create the post" do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 category: category.id,
               }

          expect(response.status).to eq(200)
          expect(Post.last.user).to eq(different_user)
        end
      end

      context "when adding custom fields to topic via the `topic_custom_fields` param" do
        it "returns 400 when no custom fields are permitted" do
          sign_in(user)

          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 category: category.id,
                 topic_custom_fields: {
                   xyz: "abc",
                   abc: "xyz",
                 },
               }

          expect(response.status).to eq(400)
          expect(Topic.last.custom_fields).to eq({})
        end

        context "when custom fields has been permitted" do
          fab!(:plugin) do
            plugin = Plugin::Instance.new
            plugin.register_editable_topic_custom_field(:xyz)
            plugin.register_editable_topic_custom_field(:abc, staff_only: true)
            plugin
          end

          it "returns 400 when a non-staff user adds a staff-only custom field" do
            sign_in(user)

            post "/posts.json",
                 params: {
                   raw: "this is the test content",
                   title: "this is the test title for the topic",
                   category: category.id,
                   topic_custom_fields: {
                     abc: "xyz",
                   },
                 }

            expect(response.status).to eq(400)
            expect(Topic.last.custom_fields).to eq({})
          end

          it "adds topic custom fields permitted for non-staff users" do
            sign_in(user)

            post "/posts.json",
                 params: {
                   raw: "this is the test content",
                   title: "this is the test title for the topic",
                   category: category.id,
                   topic_custom_fields: {
                     xyz: "abc",
                   },
                 }

            expect(response.status).to eq(200)
            expect(Topic.last.custom_fields).to eq({ "xyz" => "abc" })
          end

          it "adds permitted topic custom fields through the deprecated meta_data parameter" do
            sign_in(user)

            post "/posts.json",
                 params: {
                   raw: "this is the test content",
                   title: "this is the test title for the topic",
                   category: category.id,
                   meta_data: {
                     xyz: "abc",
                   },
                 }

            expect(response.status).to eq(200)
            expect(Topic.last.custom_fields).to eq({ "xyz" => "abc" })
          end

          it "adds topic custom fields permitted for staff and public users" do
            sign_in(Fabricate(:admin))

            post "/posts.json",
                 params: {
                   raw: "this is the test content",
                   title: "this is the test title for the topic",
                   category: category.id,
                   topic_custom_fields: {
                     xyz: "abc",
                     abc: "xyz",
                   },
                 }

            expect(response.status).to eq(200)
            expect(Topic.last.custom_fields).to eq({ "xyz" => "abc", "abc" => "xyz" })
          end
        end
      end

      it "can create an uncategorized topic" do
        title = "this is the test title for the topic"

        expect do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: title,
                 category: "",
               }

          expect(response.status).to eq(200)
        end.to change { Topic.count }.by(1)

        topic = Topic.last

        expect(topic.title).to eq(title.capitalize)
        expect(topic.category_id).to eq(SiteSetting.uncategorized_category_id)
      end

      it "can create a reply to a post" do
        topic = Fabricate(:private_message_post, user: user).topic
        post_2 = Fabricate(:private_message_post, user: user, topic: topic)

        post "/posts.json",
             params: {
               raw: "this is the test content",
               topic_id: topic.id,
               reply_to_post_number: post_2.post_number,
               image_sizes: {
                 width: "100",
                 height: "200",
               },
             }

        expect(response.status).to eq(200)

        new_post = Post.last
        topic = new_post.topic

        expect(new_post.user).to eq(user)
        expect(new_post.raw).to eq("this is the test content")
        expect(new_post.reply_to_post_number).to eq(post_2.post_number)

        job_args = Jobs::ProcessPost.jobs.first["args"].first

        expect(job_args["image_sizes"]).to eq("width" => "100", "height" => "200")
      end

      it "creates a private post" do
        user_2 = Fabricate(:user)
        user_3 = Fabricate(:user, username: "foo_bar")

        # In certain edge cases, it's possible to end up with a username
        # containing characters that would normally fail to validate
        user_4 = Fabricate(:user, username: "Iyi_Iyi")
        user_4.update_attribute(:username, "İyi_İyi")
        user_4.update_attribute(:username_lower, "İyi_İyi".downcase)

        post "/posts.json",
             params: {
               raw: "this is the test content",
               archetype: "private_message",
               title: "this is some post",
               target_recipients: "#{user_2.username},Foo_Bar,İyi_İyi",
             }

        expect(response.status).to eq(200)

        new_post = Post.last
        new_topic = Topic.last

        expect(new_post.user).to eq(user)
        expect(new_topic.private_message?).to eq(true)
        expect(new_topic.allowed_users).to contain_exactly(user, user_2, user_3, user_4)
      end

      context "when target_recipients not provided" do
        it "errors when creating a private post" do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 archetype: "private_message",
                 title: "this is some post",
                 target_recipients: "",
               }

          expect(response.status).to eq(422)
          expect(response.parsed_body["errors"]).to include(
            I18n.t("activerecord.errors.models.topic.attributes.base.no_user_selected"),
          )
        end
      end

      context "when topic_id is set" do
        fab!(:topic)

        it "errors when creating a private post" do
          user_2 = Fabricate(:user)

          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 archetype: "private_message",
                 title: "this is some post",
                 target_recipients: user_2.username,
                 topic_id: topic.id,
               }

          expect(response.status).to eq(422)
          expect(response.parsed_body["errors"]).to include(I18n.t("create_pm_on_existing_topic"))
        end
      end

      context "with errors" do
        it "does not succeed" do
          post "/posts.json", params: { raw: "test" }
          expect(response).not_to be_successful
          expect(response.status).to eq(422)
        end

        it "triggers flag_linked_posts_as_spam when the post creator returns spam" do
          SiteSetting.newuser_spam_host_threshold = 1
          sign_in(Fabricate(:user, trust_level: TrustLevel[0]))

          post "/posts.json",
               params: {
                 raw:
                   "this is the test content http://fakespamwebsite.com http://fakespamwebsite.com/spam http://fakespamwebsite.com/spammy",
                 title: "this is the test title for the topic",
               }

          expect(response.parsed_body["errors"]).to include(I18n.t(:spamming_host))
        end

        context "when allow_uncategorized_topics is false" do
          before { SiteSetting.allow_uncategorized_topics = false }

          it "cant create an uncategorized post" do
            post "/posts.json",
                 params: {
                   raw: "a new post with no category",
                   title: "a new post with no category",
                 }
            expect(response).not_to be_successful
          end

          context "as staff" do
            before { sign_in(admin) }

            it "cant create an uncategorized post" do
              post "/posts.json",
                   params: {
                     raw: "a new post with no category",
                     title: "a new post with no category",
                   }
              expect(response).not_to be_successful
            end
          end
        end
      end

      context "when topic is in slow mode" do
        fab!(:slow_topic) { Fabricate(:topic, slow_mode_seconds: 86_400) }

        it "enforces slow mode even when auto_track is false" do
          post "/posts.json",
               params: {
                 raw: "this is the first reply in slow mode",
                 topic_id: slow_topic.id,
                 auto_track: false,
               }

          expect(response.status).to eq(200)

          post "/posts.json",
               params: {
                 raw: "this is the second reply in slow mode bypassing",
                 topic_id: slow_topic.id,
                 auto_track: false,
               }

          expect(response.status).to eq(422)
          expect(response.parsed_body["errors"]).to include(I18n.t(:slow_mode_enabled))
        end

        it "does not create a TopicUser record when auto_track is false" do
          post "/posts.json",
               params: {
                 raw: "this is a reply with auto_track false",
                 topic_id: slow_topic.id,
                 auto_track: false,
               }

          expect(response.status).to eq(200)
          expect(TopicUser.find_by(user: user, topic: slow_topic)).to be_nil
        end
      end

      context "when `enable_user_status` site setting is enabled" do
        fab!(:user_to_mention, :user)

        before { SiteSetting.enable_user_status = true }

        it "does not return mentioned users when `enable_user_status` site setting is disabled" do
          SiteSetting.enable_user_status = false

          post "/posts.json",
               params: {
                 raw: "I am mentioning @#{user_to_mention.username}",
                 topic_id: topic.id,
               }

          expect(response.status).to eq(200)

          json = response.parsed_body

          expect(json["mentioned_users"]).to eq(nil)
        end

        it "returns mentioned users" do
          user_to_mention.set_status!("off to dentist", "tooth")

          post "/posts.json",
               params: {
                 raw: "I am mentioning @#{user_to_mention.username}",
                 topic_id: topic.id,
               }

          expect(response.status).to eq(200)
          json = response.parsed_body
          expect(json["mentioned_users"].length).to be(1)

          mentioned_user = json["mentioned_users"][0]
          expect(mentioned_user["id"]).to be(user_to_mention.id)
          expect(mentioned_user["name"]).to eq(user_to_mention.name)
          expect(mentioned_user["username"]).to eq(user_to_mention.username)

          status = mentioned_user["status"]
          expect(status).to be_present
          expect(status["emoji"]).to eq(user_to_mention.user_status.emoji)
          expect(status["description"]).to eq(user_to_mention.user_status.description)
        end

        it "returns an empty list of mentioned users if nobody was mentioned" do
          post "/posts.json", params: { raw: "No mentions here", topic_id: topic.id }

          expect(response.status).to eq(200)
          expect(response.parsed_body["mentioned_users"].length).to be(0)
        end

        it "returns an empty list of mentioned users if an nonexistent user was mentioned" do
          post "/posts.json", params: { raw: "Mentioning a @stranger", topic_id: topic.id }

          expect(response.status).to eq(200)
          expect(response.parsed_body["mentioned_users"].length).to be(0)
        end
      end
    end

    context "with topic unlisting" do
      context "when logged in as staff" do
        before { sign_in(admin) }

        it "creates an unlisted topic" do
          expect do
            post "/posts.json",
                 params: {
                   raw: "this is the test content",
                   title: "this is the test title for the topic",
                   unlist_topic: true,
                 }
          end.to change { Topic.count }.by(1)

          expect(response.status).to eq(200)
          expect(Topic.find(response.parsed_body["topic_id"]).visible).to eq(false)
        end
      end

      context "when logged in as a non-staff user" do
        before { sign_in(user) }

        it "prevents creation of an unlisted topic" do
          expect do
            post "/posts.json",
                 params: {
                   raw: "this is the test content",
                   title: "this is the test title for the topic",
                   unlist_topic: true,
                 }
          end.not_to change { Topic.count }

          expect(response.status).to eq(422)
          expect(response.parsed_body["errors"]).to include(
            I18n.t("activerecord.errors.models.topic.attributes.base.unable_to_unlist"),
          )
        end

        context "with apply_modifier" do
          it "can modify groups" do
            plugin = Plugin::Instance.new
            modifier = :mentionable_groups
            proc = Proc.new { Group.all }
            DiscoursePluginRegistry.register_modifier(plugin, modifier, &proc)

            expect(Group.mentionable(user)).to eq(Group.all)
          ensure
            DiscoursePluginRegistry.unregister_modifier(plugin, modifier, &proc)
          end
        end
      end
    end

    describe "shared draft" do
      fab!(:destination_category, :category)

      it "returns an error for regular users" do
        post "/posts.json",
             params: {
               raw: "this is the shared draft content",
               title: "this is the shared draft title",
               category: destination_category.id,
               shared_draft: "true",
             }
        expect(response).not_to be_successful
      end

      describe "as a staff user" do
        before { sign_in(moderator) }

        it "returns an error when no shared draft category exists" do
          post "/posts.json",
               params: {
                 raw: "this is the shared draft content",
                 title: "this is the shared draft title",
                 category: destination_category.id,
                 shared_draft: "true",
               }
          expect(response).not_to be_successful
        end

        context "with a shared category" do
          fab!(:shared_category, :category)
          before { SiteSetting.shared_drafts_category = shared_category.id }

          it "creates a shared draft when the shared draft category exists" do
            post "/posts.json",
                 params: {
                   raw: "this is the shared draft content",
                   title: "this is the shared draft title",
                   category: destination_category.id,
                   shared_draft: "true",
                 }
            expect(response.status).to eq(200)
            result = response.parsed_body
            topic = Topic.find(result["topic_id"])
            expect(topic.category_id).to eq(shared_category.id)
            expect(topic.shared_draft.category_id).to eq(destination_category.id)
          end

          it "accepts boolean true for shared_draft parameter" do
            post "/posts.json",
                 params: {
                   raw: "this is the shared draft content",
                   title: "this is the shared draft title with boolean",
                   category: destination_category.id,
                   shared_draft: true,
                 }.to_json,
                 headers: {
                   "CONTENT_TYPE" => "application/json",
                 }
            expect(response.status).to eq(200)
            result = response.parsed_body
            topic = Topic.find(result["topic_id"])
            expect(topic.category_id).to eq(shared_category.id)
            expect(topic.shared_draft.category_id).to eq(destination_category.id)
          end
        end
      end
    end

    describe "warnings" do
      fab!(:user_2) { Fabricate(:user, refresh_auto_groups: true) }

      context "as a staff user" do
        before { sign_in(admin) }

        it "marks the topic as a warning" do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 archetype: "private_message",
                 title: "this is some post",
                 target_recipients: user_2.username,
                 is_warning: true,
               }

          expect(response.status).to eq(200)

          new_topic = Topic.last

          expect(new_topic.title).to eq("This is some post")
          expect(new_topic.is_official_warning?).to eq(true)
        end

        it "accepts string 'true' for is_warning parameter" do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 archetype: "private_message",
                 title: "this is some post with string param",
                 target_recipients: user_2.username,
                 is_warning: "true",
               }

          expect(response.status).to eq(200)
          expect(Topic.last.is_official_warning?).to eq(true)
        end

        it "removes the topic's warning status" do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 archetype: "private_message",
                 title: "this is some post",
                 target_recipients: user_2.username,
                 is_warning: false,
               }

          expect(response.status).to eq(200)

          new_topic = Topic.last

          expect(new_topic.title).to eq("This is some post")
          expect(new_topic.is_official_warning?).to eq(false)
        end
      end

      context "as a normal user" do
        it "rejects marking the topic as a warning" do
          sign_in(user)
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 archetype: "private_message",
                 title: "this is some post",
                 target_recipients: user_2.username,
                 is_warning: true,
               }

          expect(response.status).to eq(200)

          new_topic = Topic.last

          expect(new_topic.title).to eq("This is some post")
          expect(new_topic.is_official_warning?).to eq(false)
        end
      end
    end

    context "with topic bump" do
      shared_examples "it works" do
        it "skips topic bumping when requested" do
          original_bumped_at = 1.day.ago
          topic = Fabricate(:topic, bumped_at: original_bumped_at)

          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 topic_id: topic.id,
                 no_bump: true,
               }

          expect(response.status).to eq(200)
          expect(topic.reload.bumped_at).to eq_time(original_bumped_at)
        end

        it "accepts string 'true' for no_bump parameter" do
          original_bumped_at = 1.day.ago
          topic = Fabricate(:topic, bumped_at: original_bumped_at)

          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 topic_id: topic.id,
                 no_bump: "true",
               }

          expect(response.status).to eq(200)
          expect(topic.reload.bumped_at).to eq_time(original_bumped_at)
        end

        it "creates the post and bumps the topic" do
          post "/posts.json", params: { raw: "this is the test content", topic_id: topic.id }

          expect(response.status).to eq(200)
          expect(topic.reload.bumped_at).to eq_time(topic.posts.last.created_at)
        end
      end

      context "with admins" do
        before { sign_in(admin) }

        include_examples "it works"
      end

      context "with moderators" do
        before { sign_in(moderator) }

        include_examples "it works"
      end

      context "with TL4 users" do
        fab!(:trust_level_4)

        before { sign_in(trust_level_4) }

        include_examples "it works"
      end

      context "with users" do
        fab!(:topic)

        [:user].each do |user|
          it "returns an error for #{user}" do
            sign_in(Fabricate(user))
            post "/posts.json",
                 params: {
                   raw: "this is the test content",
                   topic_id: topic.id,
                   no_bump: true,
                 }
            expect(response.status).to eq(400)
          end
        end
      end
    end

    context "with featured links" do
      it "allows to create topics with featured links" do
        sign_in(user_trust_level_1)

        post "/posts.json",
             params: {
               title: "this is the test title for the topic",
               raw: "this is the test content",
               featured_link: "https://discourse.org",
             }

        expect(response.status).to eq(200)
      end

      it "doesn't allow TL0 users to create topics with featured links" do
        sign_in(user_trust_level_0)

        post "/posts.json",
             params: {
               title: "this is the test title for the topic",
               raw: "this is the test content",
               featured_link: "https://discourse.org",
             }

        expect(response.status).to eq(422)
      end

      it "doesn't allow to create topics with featured links if featured links are disabled in settings" do
        SiteSetting.topic_featured_link_enabled = false
        sign_in(user_trust_level_1)

        post "/posts.json",
             params: {
               title: "this is the test title for the topic",
               raw: "this is the test content",
               featured_link: "https://discourse.org",
             }

        expect(response.status).to eq(422)
      end

      it "doesn't allow to create topics with featured links in the category with forbidden feature links" do
        category = Fabricate(:category, topic_featured_link_allowed: false)
        sign_in(user_trust_level_1)

        post "/posts.json",
             params: {
               title: "this is the test title for the topic",
               raw: "this is the test content",
               featured_link: "https://discourse.org",
               category: category.id,
             }

        expect(response.status).to eq(422)
      end
    end
  end

  describe "#revisions" do
    fab!(:post) { Fabricate(:post, version: 2) }
    let(:post_revision) { Fabricate(:post_revision, post: post) }

    it "throws an exception when revision is < 2" do
      get "/posts/#{post.id}/revisions/1.json"
      expect(response.status).to eq(400)
    end

    it "attributes coalesced grace-period edits to the correct editor" do
      SiteSetting.edit_history_visible_to_public = true
      SiteSetting.editing_grace_period = 1.minute
      SiteSetting.editing_grace_period_max_diff = 1000

      edited_post = Fabricate(:post, raw: "Original version")
      first_editor = Fabricate(:user)
      second_editor = Fabricate(:user)
      first_body = "First editor first version"
      coalesced_body = "First editor coalesced version"
      second_body = "Second editor version"

      PostRevisor.new(edited_post).revise!(
        first_editor,
        { raw: first_body },
        revised_at: edited_post.updated_at + 2.minutes,
      )
      edited_post.reload
      PostRevisor.new(edited_post).revise!(
        first_editor,
        { raw: coalesced_body },
        revised_at: edited_post.last_version_at + 1.second,
      )
      edited_post.reload
      PostRevisor.new(edited_post).revise!(
        second_editor,
        { raw: second_body },
        revised_at: edited_post.last_version_at + 2.seconds,
      )
      edited_post.reload

      get "/posts/#{edited_post.id}/revisions/2.json"
      expect(response.status).to eq(200)
      expect(response.parsed_body["username"]).to eq(first_editor.username_lower)
      expect(response.parsed_body.dig("body_changes", "side_by_side_markdown")).to eq(
        DiscourseDiff.new("Original version", coalesced_body).side_by_side_markdown,
      )

      get "/posts/#{edited_post.id}/revisions/3.json"
      expect(response.status).to eq(200)
      expect(response.parsed_body["username"]).to eq(second_editor.username_lower)
      expect(response.parsed_body.dig("body_changes", "side_by_side_markdown")).to eq(
        DiscourseDiff.new(coalesced_body, second_body).side_by_side_markdown,
      )
    end

    context "when the id is passed as an array" do
      fab!(:accessible_post) { Fabricate(:post, user: moderator) }
      fab!(:inaccessible_post, :private_message_post)
      fab!(:inaccessible_revision) do
        Fabricate(
          :post_revision,
          post: inaccessible_post,
          number: 2,
          modifications: {
            "raw" => ["previous private body", "current private body"],
          },
        )
      end

      before { sign_in(moderator) }

      it "does not return a revision the user cannot see on another post" do
        expect(accessible_post.id).to be < inaccessible_post.id
        expect(moderator.guardian.can_see?(inaccessible_post)).to eq(false)

        previous_raw = inaccessible_revision.modifications["raw"][0]

        get "/posts/#{accessible_post.id}/revisions/2.json",
            params: {
              id: [accessible_post.id, inaccessible_post.id],
            }

        expect(response.status).to eq(404)
        expect(response.body).not_to include(previous_raw)
      end
    end

    context "when a visible revision is adjacent to a hidden revision" do
      fab!(:post_owner, :user)
      fab!(:post_with_following_hidden_revision) do
        Fabricate(:post, user: post_owner, raw: "Initial public version")
      end
      fab!(:post_with_previous_hidden_revision) do
        Fabricate(:post, user: post_owner, raw: "Initial public version")
      end

      before do
        SiteSetting.edit_history_visible_to_public = true
        SiteSetting.editing_grace_period = 0
      end

      it "does not disclose a following hidden revision to non-staff" do
        post_with_following_hidden_revision.revise(post_owner, raw: "Visible version")
        post_with_following_hidden_revision.revise(post_owner, raw: "Following hidden secret")
        hidden_revision = post_with_following_hidden_revision.revisions.find_by(number: 3)
        hidden_revision.hide!

        get "/posts/#{post_with_following_hidden_revision.id}/revisions/2.json"

        expect(response.status).to eq(200)
        expect(response.parsed_body["current_hidden"]).to eq(true)
        expect(response.parsed_body["body_changes"]).to eq(nil)
        expect(response.body).not_to include(hidden_revision.modifications["raw"].last)
      end

      it "does not disclose a previous hidden revision to non-staff" do
        post_with_previous_hidden_revision.revise(post_owner, raw: "Previous hidden secret")
        hidden_revision = post_with_previous_hidden_revision.revisions.find_by(number: 2)
        hidden_revision.hide!
        post_with_previous_hidden_revision.revise(post_owner, raw: "Visible version")

        get "/posts/#{post_with_previous_hidden_revision.id}/revisions/3.json"

        expect(response.status).to eq(200)
        expect(response.parsed_body["previous_hidden"]).to eq(true)
        expect(response.parsed_body["body_changes"]).to eq(nil)
        expect(response.body).not_to include(hidden_revision.modifications["raw"].last)
      end

      it "does not disclose metadata changes from a previous hidden revision to non-staff" do
        topic = Fabricate(:topic, user: post_owner)
        op = Fabricate(:post, topic: topic, user: post_owner, post_number: 1)
        hidden_parent = Fabricate(:post, topic: topic, user: post_owner, post_number: 2)
        visible_parent = Fabricate(:post, topic: topic, user: post_owner, post_number: 3)
        post =
          Fabricate(
            :post,
            topic: topic,
            user: post_owner,
            post_number: 4,
            raw: "Initial public version",
            reply_to_post_number: op.post_number,
            locale: "en",
            wiki: false,
            post_type: Post.types[:regular],
          )

        post.revise(
          post_owner,
          {
            raw: "Hidden metadata version",
            reply_to_post_number: hidden_parent.post_number,
            wiki: true,
            post_type: Post.types[:whisper],
            locale: "ja",
          },
          skip_validations: true,
        )
        hidden_revision = post.revisions.find_by(number: 2)
        hidden_revision.hide!
        post.revise(
          post_owner,
          {
            raw: "Visible metadata version",
            reply_to_post_number: visible_parent.post_number,
            wiki: false,
            post_type: Post.types[:regular],
            locale: "fr",
          },
          skip_validations: true,
        )

        get "/posts/#{post.id}/revisions/3.json"

        expect(response.status).to eq(200)
        expect(response.parsed_body["previous_hidden"]).to eq(true)
        expect(response.parsed_body["body_changes"]).to eq(nil)
        expect(response.parsed_body).not_to have_key("reply_to_post_number_changes")
        expect(response.parsed_body).not_to have_key("wiki_changes")
        expect(response.parsed_body).not_to have_key("post_type_changes")
        expect(response.parsed_body).not_to have_key("locale_changes")
        expect(response.body).not_to include(hidden_revision.modifications["raw"].last)
      end
    end

    context "when diff generation exceeds the comparison budget" do
      let(:diff_error) do
        ONPDiff::DiffLimitExceeded.new(
          comparisons_used: 1,
          comparison_budget: 0,
          left_size: 1,
          right_size: 1,
        )
      end

      before { ONPDiff.any_instance.stubs(:compose).raises(diff_error) }

      it "returns an empty diff and an error flag for a specific revision endpoint" do
        sign_in(admin)
        get "/posts/#{post.id}/revisions/#{post_revision.number}.json"

        expect(response.parsed_body["body_changes"]).to eq(nil)
        expect(response.parsed_body["diff_error"]).to eq(true)
      end

      it "returns an empty diff and an error flag for the latest revision endpoint" do
        sign_in(admin)
        post_revision
        get "/posts/#{post.id}/revisions/latest.json"

        expect(response.parsed_body["body_changes"]).to eq(nil)
        expect(response.parsed_body["diff_error"]).to eq(true)
      end
    end

    context "when edit history is not visible to the public" do
      before { SiteSetting.edit_history_visible_to_public = false }

      it "ensures anonymous cannot see the revisions" do
        get "/posts/#{post.id}/revisions/#{post_revision.number}.json"
        expect(response).to be_forbidden
      end

      it "ensures regular user cannot see the revisions" do
        sign_in(user)
        get "/posts/#{post.id}/revisions/#{post_revision.number}.json"
        expect(response).to be_forbidden
      end

      it "ensures staff can see the revisions" do
        sign_in(admin)
        get "/posts/#{post.id}/revisions/#{post_revision.number}.json"
        expect(response.status).to eq(200)
      end

      it "ensures poster can see the revisions" do
        user = Fabricate(:active_user)
        sign_in(user)

        post = Fabricate(:post, user: user, version: 3)
        pr = Fabricate(:post_revision, user: user, post: post)

        get "/posts/#{pr.post_id}/revisions/#{pr.number}.json"
        expect(response.status).to eq(200)
      end

      it "ensures trust level 4 cannot see the revisions" do
        sign_in(Fabricate(:user, trust_level: 4))
        get "/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json"
        expect(response.status).to eq(403)
      end

      context "with a category group moderator" do
        fab!(:group)
        fab!(:category_moderator) { Fabricate(:user, groups: [group]) }

        before do
          SiteSetting.enable_category_group_moderation = true
          sign_in(category_moderator)
        end

        it "ensures they can see the revisions in their moderated category" do
          Fabricate(:category_moderation_group, category: post.topic.category, group:)

          get "/posts/#{post.id}/revisions/#{post_revision.number}.json"
          expect(response.status).to eq(200)
        end

        it "ensures they cannot see the revisions in other categories" do
          Fabricate(:category_moderation_group, category: Fabricate(:category), group:)

          get "/posts/#{post.id}/revisions/#{post_revision.number}.json"
          expect(response).to be_forbidden
        end

        it "ensures they cannot see hidden revisions in their moderated category" do
          Fabricate(:category_moderation_group, category: post.topic.category, group:)
          post_revision.update!(hidden: true)

          get "/posts/#{post.id}/revisions/#{post_revision.number}.json"
          expect(response).to be_forbidden
        end
      end
    end

    context "when the history on a specific post is hidden" do
      it "works when hiding a revision" do
        sign_in(admin)

        message =
          MessageBus
            .track_publish("/topic/#{post.topic.id}") do
              put "/posts/#{post_revision.post_id}/revisions/#{post_revision.number}/hide"
            end
            .first

        expect(response.status).to eq(200)
        expect(message.data[:type]).to eq(:revised)
        expect(message.data[:version]).to eq(2)
        expect(post_revision.reload[:hidden]).to eq(true)
      end

      it "works when showing a revision" do
        post_revision.update!(hidden: true)
        sign_in(admin)

        message =
          MessageBus
            .track_publish("/topic/#{post.topic.id}") do
              put "/posts/#{post_revision.post_id}/revisions/#{post_revision.number}/show"
            end
            .first

        expect(response.status).to eq(200)
        expect(message.data[:type]).to eq(:revised)
        expect(message.data[:version]).to eq(2)
        expect(post_revision.reload[:hidden]).to eq(false)
      end
    end

    context "when post is hidden" do
      before do
        post.hidden = true
        post.save
      end

      it "throws an exception for users" do
        sign_in(user)
        get "/posts/#{post.id}/revisions/#{post_revision.number}.json"
        expect(response.status).to eq(404)
      end

      it "works for admins" do
        sign_in(admin)
        get "/posts/#{post.id}/revisions/#{post_revision.number}.json"
        expect(response.status).to eq(200)
      end
    end

    context "when edit history is visible to everyone" do
      before { SiteSetting.edit_history_visible_to_public = true }

      it "ensures anyone can see the revisions" do
        get "/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json"
        expect(response.status).to eq(200)
      end

      it "does not expose tag names restricted to an inaccessible category" do
        SiteSetting.tagging_enabled = true
        public_tag = Fabricate(:tag, name: "public-revision-tag")
        restricted_tag = Fabricate(:tag, name: "restricted-revision-tag")
        revised_post = Fabricate(:post, version: 2)
        revision =
          Fabricate(
            :post_revision,
            post: revised_post,
            modifications: {
              "tags" => [[public_tag.name], [public_tag.name, restricted_tag.name]],
            },
          )

        revised_post.topic.update!(tags: [public_tag, restricted_tag])
        CategoryTag.create!(
          category: Fabricate(:private_category, group: Group[:staff]),
          tag: restricted_tag,
        )

        [
          "/posts/#{revised_post.id}/revisions/#{revision.number}.json",
          "/posts/#{revised_post.id}/revisions/latest.json",
        ].each do |url|
          get url

          expect(response).to have_http_status(:ok)
          expect(response.body).not_to include(restricted_tag.name)
        end
      end

      it "does not disclose category-restricted tag names to anonymous users" do
        SiteSetting.tagging_enabled = true

        restricted_tag = Fabricate(:tag, name: "classified-tag")
        revision =
          Fabricate(
            :post_revision,
            post: post,
            modifications: {
              "tags" => [[restricted_tag.name], []],
            },
          )
        private_category = Fabricate(:private_category, group: Group[:staff])
        tag_group = Fabricate(:tag_group, tags: [restricted_tag])
        CategoryTagGroup.create!(category: private_category, tag_group: tag_group)

        get "/posts/#{post.id}/revisions/#{revision.number}.json"

        expect(response.status).to eq(200)
        expect(response.body).not_to include(restricted_tag.name)
      end

      it "does not disclose historical tags restricted to inaccessible categories" do
        SiteSetting.tagging_enabled = true

        restricted_tag = Fabricate(:tag, name: "restricted-historical-tag")
        visible_previous_tag = Fabricate(:tag, name: "visible-previous-tag")
        visible_current_tag = Fabricate(:tag, name: "visible-current-tag")
        private_category = Fabricate(:private_category, group: Group[:staff])
        CategoryTag.create!(category: private_category, tag: restricted_tag)
        post.topic.update!(tags: [visible_current_tag])
        revision =
          Fabricate(
            :post_revision,
            post: post,
            modifications: {
              "tags" => [
                [visible_previous_tag.name, restricted_tag.name],
                [visible_current_tag.name],
              ],
            },
          )

        get "/posts/#{post.id}/revisions/#{revision.number}.json"

        expect(response.status).to eq(200)
        expect(response.parsed_body["tags_changes"]).to eq(
          "previous" => [visible_previous_tag.name],
          "current" => [visible_current_tag.name],
        )
        expect(response.body).not_to include(restricted_tag.name)
      end

      it "omits unseen reply target post numbers" do
        SiteSetting.editing_grace_period = 0
        SiteSetting.whispers_allowed_groups = Group::AUTO_GROUPS[:staff]

        topic = Fabricate(:topic)
        Fabricate(:post, topic: topic, post_number: 1)
        visible_parent = Fabricate(:post, topic: topic, post_number: 2)
        whisper = Fabricate(:post, topic: topic, post_number: 3, post_type: Post.types[:whisper])
        revised_post =
          Fabricate(
            :post,
            topic: topic,
            post_number: 4,
            reply_to_post_number: visible_parent.post_number,
            reply_to_user_id: visible_parent.user_id,
          )

        sign_in(admin)
        put "/posts/#{revised_post.id}.json",
            params: {
              post: {
                raw: revised_post.raw,
                reply_to_post_number: whisper.post_number,
              },
            }
        expect(response.status).to eq(200)
        delete "/session/#{admin.username}.json"

        revision = revised_post.reload.revisions.last
        get "/posts/#{revised_post.id}/revisions/#{revision.number}.json"

        expect(response.status).to eq(200)
        expect(
          response.parsed_body["reply_to_post_number_changes"]["previous"]["post_number"],
        ).to eq(visible_parent.post_number)
        expect(response.parsed_body["reply_to_post_number_changes"]["current"]).to eq(nil)
      end

      context "when names are disabled" do
        before { SiteSetting.enable_names = false }

        it "does not expose the acting user's name" do
          post_revision.user.update!(name: "Hidden Editor")

          get "/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json"

          expect(response.status).to eq(200)
          expect(response.parsed_body["acting_user_name"]).to eq(nil)
        end
      end
    end

    context "with deleted post" do
      fab!(:deleted_post) { Fabricate(:post, user: admin, version: 3) }
      fab!(:deleted_post_revision) { Fabricate(:post_revision, user: admin, post: deleted_post) }

      before { deleted_post.trash!(admin) }

      it "also work on deleted post" do
        sign_in(admin)
        get "/posts/#{deleted_post_revision.post_id}/revisions/#{deleted_post_revision.number}.json"
        expect(response.status).to eq(200)
      end
    end

    context "with deleted topic" do
      fab!(:deleted_topic) { Fabricate(:topic, user: admin) }
      fab!(:post) { Fabricate(:post, user: admin, topic: deleted_topic, version: 3) }
      fab!(:post_revision) { Fabricate(:post_revision, user: admin, post: post) }

      before { deleted_topic.trash!(admin) }

      it "also work on deleted topic" do
        sign_in(admin)
        get "/posts/#{post_revision.post_id}/revisions/#{post_revision.number}.json"
        expect(response.status).to eq(200)
      end
    end

    context "with an unlisted revision" do
      fab!(:revised_post) { Fabricate(:post, version: 3) }

      before do
        Fabricate(:post_revision, post: revised_post, number: 2)
        Fabricate(:post_revision, post: revised_post, number: 3, unlisted: true)
      end

      it "steps to it only when unlisted revisions are included" do
        SiteSetting.edit_history_visible_to_public = true

        get "/posts/#{revised_post.id}/revisions/2.json"
        expect(response.parsed_body["next_revision"]).to eq(nil)

        get "/posts/#{revised_post.id}/revisions/2.json", params: { include_unlisted: true }
        expect(response.parsed_body["next_revision"]).to eq(3)
      end

      it "doesn't grant access to edit history that isn't visible" do
        SiteSetting.edit_history_visible_to_public = false
        sign_in(user)

        get "/posts/#{revised_post.id}/revisions/2.json", params: { include_unlisted: true }
        expect(response.status).to eq(403)

        get "/posts/#{revised_post.id}/revisions/latest.json", params: { include_unlisted: true }
        expect(response.status).to eq(403)
      end
    end

    context "with a tagged topic" do
      let(:tag) { Fabricate(:tag) }

      it "returns tagged topic revisions with tagging enabled or disabled" do
        SiteSetting.tagging_enabled = true

        post_revision.post.topic.update(tags: [tag])

        get "/posts/#{post_revision.post_id}/revisions/latest.json"
        expect(response.status).to eq(200)

        SiteSetting.tagging_enabled = false

        get "/posts/#{post_revision.post_id}/revisions/latest.json"
        expect(response.status).to eq(200)
      end
    end
  end

  describe "#latest_revision" do
    fab!(:post_owner, :user)
    fab!(:revised_post) { Fabricate(:post, user: post_owner, raw: "Initial version") }

    before do
      SiteSetting.edit_history_visible_to_public = true
      SiteSetting.editing_grace_period = 0

      revised_post.revise(post_owner, raw: "Listed version")
      revised_post.revise(post_owner, raw: "Unlisted version")
      revised_post.revisions.find_by(number: 3).unlist!
    end

    it "opens the latest listed revision for non-staff" do
      get "/posts/#{revised_post.id}/revisions/latest.json"

      expect(response.status).to eq(200)
      expect(response.parsed_body).to include("current_revision" => 2, "next_revision" => nil)
    end

    it "opens the latest revision for non-staff who include unlisted revisions" do
      get "/posts/#{revised_post.id}/revisions/latest.json", params: { include_unlisted: true }

      expect(response.status).to eq(200)
      expect(response.parsed_body).to include("current_revision" => 3, "unlisted" => true)
    end

    it "opens the latest revision for staff" do
      sign_in(moderator)

      get "/posts/#{revised_post.id}/revisions/latest.json"

      expect(response.status).to eq(200)
      expect(response.parsed_body["current_revision"]).to eq(3)
    end

    it "falls back to the latest visible revision when no listed revision is left" do
      revised_post.revisions.find_by(number: 2).unlist!
      revised_post.revisions.find_by(number: 3).hide!

      get "/posts/#{revised_post.id}/revisions/latest.json"

      expect(response.status).to eq(200)
      expect(response.parsed_body).to include(
        "current_revision" => 2,
        "last_revision" => 2,
        "unlisted" => true,
      )
    end

    it "opens a loaded revision when the latest listed one is older than the loaded history" do
      (4..102).each do |number|
        Fabricate(:post_revision, post: revised_post, user: post_owner, number:, unlisted: true)
      end

      get "/posts/#{revised_post.id}/revisions/latest.json"

      expect(response.status).to eq(200)
      expect(response.parsed_body).to include("current_revision" => 102, "unlisted" => true)
    end
  end

  describe "#hide_revision" do
    fab!(:revised_post) { Fabricate(:post, version: 2, public_version: 2) }
    fab!(:post_revision) { Fabricate(:post_revision, post: revised_post, unlisted: true) }

    it "clears the unlisted flag when hiding an unlisted revision" do
      sign_in(moderator)

      expect { put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/hide" }.to change {
        revised_post.reload.public_version
      }.by(-1)

      expect(response.status).to eq(200)
      expect(post_revision.reload).to have_attributes(hidden: true, unlisted: false)
    end
  end

  describe "#unlist_revision" do
    fab!(:revised_post) { Fabricate(:post, version: 2) }
    fab!(:post_revision) { Fabricate(:post_revision, post: revised_post) }

    it "only allows staff to unlist a revision" do
      put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/unlist"
      expect(response.status).to eq(403)

      sign_in(user)
      put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/unlist"
      expect(response.status).to eq(403)

      expect(post_revision.reload.unlisted).to eq(false)
    end

    it "unlists the revision" do
      sign_in(moderator)

      put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/unlist"

      expect(response.status).to eq(204)
      expect(post_revision.reload.unlisted).to eq(true)
    end

    it "refuses to unlist a hidden revision" do
      post_revision.hide!
      sign_in(moderator)

      put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/unlist"

      expect(response.status).to eq(422)
      expect(response.parsed_body["errors"]).to contain_exactly(
        I18n.t("cannot_unlist_hidden_revision"),
      )
      expect(post_revision.reload).to have_attributes(hidden: true, unlisted: false)
    end
  end

  describe "#relist_revision" do
    fab!(:revised_post) { Fabricate(:post, version: 2) }
    fab!(:post_revision) { Fabricate(:post_revision, post: revised_post, unlisted: true) }

    it "only allows staff to relist a revision" do
      put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/relist"
      expect(response.status).to eq(403)

      sign_in(user)
      put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/relist"
      expect(response.status).to eq(403)

      expect(post_revision.reload.unlisted).to eq(true)
    end

    it "relists the revision" do
      sign_in(moderator)

      put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/relist"

      expect(response.status).to eq(204)
      expect(post_revision.reload.unlisted).to eq(false)
    end
  end

  describe "#permanently_delete_check" do
    fab!(:post)

    before { SiteSetting.can_permanently_delete = true }

    it "returns 404 for anonymous users" do
      get "/posts/#{post.id}/permanently_delete_check.json"
      expect(response.status).to eq(404)
    end

    it "returns 404 for regular users" do
      sign_in(user)
      get "/posts/#{post.id}/permanently_delete_check.json"
      expect(response.status).to eq(404)
    end

    it "returns 404 for moderators" do
      sign_in(moderator)
      get "/posts/#{post.id}/permanently_delete_check.json"
      expect(response.status).to eq(404)
    end

    context "when logged in as admin" do
      before { sign_in(admin) }

      it "returns can_permanently_delete true when allowed" do
        PostDestroyer.new(Fabricate(:admin), post).destroy

        get "/posts/#{post.id}/permanently_delete_check.json"

        expect(response.status).to eq(200)
        json = response.parsed_body
        expect(json["can_permanently_delete"]).to eq(true)
        expect(json["reason"]).to be_nil
      end

      it "returns the reason when the same admin must wait" do
        freeze_time do
          PostDestroyer.new(admin, post).destroy
          get "/posts/#{post.id}/permanently_delete_check.json"
        end

        expect(response.status).to eq(200)
        json = response.parsed_body
        expect(json["can_permanently_delete"]).to eq(false)
        expect(json["reason"]).to eq(
          I18n.t("post.cannot_permanently_delete.wait_or_different_admin", time_left: "5 minutes"),
        )
      end

      it "returns the reason when topic has undeleted posts" do
        Fabricate(:post, topic: post.topic)
        PostDestroyer.new(Fabricate(:admin), post).destroy

        get "/posts/#{post.id}/permanently_delete_check.json"

        expect(response.status).to eq(200)
        json = response.parsed_body
        expect(json["can_permanently_delete"]).to eq(false)
        expect(json["reason"]).to eq(I18n.t("post.cannot_permanently_delete.many_posts", count: 1))
      end
    end
  end

  describe "#permanently_delete_revisions" do
    before { SiteSetting.can_permanently_delete = true }

    fab!(:post) do
      Fabricate(
        :post,
        user: Fabricate(:user),
        raw: "Lorem ipsum dolor sit amet, cu nam libris tractatos, ancillae senserit ius ex",
      )
    end

    fab!(:post_with_no_revisions) do
      Fabricate(
        :post,
        user: Fabricate(:user),
        raw: "Lorem ipsum dolor sit amet, cu nam libris tractatos, ancillae senserit ius ex",
      )
    end

    fab!(:post_revision) { Fabricate(:post_revision, post: post) }
    fab!(:post_revision_2) { Fabricate(:post_revision, post: post) }

    let(:post_id) { post.id }

    describe "when logged in as a regular user" do
      it "does not delete revisions" do
        sign_in(user)
        delete "/posts/#{post_id}/revisions/permanently_delete.json"
        expect(response).to_not be_successful
      end
    end

    describe "when logged in as staff" do
      before { sign_in(admin) }

      it "fails when post record is not found" do
        delete "/posts/#{post_id + 1}/revisions/permanently_delete.json"
        expect(response).to_not be_successful
      end

      it "fails when no post revisions are found" do
        delete "/posts/#{post_with_no_revisions.id}/revisions/permanently_delete.json"
        expect(response).to_not be_successful
      end

      it "fails when 'can_permanently_delete' setting is false" do
        SiteSetting.can_permanently_delete = false
        delete "/posts/#{post_id}/revisions/permanently_delete.json"
        expect(response).to_not be_successful
      end

      it "permanently deletes revisions from post and adds a staff log" do
        delete "/posts/#{post_id}/revisions/permanently_delete.json"
        expect(response.status).to eq(200)

        # It creates a staff log
        logs =
          UserHistory.find_by(
            action: UserHistory.actions[:permanently_delete_post_revisions],
            acting_user_id: admin.id,
            post_id: post_id,
          )
        expect(logs).to be_present

        # ensure post revisions are deleted
        expect(PostRevision.where(post: post)).to eq([])
      end
    end
  end

  describe "#revert" do
    include_examples "action requires login", :put, "/posts/123/revisions/2/revert.json"

    fab!(:post) do
      Fabricate(
        :post,
        user: Fabricate(:user),
        raw: "Lorem ipsum dolor sit amet, cu nam libris tractatos, ancillae senserit ius ex",
      )
    end
    let(:post_revision) do
      Fabricate(
        :post_revision,
        post: post,
        modifications: {
          "raw" => ["this is original post body.", "this is edited post body."],
        },
      )
    end
    let(:blank_post_revision) do
      Fabricate(
        :post_revision,
        post: post,
        modifications: {
          "edit_reason" => ["edit reason #1", "edit reason #2"],
        },
      )
    end
    let(:same_post_revision) do
      Fabricate(
        :post_revision,
        post: post,
        modifications: {
          "raw" => [
            "Lorem ipsum dolor sit amet, cu nam libris tractatos, ancillae senserit ius ex",
            "this is edited post body.",
          ],
        },
      )
    end
    let(:tag_only_revision) do
      Fabricate(
        :post_revision,
        post: post,
        modifications: {
          "tags" => [%w[tag1 tag2], %w[tag2 tag3]],
        },
      )
    end
    let(:text_number_tags) do
      Fabricate(
        :post_revision,
        post: post,
        modifications: {
          "tags" => [%w[123 tag1 tag2], %w[456 tag3 tag4]],
        },
      )
    end
    let(:legacy_string_tag_revision) do
      Fabricate(
        :post_revision,
        post: post,
        modifications: {
          "tags" => ["tag1, tag2", "tag2, tag3"],
        },
      )
    end

    let(:post_id) { post.id }
    let(:revision_id) { post_revision.number }

    describe "when logged in as a regular user" do
      it "does not work" do
        sign_in(user)
        put "/posts/#{post_id}/revisions/#{revision_id}/revert.json"
        expect(response).to_not be_successful
      end
    end

    describe "when logged in as staff" do
      before { sign_in(moderator) }

      it "fails when revision is < 2" do
        put "/posts/#{post_id}/revisions/1/revert.json"
        expect(response.status).to eq(400)
      end

      it "fails when post_revision record is not found" do
        put "/posts/#{post_id}/revisions/#{revision_id + 1}/revert.json"
        expect(response).to_not be_successful
      end

      it "fails when post record is not found" do
        put "/posts/#{post_id + 1}/revisions/#{revision_id}/revert.json"
        expect(response).to_not be_successful
      end

      it "fails when revision is blank" do
        put "/posts/#{post_id}/revisions/#{blank_post_revision.number}/revert.json"
        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"]).to include(I18n.t("revert_version_same"))
      end

      it "fails when revised version is same as current version" do
        put "/posts/#{post_id}/revisions/#{same_post_revision.number}/revert.json"
        expect(response.status).to eq(422)
        expect(response.parsed_body["errors"]).to include(I18n.t("revert_version_same"))
      end

      it "works!" do
        put "/posts/#{post_id}/revisions/#{revision_id}/revert.json"
        expect(response.status).to eq(200)
      end

      it "supports reverting posts in deleted topics" do
        first_post = post.topic.ordered_posts.first
        PostDestroyer.new(moderator, first_post).destroy

        put "/posts/#{post_id}/revisions/#{revision_id}/revert.json"
        expect(response.status).to eq(200)
      end

      it "supports reverting tag-only revisions" do
        post.topic.tags = Tag.where(name: %w[tag2 tag3])

        put "/posts/#{post_id}/revisions/#{tag_only_revision.number}/revert.json"
        expect(response.status).to eq(200)

        post.topic.reload
        expect(post.topic.tags.pluck(:name).sort).to eq(%w[tag1 tag2])
      end

      it "supports reverting text and number tags" do
        post.topic.tags = Tag.where(name: %w[456 tag3 tag4])

        put "/posts/#{post_id}/revisions/#{text_number_tags.number}/revert.json"
        expect(response.status).to eq(200)

        post.topic.reload
        expect(post.topic.tags.pluck(:name).sort).to eq(%w[123 tag1 tag2])
      end

      it "supports reverting legacy string-format tags" do
        post.topic.tags = Tag.where(name: ["tag2, tag3"])

        put "/posts/#{post_id}/revisions/#{legacy_string_tag_revision.number}/revert.json"
        expect(response.status).to eq(200)

        post.topic.reload
        expect(post.topic.tags.pluck(:name).sort).to eq(%w[tag1 tag2])
      end

      it "supports reverting reply-target-only revisions" do
        earlier_post = Fabricate(:post, topic: post.topic, post_number: post.post_number - 1)
        post.update!(reply_to_post_number: nil)

        reply_to_revision =
          Fabricate(
            :post_revision,
            post: post,
            modifications: {
              "reply_to_post_number" => [earlier_post.post_number, nil],
            },
          )

        put "/posts/#{post_id}/revisions/#{reply_to_revision.number}/revert.json"

        expect(response.status).to eq(200)
        expect(post.reload.reply_to_post_number).to eq(earlier_post.post_number)
      end
    end

    context "when the id is passed as an array" do
      fab!(:accessible_post) { Fabricate(:post, user: moderator) }
      fab!(:inaccessible_post, :private_message_post)
      fab!(:inaccessible_revision) do
        Fabricate(
          :post_revision,
          post: inaccessible_post,
          number: 2,
          modifications: {
            "raw" => ["previous private body", "current private body"],
          },
        )
      end

      before { sign_in(moderator) }

      it "does not revert using a revision the user cannot see on another post" do
        expect(accessible_post.id).to be < inaccessible_post.id
        expect(moderator.guardian.can_see?(inaccessible_post)).to eq(false)

        previous_raw = inaccessible_revision.modifications["raw"][0]

        put "/posts/#{accessible_post.id}/revisions/2/revert.json",
            params: {
              id: [accessible_post.id, inaccessible_post.id],
            }

        expect(response.status).to eq(404)
        expect(response.body).not_to include(previous_raw)
        expect(accessible_post.reload.raw).not_to include(previous_raw)
      end
    end
  end

  describe "#expand_embed" do
    before { sign_in(user) }

    fab!(:post)

    it "raises an error when you can't see the post" do
      post = Fabricate(:private_message_post)
      get "/posts/#{post.id}/expand-embed.json"
      expect(response).not_to be_successful
    end

    it "retrieves the body when you can see the post" do
      TopicEmbed.expects(:expanded_for).with(post).returns("full content")
      get "/posts/#{post.id}/expand-embed.json"
      expect(response.status).to eq(200)
      expect(response.parsed_body["cooked"]).to eq("full content")
    end
  end

  describe "#deleted_posts" do
    include_examples "action requires login", :get, "/posts/system/deleted.json"

    describe "when logged in" do
      it "raises an error if the user doesn't have permission to see the deleted posts" do
        sign_in(user)
        get "/posts/system/deleted.json"
        expect(response).to be_forbidden
      end

      describe "when limit params is invalid" do
        before { sign_in(moderator) }

        include_examples "invalid limit params",
                         "/posts/system/deleted.json",
                         described_class::DELETED_POSTS_MAX_LIMIT
      end

      it "can see the deleted posts when authorized" do
        sign_in(moderator)
        get "/posts/system/deleted.json"
        expect(response.status).to eq(200)
      end

      it "does not raise if topic has been permanently deleted" do
        post = Fabricate(:post, user: admin)
        PostDestroyer.new(admin, post).destroy
        post.update!(topic_id: -1000)

        sign_in(admin)
        get "/posts/#{admin.username}/deleted.json"
        expect(response.status).to eq(200)
      end

      it "doesn't return secured categories for moderators if they don't have access" do
        Fabricate(:moderator)

        group = Fabricate(:group)
        group.add_owner(user)

        secured_category = Fabricate(:private_category, group: group)
        secured_post = create_post(user: user, category: secured_category)
        PostDestroyer.new(admin, secured_post).destroy

        sign_in(moderator)
        get "/posts/#{user.username}/deleted.json"
        expect(response.status).to eq(200)

        data = response.parsed_body
        expect(data.length).to eq(0)
      end

      it "doesn't return PMs for moderators" do
        Fabricate(:moderator)

        pm_post =
          create_post(user: user, archetype: "private_message", target_usernames: [admin.username])
        PostDestroyer.new(admin, pm_post).destroy

        sign_in(moderator)
        get "/posts/#{user.username}/deleted.json"
        expect(response.status).to eq(200)

        data = response.parsed_body
        expect(data.length).to eq(0)
      end

      it "returns PMs for admins who are also moderators" do
        admin.update!(moderator: true)

        pm_post = Fabricate(:private_message_post)
        PostDestroyer.new(admin, pm_post).destroy

        sign_in(admin)

        get "/posts/#{pm_post.user.username}/deleted.json"

        expect(response.status).to eq(200)
        expect(response.parsed_body.size).to eq(1)
        expect(response.parsed_body.first["id"]).to eq(pm_post.id)
      end

      it "only shows posts deleted by other users" do
        create_post(user: user)
        post_deleted_by_user = create_post(user: user)
        post_deleted_by_admin = create_post(user: user)

        PostDestroyer.new(user, post_deleted_by_user).destroy
        PostDestroyer.new(admin, post_deleted_by_admin).destroy

        sign_in(admin)
        get "/posts/#{user.username}/deleted.json"
        expect(response.status).to eq(200)

        data = response.parsed_body
        expect(data.length).to eq(1)
        expect(data[0]["id"]).to eq(post_deleted_by_admin.id)
        expect(data[0]["deleted_by"]["id"]).to eq(admin.id)
      end

      it "denies access to non-staff users in delete_all_posts_and_topics_allowed_groups" do
        group = Fabricate(:group)
        non_staff_user = Fabricate(:user, refresh_auto_groups: true)
        group.add(non_staff_user)
        SiteSetting.delete_all_posts_and_topics_allowed_groups = "1|2|#{group.id}"

        sign_in(non_staff_user)
        get "/posts/#{user.username}/deleted.json"
        expect(response).to be_forbidden
      end
    end
  end

  describe "#markdown_id" do
    it "can be viewed by anonymous" do
      post = Fabricate(:post, raw: "123456789")
      get "/posts/#{post.id}/raw.json"
      expect(response.status).to eq(200)
      expect(response.body).to eq("123456789")
    end

    it "renders a 404 page" do
      get "/posts/0/raw"
      expect(response.status).to eq(404)
      expect(response.body).to include(I18n.t("page_not_found.title"))
    end
  end

  describe "#markdown_num" do
    it "can be viewed by anonymous" do
      topic = Fabricate(:topic)
      post = Fabricate(:post, topic: topic, post_number: 1, raw: "123456789")
      post.save
      get "/raw/#{topic.id}/1.json"
      expect(response.status).to eq(200)
      expect(response.body).to eq("123456789")
    end

    it "can show whole topics" do
      topic = Fabricate(:topic)
      post = Fabricate(:post, topic: topic, post_number: 1, raw: "123456789")
      _post_2 = Fabricate(:post, topic: topic, post_number: 2, raw: "abcdefghij")
      post.save
      get "/raw/#{topic.id}"
      expect(response.status).to eq(200)
      expect(response.body).to include("123456789", "abcdefghij")
    end

    context "with a hidden post revision" do
      before do
        SiteSetting.edit_history_visible_to_public = true
        SiteSetting.editing_grace_period = 0
      end

      it "prevents anonymous access while allowing staff to fetch a visible raw revision after a hidden revision" do
        post = Fabricate(:post, raw: "Initial public version")
        hidden_raw = "moderator-redacted secret"
        visible_raw = "Visible version"
        post.revise(post.user, raw: hidden_raw)
        hidden_revision = post.revisions.find_by(number: 2)
        hidden_revision.hide!
        post.revise(post.user, raw: visible_raw)

        get "/raw/#{post.topic_id}/#{post.post_number}", params: { revision: 3 }

        aggregate_failures do
          expect(response).to be_forbidden
          expect(response.body).not_to include(hidden_raw)
        end

        sign_in(moderator)
        get "/raw/#{post.topic_id}/#{post.post_number}", params: { revision: 3 }

        aggregate_failures do
          expect(response).to have_http_status(:ok)
          expect(response.body).to eq(visible_raw)
        end
      end
    end

    context "with a hidden post" do
      fab!(:topic)
      fab!(:visible_post) do
        Fabricate(:post, topic: topic, post_number: 1, raw: "visible post content")
      end
      fab!(:hidden_post) do
        Fabricate(:post, topic: topic, post_number: 2, raw: "hidden post content", hidden: true)
      end
      fab!(:post_author) { hidden_post.user }

      before { SiteSetting.hidden_post_visible_groups = Group::AUTO_GROUPS[:trust_level_4] }

      context "when fetching a single hidden post" do
        context "when logged out" do
          it "returns not found" do
            get "/raw/#{topic.id}/#{hidden_post.post_number}"
            expect(response).to have_http_status(:not_found)
          end
        end

        context "when logged in as a regular user" do
          before { sign_in(user) }

          it "returns not found" do
            get "/raw/#{topic.id}/#{hidden_post.post_number}"
            expect(response).to have_http_status(:not_found)
          end
        end

        context "when logged in as the post author" do
          before { sign_in(post_author) }

          it "returns the hidden post content" do
            get "/raw/#{topic.id}/#{hidden_post.post_number}"
            expect(response.body).to eq("hidden post content")
          end
        end

        context "when logged in as a moderator" do
          before { sign_in(moderator) }

          it "returns the hidden post content" do
            get "/raw/#{topic.id}/#{hidden_post.post_number}"
            expect(response.body).to eq("hidden post content")
          end
        end
      end

      context "when fetching the whole topic" do
        context "when logged out" do
          it "excludes hidden post content" do
            get "/raw/#{topic.id}"
            expect(response.body).to include("visible post content").and exclude(
                    "hidden post content",
                  )
          end
        end

        context "when logged in as a regular user" do
          before { sign_in(user) }

          it "excludes hidden post content" do
            get "/raw/#{topic.id}"
            expect(response.body).to include("visible post content").and exclude(
                    "hidden post content",
                  )
          end
        end

        context "when logged in as the post author" do
          before { sign_in(post_author) }

          it "includes hidden post content" do
            get "/raw/#{topic.id}"
            expect(response.body).to include("visible post content", "hidden post content")
          end
        end

        context "when logged in as a moderator" do
          before { sign_in(moderator) }

          it "includes hidden post content" do
            get "/raw/#{topic.id}"
            expect(response.body).to include("visible post content", "hidden post content")
          end
        end
      end
    end
  end

  describe "#short_link" do
    fab!(:topic)
    fab!(:post) { Fabricate(:post, topic: topic) }

    it "redirects to the topic" do
      get "/p/#{post.id}.json"
      expect(response).to be_redirect
    end

    it "returns a 403 when access is denied for JSON format" do
      post = Fabricate(:private_message_post)
      get "/p/#{post.id}.json"
      expect(response).to be_forbidden
    end

    it "returns a 403 when access is denied for HTML format" do
      post = Fabricate(:private_message_post)
      get "/p/#{post.id}"
      expect(response).to be_forbidden
      expect(response.body).to have_tag("body.no-ember")
    end

    it "renders a 404 page" do
      get "/p/0"
      expect(response.status).to eq(404)
      expect(response.body).to include(I18n.t("page_not_found.title"))
    end
  end

  describe "#user_posts_feed" do
    before { user.user_stat.update!(post_count: 1) }

    it "returns public posts rss feed" do
      public_post
      private_post

      get "/u/#{user.username}/activity.rss"

      expect(response.status).to eq(200)

      body = response.body

      expect(body).to_not include(private_post.url)
      expect(body).to include(public_post.url)
    end

    it "doesn't include posts from hidden topics" do
      public_post.topic.update!(visible: false)

      get "/u/#{user.username}/activity.rss"

      expect(response.status).to eq(200)

      body = response.body
      expect(body).not_to include(public_post.url)
    end

    it "excludes small actions" do
      small_action = Fabricate(:small_action, user: user)

      get "/u/#{user.username}/activity.rss"

      expect(response.status).to eq(200)

      body = response.body

      expect(body).not_to include(small_action.canonical_url)
    end

    it "returns public posts as JSON" do
      public_post
      private_post

      get "/u/#{user.username}/activity.json"

      expect(response.status).to eq(200)

      body = response.body

      expect(body).to_not include(private_post.topic.slug)
      expect(body).to include(public_post.topic.slug)
    end

    it "does not disclose a user's posts when public profiles are hidden" do
      public_post
      SiteSetting.hide_user_profiles_from_public = true

      %w[rss json].each do |format|
        get "/u/#{user.username}/activity.#{format}"

        expect(response).to have_http_status(:not_found)
        expect(response.body).not_to include(public_post.raw)
      end
    end

    it "excludes ignored users' likes from JSON like counts" do
      viewer = Fabricate(:user, refresh_auto_groups: true)
      ignored_liker = Fabricate(:user, refresh_auto_groups: true)
      regular_liker = Fabricate(:user, refresh_auto_groups: true)
      PostActionCreator.like(ignored_liker, public_post)
      PostActionCreator.like(regular_liker, public_post)
      Fabricate(:ignored_user, user: viewer, ignored_user: ignored_liker)
      sign_in(viewer)

      get "/u/#{user.username}/activity.json"

      post_json = response.parsed_body.find { |post| post["id"] == public_post.id }
      like_summary =
        post_json["actions_summary"].find { |action| action["id"] == PostActionType.types[:like] }
      expect(like_summary["count"]).to eq(1)
    end

    it "returns 404 if `hide_profile` user option is checked" do
      user.user_option.update_columns(hide_profile: true)

      get "/u/#{user.username}/activity.rss"
      expect(response.status).to eq(404)

      get "/u/#{user.username}/activity.json"
      expect(response.status).to eq(404)
    end

    it "succeeds when `allow_users_to_hide_profile` is false" do
      user.user_option.update_columns(hide_profile: true)
      SiteSetting.allow_users_to_hide_profile = false

      get "/u/#{user.username}/activity.rss"
      expect(response.status).to eq(200)

      get "/u/#{user.username}/activity.json"
      expect(response.status).to eq(200)
    end
  end

  describe "#latest" do
    it "returns the translated excerpt" do
      viewer = Fabricate(:user, locale: "ja")
      SiteSetting.content_localization_enabled = true
      post = Fabricate(:post, raw: "Original post body", locale: "en")
      Fabricate(:post_localization, post: post, locale: "ja", cooked: "<p>翻訳された本文</p>")

      sign_in(viewer)
      get "/posts.json"

      expect(response.parsed_body["latest_posts"].first["excerpt"]).to eq("翻訳された本文")
    end

    context "with private posts" do
      describe "when not logged in" do
        it "returns 404 and the private posts login form" do
          Fabricate(:post)

          get "/private-posts.rss"

          expect(response.status).to eq(404)

          expect(response.body).to have_tag("input", with: { value: "private_posts" })
        end
      end

      it "returns private posts rss feed" do
        sign_in(admin)

        public_post
        private_post
        get "/private-posts.rss"

        expect(response.status).to eq(200)

        body = response.body

        expect(body).to include(private_post.url)
        expect(body).to_not include(public_post.url)
      end

      it "properly secures private posts" do
        sign_in(user)

        private_post

        pm = Fabricate(:private_message_topic, recipient: user)
        post_id = Fabricate(:post, topic: pm).id

        get "/private-posts.json"
        expect(response.status).to eq(200)

        json = response.parsed_body
        post_ids = json["private_posts"].map { |p| p["id"] }

        expect(post_ids).to eq([post_id])
      end

      it "does not include whisper posts for non-whisperer users" do
        sign_in(user)

        pm = Fabricate(:private_message_topic, recipient: user)
        regular_post = Fabricate(:post, topic: pm)
        whisper_post = Fabricate(:post, topic: pm, post_type: Post.types[:whisper])

        get "/private-posts.json"
        expect(response.status).to eq(200)

        json = response.parsed_body
        post_ids = json["private_posts"].map { |p| p["id"] }

        expect(post_ids).to include(regular_post.id)
        expect(post_ids).to_not include(whisper_post.id)
      end

      it "returns private posts for json" do
        sign_in(admin)

        public_post
        private_post
        get "/private-posts.json"
        expect(response.status).to eq(200)

        json = response.parsed_body
        post_ids = json["private_posts"].map { |p| p["id"] }

        expect(post_ids).to include private_post.id
        expect(post_ids).to_not include public_post.id
      end
    end

    context "with public posts" do
      it "caches paginated results for anonymous users" do
        public_post
        global_setting :anon_cache_store_threshold, 1
        Middleware::AnonymousCache.enable_anon_cache
        Middleware::AnonymousCache.clear_all_cache!

        get "/posts.json", params: { before: public_post.id + 1 }
        expect(response.headers["X-Discourse-Cached"]).to eq("store")

        get "/posts.json", params: { before: public_post.id + 1 }
        expect(response.headers["X-Discourse-Cached"]).to eq("true")
      end

      it "returns public posts with topic rss feed" do
        public_post
        private_post

        get "/posts.rss"

        expect(response.status).to eq(200)

        body = response.body

        # we cache in redis, in rare cases this can cause a flaky test
        PostsHelper.clear_canonical_cache!(public_post)

        expect(body).to include(public_post.canonical_url)
        expect(body).to_not include(private_post.url)
      end

      it "doesn't include posts from secured categories you have no access to" do
        public_post
        private_post

        category = Fabricate(:category, read_restricted: true)
        topic = Fabricate(:topic, category: category)
        secure_post = Fabricate(:post, topic: topic)

        get "/posts.json"

        expect(response.status).to eq(200)

        body = response.parsed_body
        ids = body["latest_posts"].map { |p| p["id"] }

        expect(ids).not_to include secure_post.id
      end

      it "doesn't include posts from hidden topics" do
        public_post.topic.update!(visible: false)

        get "/posts.rss"

        expect(response.status).to eq(200)

        body = response.body

        # we cache in redis, in rare cases this can cause a flaky test
        PostsHelper.clear_canonical_cache!(public_post)

        expect(body).not_to include(public_post.canonical_url)
      end

      it "excludes small actions" do
        small_action = Fabricate(:small_action)

        get "/posts.rss"

        expect(response.status).to eq(200)

        body = response.body

        expect(body).not_to include(small_action.canonical_url)
      end

      it "returns public posts with topic for json" do
        topicless_post.update topic_id: -100

        public_post
        private_post
        topicless_post

        get "/posts.json"
        expect(response.status).to eq(200)

        json = response.parsed_body
        post_ids = json["latest_posts"].map { |p| p["id"] }

        expect(post_ids).to include public_post.id
        expect(post_ids).to_not include private_post.id
        expect(post_ids).to_not include topicless_post.id
      end

      it "excludes ignored users' likes from json like counts" do
        viewer = Fabricate(:user, refresh_auto_groups: true)
        ignored_liker = Fabricate(:user, refresh_auto_groups: true)
        regular_liker = Fabricate(:user, refresh_auto_groups: true)
        PostActionCreator.like(ignored_liker, public_post)
        PostActionCreator.like(regular_liker, public_post)
        Fabricate(:ignored_user, user: viewer, ignored_user: ignored_liker)
        sign_in(viewer)

        get "/posts.json"

        post_json =
          response.parsed_body["latest_posts"].find { |post| post["id"] == public_post.id }
        like_summary =
          post_json["actions_summary"].find { |action| action["id"] == PostActionType.types[:like] }
        expect(like_summary["count"]).to eq(1)
      end
    end
  end

  describe "#cooked" do
    it "returns the cooked content" do
      post = Fabricate(:post, cooked: "WAt")
      get "/posts/#{post.id}/cooked.json"

      expect(response.status).to eq(200)
      json = response.parsed_body

      expect(json).to be_present
      expect(json["cooked"]).to eq("WAt")
    end
  end

  describe "#raw_email" do
    include_examples "action requires login", :get, "/posts/2/raw-email.json"

    describe "when logged in" do
      let(:post) do
        Fabricate(
          :post,
          deleted_at: 2.hours.ago,
          user: Fabricate(:user),
          raw_email: "email_content",
        )
      end

      it "returns 403 when trying to view raw as user that created the post" do
        sign_in(post.user)

        get "/posts/#{post.id}/raw-email.json"
        expect(response.status).to eq(403)
      end

      it "returns 403 when trying to view raw email as a normal user" do
        sign_in(user)

        get "/posts/#{post.id}/raw-email.json"
        expect(response.status).to eq(403)
      end

      it "blocks raw email for unseen private messages" do
        raw_email = "From: [email protected]\nTo: [email protected]\n\nsecret body"
        private_message_post =
          Fabricate(
            :private_message_post,
            user: user,
            recipient: Fabricate(:user),
            raw_email: raw_email,
          )
        sign_in(moderator)

        get "/posts/#{private_message_post.id}/raw-email.json"

        expect(response.status).to eq(403)
        expect(response.body).not_to include(raw_email)
      end

      it "blocks deleted raw email for allowed non-staff users" do
        sign_in(user)
        SiteSetting.view_raw_email_allowed_groups = "trust_level_0"

        get "/posts/#{post.id}/raw-email.json"

        expect(response.status).to eq(403)
        expect(response.body).not_to include(post.raw_email)
      end

      it "can view raw email if the user is in the allowed group" do
        allowed_post = Fabricate(:post, user: Fabricate(:user), raw_email: "email_content")
        sign_in(user)
        SiteSetting.view_raw_email_allowed_groups = "trust_level_0"

        get "/posts/#{allowed_post.id}/raw-email.json"
        expect(response.status).to eq(200)

        json = response.parsed_body
        expect(json["raw_email"]).to eq("email_content")
      end

      it "can view raw email" do
        sign_in(moderator)

        get "/posts/#{post.id}/raw-email.json"
        expect(response.status).to eq(200)

        json = response.parsed_body
        expect(json["raw_email"]).to eq("email_content")
      end
    end
  end

  describe "#locked" do
    before { sign_in(moderator) }

    it "can lock and unlock the post" do
      put "/posts/#{public_post.id}/locked.json", params: { locked: "true" }
      expect(response.status).to eq(200)
      public_post.reload
      expect(public_post).to be_locked

      put "/posts/#{public_post.id}/locked.json", params: { locked: "false" }
      expect(response.status).to eq(200)
      public_post.reload
      expect(public_post).not_to be_locked
    end
  end

  describe "#notice" do
    it "can create and remove notices as a moderator" do
      sign_in(moderator)

      raw_notice = "Hello *world*!\n\nhttps://github.com/discourse/discourse"
      put "/posts/#{public_post.id}/notice.json", params: { notice: raw_notice }

      expect(response.status).to eq(200)
      expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(
        "type" => Post.notices[:custom],
        "raw" => raw_notice,
        "cooked" => PrettyText.cook(raw_notice, features: { onebox: false }),
        "created_by_user_id" => moderator.id,
      )
      expect(UserHistory.where(action: UserHistory.actions[:post_staff_note_create]).count).to eq(1)

      put "/posts/#{public_post.id}/notice.json", params: { notice: nil }

      expect(response.status).to eq(200)
      expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(nil)
      expect(UserHistory.where(action: UserHistory.actions[:post_staff_note_destroy]).count).to eq(
        1,
      )
    end

    describe "group moderators" do
      fab!(:group_user)
      let(:user) { group_user.user }
      let(:group) { group_user.group }

      before do
        SiteSetting.enable_category_group_moderation = true
        Fabricate(:category_moderation_group, category: topic.category, group:)

        sign_in(user)
      end

      it "can create and remove notices as a group moderator" do
        raw_notice = "Hello *world*!\n\nhttps://github.com/discourse/discourse"
        put "/posts/#{public_post.id}/notice.json", params: { notice: raw_notice }

        expect(response.status).to eq(200)
        expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(
          "type" => Post.notices[:custom],
          "raw" => raw_notice,
          "cooked" => PrettyText.cook(raw_notice, features: { onebox: false }),
          "created_by_user_id" => user.id,
        )

        put "/posts/#{public_post.id}/notice.json", params: { notice: nil }

        expect(response.status).to eq(200)
        expect(public_post.reload.custom_fields[Post::NOTICE]).to eq(nil)
      end

      it "prevents a group moderator from altering notes outside of their category" do
        topic.category.category_moderation_groups.where(group:).delete_all

        put "/posts/#{public_post.id}/notice.json", params: { notice: "Hello" }

        expect(response.status).to eq(404)
      end

      it "prevents a normal user from altering notes" do
        group_user.destroy!
        put "/posts/#{public_post.id}/notice.json", params: { notice: "Hello" }

        expect(response.status).to eq(404)
      end
    end
  end

  describe "#pending" do
    subject(:request) { get "/posts/#{user.username}/pending.json" }

    context "when user is not logged in" do
      it_behaves_like "action requires login", :get, "/posts/system/pending.json"
    end

    context "when user is logged in" do
      let(:pending_posts) { response.parsed_body["pending_posts"] }

      before { sign_in(current_user) }

      context "when current user is the same as user" do
        let(:current_user) { user }

        context "when there are existing pending posts" do
          let!(:owner_pending_posts) do
            Fabricate.times(2, :reviewable_queued_post, created_by: user)
          end
          let!(:other_pending_post) { Fabricate(:reviewable_queued_post) }
          let(:expected_keys) do
            %w[
              avatar_template
              category_id
              created_at
              created_by_id
              name
              raw_text
              title
              topic_id
              topic_url
              username
            ]
          end

          it "returns user's pending posts" do
            request
            expect(pending_posts).to all include "id" => be_in(owner_pending_posts.map(&:id))
            expect(pending_posts).to all include(*expected_keys)
          end
        end

        context "when there aren't any pending posts" do
          it "returns an empty array" do
            request
            expect(pending_posts).to be_empty
          end
        end
      end

      context "when current user is a staff member" do
        let(:current_user) { moderator }

        context "when there are existing pending posts" do
          let!(:owner_pending_posts) do
            Fabricate.times(2, :reviewable_queued_post, created_by: user)
          end
          let!(:other_pending_post) { Fabricate(:reviewable_queued_post) }
          let(:expected_keys) do
            %w[
              avatar_template
              category_id
              created_at
              created_by_id
              name
              raw_text
              title
              topic_id
              topic_url
              username
            ]
          end

          it "returns user's pending posts" do
            request
            expect(pending_posts).to all include "id" => be_in(owner_pending_posts.map(&:id))
            expect(pending_posts).to all include(*expected_keys)
          end
        end

        context "when there aren't any pending posts" do
          it "returns an empty array" do
            request
            expect(pending_posts).to be_empty
          end
        end
      end

      context "when current user is another user" do
        let(:current_user) { Fabricate(:user) }

        it "does not allow access" do
          request
          expect(response).to have_http_status :not_found
        end
      end
    end
  end

  describe Plugin::Instance do
    describe "#add_permitted_post_create_param" do
      fab!(:user)
      let(:instance) { Plugin::Instance.new }
      let(:request) do
        Proc.new do
          post "/posts.json",
               params: {
                 raw: "this is the test content",
                 title: "this is the test title for the topic",
                 composer_open_duration_msecs: 204,
                 typing_duration_msecs: 100,
                 reply_to_post_number: 123,
                 string_arg: "123",
                 hash_arg: {
                   key1: "val",
                 },
                 array_arg: %w[1 2 3],
               }
        end
      end

      before do
        sign_in(user)
        SiteSetting.fast_typing_threshold = "disabled"
      end

      it "allows strings to be added" do
        request.call
        expect(@controller.send(:create_params)).not_to include(string_arg: "123")

        instance.add_permitted_post_create_param(:string_arg)
        request.call
        expect(@controller.send(:create_params)).to include(string_arg: "123")
      end

      it "allows hashes to be added" do
        instance.add_permitted_post_create_param(:hash_arg)
        request.call
        expect(@controller.send(:create_params)).not_to include(hash_arg: { key1: "val" })

        instance.add_permitted_post_create_param(:hash_arg, :hash)
        request.call
        expect(@controller.send(:create_params)).to include(hash_arg: { key1: "val" })
      end

      it "allows arrays to be added" do
        instance.add_permitted_post_create_param(:array_arg)
        request.call
        expect(@controller.send(:create_params)).not_to include(array_arg: %w[1 2 3])

        instance.add_permitted_post_create_param(:array_arg, :array)
        request.call
        expect(@controller.send(:create_params)).to include(array_arg: %w[1 2 3])
      end
    end
  end
end