Skip to content

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

FIX: Cap tag CSV uploads at 5000 rows

Régis Hanol2fda41c15651
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
index 2c0e200ca79..9a3d1933fb9 100644
--- a/app/controllers/tags_controller.rb
+++ b/app/controllers/tags_controller.rb
@@ -4,6 +4,8 @@ class TagsController < ::ApplicationController
include TopicListResponder
include TopicQueryParams
+ MAX_CSV_ROWS = 5_000
+
before_action :ensure_tags_enabled
def self.show_methods
@@ -304,8 +306,18 @@ class TagsController < ::ApplicationController
file = params[:file] || params[:files].first
hijack do
+ rows = 0
+
Tag.transaction do
CSV.foreach(file.tempfile) do |row|
+ rows += 1
+
+ if rows > MAX_CSV_ROWS
+ raise Discourse::InvalidParameters.new(
+ I18n.t("tags.upload_too_many_rows", count: MAX_CSV_ROWS),
+ )
+ end
+
if row.length > 2
raise Discourse::InvalidParameters.new(I18n.t("tags.upload_row_too_long"))
end
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index b91332c7e93..e3e9058ff96 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -6039,6 +6039,9 @@ en:
one: "You can apply up to %{count} tag to a topic."
other: "You can apply up to %{count} tags to a topic."
upload_row_too_long: "The CSV file should have one tag per line. Optionally the tag can be followed by a comma, then the tag group name."
+ upload_too_many_rows:
+ one: "Too many rows in the CSV file. Please upload no more than %{count} row at a time."
+ other: "Too many rows in the CSV file. Please upload no more than %{count} rows at a time."
bulk_create:
invalid_params: "Invalid parameters. Please provide an array of tag names."
invalid_name: "Invalid tag name."
diff --git a/spec/requests/tags_controller_spec.rb b/spec/requests/tags_controller_spec.rb
index cd410881b4e..6096c342f63 100644
--- a/spec/requests/tags_controller_spec.rb
+++ b/spec/requests/tags_controller_spec.rb
@@ -2397,6 +2397,21 @@ RSpec.describe TagsController do
expect(response.status).to eq(422)
end.not_to change { [Tag.count, TagGroup.count] }
end
+
+ it "fails if the CSV has too many rows" do
+ sign_in(moderator)
+
+ expect do
+ stub_const(TagsController, "MAX_CSV_ROWS", 2) do
+ post "/tags/upload.json", params: { file: file, name: filename }
+ end
+ end.not_to change { [Tag.count, TagGroup.count] }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to contain_exactly(
+ I18n.t("tags.upload_too_many_rows", count: 2),
+ )
+ end
end
end