A platform for community discussion. Free, open, simple.
FIX: Block restricted code signups before OTP (#43101)
Keegan George5cf6cdeae68f
diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rbindex 3bfb978b2b8..1dda8c28d6c 100644--- a/app/controllers/session_controller.rb+++ b/app/controllers/session_controller.rb@@ -502,8 +502,13 @@ class SessionController < ApplicationController# the behavior for emails we refuse to deliver to.return render json: success_json if login_code_honeypot_fails?- EmailLoginCode::Request.call(service_params) do |result|+ EmailLoginCode::Request.call(+ service_params.deep_merge(ip_address: request.remote_ip),+ ) do |result|on_success { render json: success_json }+ on_failed_policy(:can_register_from_ip) do+ render json: login_code_registration_ip_limit_error+ endon_failed_contract do |contract|render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_requestend@@ -1029,6 +1034,15 @@ class SessionController < ApplicationController{ error: I18n.t("email_login_code.invalid_code") }end+ def login_code_registration_ip_limit_error+ {+ error:+ I18n.t(+ "activerecord.errors.models.user.attributes.ip_address.max_new_accounts_per_registration_ip",+ ),+ }+ end+def login_code_account_error(user)ip_error =user.errors.find do |error|@@ -1036,11 +1050,7 @@ class SessionController < ApplicationControllererror.type.in?(%i[blocked max_new_accounts_per_registration_ip])end- if ip_error- { error: I18n.t("email_login_code.account_creation_failed") }- else- invalid_login_code- end+ ip_error ? { error: ip_error.message } : invalid_login_codeenddef invalid_credentialsdiff --git a/app/services/email_login_code/request.rb b/app/services/email_login_code/request.rbindex ece46a89e61..dbb29f19893 100644--- a/app/services/email_login_code/request.rb+++ b/app/services/email_login_code/request.rb@@ -5,6 +5,7 @@ class EmailLoginCode::Requestparams doattribute :email, :string+ attribute :signup, :boolean, default: falsebefore_validation { self.email = email.to_s.strip.downcase }@@ -18,6 +19,7 @@ class EmailLoginCode::Request}end+ only_if(:signup?) { policy :can_register_from_ip }model :user, optional: trueonly_if(:existing_account?) { step :trigger_before_email_login }@@ -28,6 +30,14 @@ class EmailLoginCode::Requestprivate+ def signup?(params:)+ params.signup+ end++ def can_register_from_ip(ip_address:)+ !SpamHandler.should_prevent_registration_from_ip?(ip_address)+ end+def fetch_user(params:)User.real.where(staged: false).with_email(params.email).firstenddiff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 4d68fb3cfae..7798de43688 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1098,7 +1098,6 @@ en:email_login_code:invalid_code: "That code is incorrect or has expired. Request a new code and try again."- account_creation_failed: "We couldn't create your account. Please try again later or contact a staff member."browsers:android_browser: "Android Browser"diff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjsindex e1101474526..dfc6ecd0501 100644--- a/frontend/discourse/app/components/code-login-form.gjs+++ b/frontend/discourse/app/components/code-login-form.gjs@@ -567,15 +567,21 @@ export default class CodeLoginForm extends Component {try {const honeypot = await ajax("/session/hp.json");- await ajax("/session/login-code", {+ const result = await ajax("/session/login-code", {type: "POST",data: {email: this.email,+ signup: this.isSignup,password_confirmation: honeypot.value,challenge: honeypot.challenge.split("").reverse().join(""),},});+ if (result?.error) {+ this.codeError = result.error;+ return false;+ }+this.step = "code";this.startResendCooldown();return true;@@ -679,6 +685,12 @@ export default class CodeLoginForm extends Component {<field.Control autofocus="autofocus" autocomplete="username" /></form.Field>+ {{#if this.codeError}}+ <div class="code-login-form__error" aria-live="polite" role="alert">+ {{this.codeError}}+ </div>+ {{/if}}+<div class="code-login-form__email-actions"><form.Submit@label="code_login.continue_button"diff --git a/frontend/discourse/tests/integration/components/code-login-form-test.gjs b/frontend/discourse/tests/integration/components/code-login-form-test.gjsindex cbc3c839047..17a58a21170 100644--- a/frontend/discourse/tests/integration/components/code-login-form-test.gjs+++ b/frontend/discourse/tests/integration/components/code-login-form-test.gjs@@ -62,6 +62,56 @@ module("Integration | Component | CodeLoginForm", function (hooks) {assert.dom(".code-login-form__resend").exists();});+ test("signup requests declare their intent", async function (assert) {+ let signup;+ pretender.get("/session/hp.json", () =>+ response({ value: "hp-value", challenge: "abc", expires_in: 300 })+ );+ pretender.post("/session/login-code", (request) => {+ signup = new URLSearchParams(request.requestBody).get("signup");+ return response({ success: "OK" });+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();++ assert.strictEqual(signup, "true", "the request identifies signup intent");+ assert+ .dom(".code-login-form__code-step")+ .exists("the form advances after the request succeeds");+ });++ test("shows a request error without advancing to the code step", async function (assert) {+ const error =+ "New registrations are not allowed from your IP address (maximum limit reached). Contact a staff member.";+ pretender.get("/session/hp.json", () =>+ response({ value: "hp-value", challenge: "abc", expires_in: 300 })+ );+ pretender.post("/session/login-code", () => response({ error }));++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();++ assert+ .dom(".code-login-form__email-step")+ .exists("the email step remains visible");+ assert+ .dom(".code-login-form__error")+ .hasText(error, "the account limit error is shown inline");+ assert+ .dom(".code-login-form__code-step")+ .doesNotExist("the code step is not rendered");+ assert.dom(".d-otp-input").doesNotExist("the code input is not rendered");+ });+test("keeps a hidden email field for password managers after the email step", async function (assert) {stubCodeRequest();diff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rbindex d12bb48ff9c..43afc71c3da 100644--- a/spec/requests/session_controller_spec.rb+++ b/spec/requests/session_controller_spec.rb@@ -657,6 +657,56 @@ RSpec.describe SessionController doexpect(response.body).to eq(existing_email_body)end+ context "when the signup IP has reached the account limit" do+ let(:ip_address) { "192.0.2.1" }++ before do+ Fabricate(:user, ip_address:, trust_level: TrustLevel[0])+ SiteSetting.max_new_accounts_per_registration_ip = 1+ end++ it "returns the account limit error without sending a code for any email" do+ expect_not_enqueued_with(job: :send_email_login_code) do+ post "/session/login-code.json",+ params: honeypot_magic(email: user.email, signup: true),+ env: {+ REMOTE_ADDR: ip_address,+ }+ existing_email_response = response.parsed_body++ post "/session/login-code.json",+ params: honeypot_magic(email: "[email protected]", signup: true),+ env: {+ REMOTE_ADDR: ip_address,+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body).to eq(existing_email_response)+ expect(response.parsed_body["error"]).to eq(+ I18n.t(+ "activerecord.errors.models.user.attributes.ip_address.max_new_accounts_per_registration_ip",+ ),+ )+ end++ expect(EmailLoginCode.count).to eq(0)+ end++ it "continues to send login codes for existing accounts" do+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: user.email }) do+ post "/session/login-code.json",+ params: honeypot_magic(email: user.email, signup: false),+ env: {+ REMOTE_ADDR: ip_address,+ }+ end++ expect(response.status).to eq(200)+ expect(response.parsed_body["success"]).to eq("OK")+ expect(EmailLoginCode.for_email(user.email).count).to eq(1)+ end+ end+context "when rate limited" dobefore { RateLimiter.enable }@@ -976,7 +1026,9 @@ RSpec.describe SessionController doexpect(response.status).to eq(200)expect(response.parsed_body["error"]).to eq(- I18n.t("email_login_code.account_creation_failed"),+ I18n.t(+ "activerecord.errors.models.user.attributes.ip_address.max_new_accounts_per_registration_ip",+ ),)expect(User.find_by_email("[email protected]")).to be_nilexpect(session[:current_user_id]).to be_nildiff --git a/spec/services/email_login_code/request_spec.rb b/spec/services/email_login_code/request_spec.rbindex 3f8b83811f7..f996db687bc 100644--- a/spec/services/email_login_code/request_spec.rb+++ b/spec/services/email_login_code/request_spec.rb@@ -6,6 +6,12 @@ RSpec.describe EmailLoginCode::Request doit { is_expected.to validate_length_of(:email).is_at_most(513) }it { is_expected.to allow_values("[email protected]", "[email protected]").for(:email) }it { is_expected.not_to allow_values("not-an-email", "foo@").for(:email) }++ it "defaults signup to false and coerces string booleans" do+ expect(described_class.new(email: "[email protected]").signup).to be(false)+ expect(described_class.new(email: "[email protected]", signup: "true").signup).to be(true)+ expect(described_class.new(email: "[email protected]", signup: "false").signup).to be(false)+ endenddescribe ".call" do@@ -23,6 +29,44 @@ RSpec.describe EmailLoginCode::Request doit { is_expected.to fail_a_contract }end+ context "when the signup IP has reached the account limit" do+ let(:email) { "[email protected]" }+ let(:ip_address) { "192.0.2.1" }+ let(:dependencies) { { ip_address: } }+ let(:params) { { email:, signup: "true" } }++ before do+ Fabricate(:user, ip_address:, trust_level: TrustLevel[0])+ SiteSetting.max_new_accounts_per_registration_ip = 1+ end++ it { is_expected.to fail_a_policy(:can_register_from_ip) }++ it "does not generate or enqueue a login code" do+ expect_not_enqueued_with(job: :send_email_login_code) { result }++ expect(EmailLoginCode.for_email(email)).to be_empty+ end+ end++ context "when a login IP has reached the account limit" do+ let(:ip_address) { "192.0.2.1" }+ let(:dependencies) { { ip_address: } }+ let(:params) { { email:, signup: "false" } }++ before do+ Fabricate(:user, ip_address:, trust_level: TrustLevel[0])+ SiteSetting.max_new_accounts_per_registration_ip = 1+ end++ it "generates and enqueues a login code for an existing account" do+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: email }) { result }++ expect(result).to run_successfully+ expect(EmailLoginCode.for_email(email).count).to eq(1)+ end+ end+context "when the email belongs to an existing user" doit { is_expected.to run_successfully }