Skip to content

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

SECURITY: Add maximum length limit for `new_username` param

Penar Musaraje4dc4c3b85d1
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index 8a8399670c0..e36b91e9dfc 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -265,6 +265,11 @@ class UsersController < ApplicationController
def username
params.require(:new_username)
+ # Fast fail for usernames exceeding hardcoded max length
+ if params[:new_username].length > UsernameValidator::MAX_CHARS * 3
+ return render_json_error(I18n.t("user.username.long", count: SiteSetting.max_username_length))
+ end
+
if clashing_with_existing_route?(params[:new_username]) ||
(User.reserved_username?(params[:new_username]) && !current_user.admin?)
return render_json_error(I18n.t("login.reserved_username"))
diff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rb
index 3078eafb2b9..2219b02e041 100644
--- a/spec/requests/users_controller_spec.rb
+++ b/spec/requests/users_controller_spec.rb
@@ -2010,6 +2010,19 @@ RSpec.describe UsersController do
expect(user.reload.username).to eq(old_username)
end
+ it "raises an error when new_username exceeds maximum length" do
+ put "/u/#{user.username}/preferences/username.json",
+ params: {
+ new_username: "a" * ((UsernameValidator::MAX_CHARS * 3) + 1),
+ }
+
+ expect(response).to be_unprocessable
+ expect(response.parsed_body["errors"].first).to include(
+ I18n.t("user.username.long", count: SiteSetting.max_username_length),
+ )
+ expect(user.reload.username).to eq(old_username)
+ end
+
it "should succeed in normal circumstances" do
put "/u/#{user.username}/preferences/username.json", params: { new_username: new_username }