crbench//

← all cases

Add comprehensive email validation for blocked users

Tier 2 easy ruby · local · real merged PR from ai-code-review-evaluation/discourse-graphite #3

Ground-truth defects

d3 · correctness · medium
BlockedEmail.should_block? (app/models/blocked_email.rb) increments match_count, sets last_match_at, and calls save; it is invoked from EmailValidator#validate_each, and UsersController#create re-runs validations on both user.valid? (line 168) and user.save (line 172), so a single signup with a matching blocked email writes the row and over-counts match_count twice, plus performs a DB write during the read-only valid? check.

The change under review

diff
diff --git a/app/assets/javascripts/discourse/controllers/create_account_controller.js b/app/assets/javascripts/discourse/controllers/create_account_controller.js
index 6ec6c8fa2a..7f48f718fd 100644
--- a/app/assets/javascripts/discourse/controllers/create_account_controller.js
+++ b/app/assets/javascripts/discourse/controllers/create_account_controller.js
@@ -14,6 +14,7 @@ Discourse.CreateAccountController = Discourse.Controller.extend(Discourse.ModalF
   accountPasswordConfirm: 0,
   accountChallenge: 0,
   formSubmitted: false,
+  rejectedEmails: Em.A([]),
 
   submitDisabled: function() {
     if (this.get('formSubmitted')) return true;
@@ -64,6 +65,14 @@ Discourse.CreateAccountController = Discourse.Controller.extend(Discourse.ModalF
     }
 
     email = this.get("accountEmail");
+
+    if (this.get('rejectedEmails').contains(email)) {
+      return Discourse.InputValidation.create({
+        failed: true,
+        reason: I18n.t('user.email.invalid')
+      });
+    }
+
     if ((this.get('authOptions.email') === email) && this.get('authOptions.email_valid')) {
       return Discourse.InputValidation.create({
         ok: true,
@@ -84,7 +93,7 @@ Discourse.CreateAccountController = Discourse.Controller.extend(Discourse.ModalF
       failed: true,
       reason: I18n.t('user.email.invalid')
     });
-  }.property('accountEmail'),
+  }.property('accountEmail', 'rejectedEmails.@each'),
 
   usernameMatch: function() {
     if (this.usernameNeedsToBeValidatedWithEmail()) {
@@ -262,6 +271,9 @@ Discourse.CreateAccountController = Discourse.Controller.extend(Discourse.ModalF
         createAccountController.set('complete', true);
       } else {
         createAccountController.flash(result.message || I18n.t('create_account.failed'), 'error');
+        if (result.errors && result.errors.email && result.values) {
+          createAccountController.get('rejectedEmails').pushObject(result.values.email);
+        }
         createAccountController.set('formSubmitted', false);
       }
       if (result.active) {
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index 69c028e933..168ab564bd 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -194,7 +194,9 @@ class UsersController < ApplicationController
     else
       render json: {
         success: false,
-        message: I18n.t("login.errors", errors: user.errors.full_messages.join("\n"))
+        message: I18n.t("login.errors", errors: user.errors.full_messages.join("\n")),
+        errors: user.errors.to_hash,
+        values: user.attributes.slice("name", "username", "email")
       }
     end
   rescue ActiveRecord::StatementInvalid
diff --git a/app/models/blocked_email.rb b/app/models/blocked_email.rb
new file mode 100644
index 0000000000..6bc8a48570
--- /dev/null
+++ b/app/models/blocked_email.rb
@@ -0,0 +1,25 @@
+class BlockedEmail < ActiveRecord::Base
+
+  before_validation :set_defaults
+
+  validates :email, presence: true, uniqueness: true
+
+  def self.actions
+    @actions ||= Enum.new(:block, :do_nothing)
+  end
+
+  def self.should_block?(email)
+    record = BlockedEmail.where(email: email).first
+    if record
+      record.match_count += 1
+      record.last_match_at = Time.zone.now
+      record.save
+    end
+    record && record.action_type == actions[:block]
+  end
+
+  def set_defaults
+    self.action_type ||= BlockedEmail.actions[:block]
+  end
+
+end
diff --git a/app/models/user.rb b/app/models/user.rb
index c8b7f1e9f8..f4f5d9f40f 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -42,10 +42,9 @@ class User < ActiveRecord::Base
   has_one :user_search_data
 
   validates_presence_of :username
-  validates_presence_of :email
-  validates_uniqueness_of :email
   validate :username_validator
-  validate :email_validator, if: :email_changed?
+  validates :email, presence: true, uniqueness: true
+  validates :email, email: true, if: :email_changed?
   validate :password_validator
 
   before_save :cook
@@ -565,24 +564,6 @@ class User < ActiveRecord::Base
     end
   end
 
-  def email_validator
-    if (setting = SiteSetting.email_domains_whitelist).present?
-      unless email_in_restriction_setting?(setting)
-        errors.add(:email, I18n.t(:'user.email.not_allowed'))
-      end
-    elsif (setting = SiteSetting.email_domains_blacklist).present?
-      if email_in_restriction_setting?(setting)
-        errors.add(:email, I18n.t(:'user.email.not_allowed'))
-      end
-    end
-  end
-
-  def email_in_restriction_setting?(setting)
-    domains = setting.gsub('.', '\.')
-    regexp = Regexp.new("@(#{domains})", true)
-    self.email =~ regexp
-  end
-
   def password_validator
     if (@raw_password && @raw_password.length < 6) || (@password_required && !@raw_password)
       errors.add(:password, "must be 6 letters or longer")
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 356e0e71ca..6ce5772d52 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -731,6 +731,7 @@ en:
       must_begin_with_alphanumeric: "must begin with a letter or number"
     email:
       not_allowed: "is not allowed from that email provider. Please use another email address."
+      blocked: "is not allowed."
 
   invite_mailer:
     subject_template: "[%{site_name}] %{invitee_name} invited you to join a discussion on %{site_name}"
diff --git a/db/migrate/20130724201552_create_blocked_emails.rb b/db/migrate/20130724201552_create_blocked_emails.rb
new file mode 100644
index 0000000000..2c669e3ee1
--- /dev/null
+++ b/db/migrate/20130724201552_create_blocked_emails.rb
@@ -0,0 +1,12 @@
+class CreateBlockedEmails < ActiveRecord::Migration
+  def change
+    create_table :blocked_emails do |t|
+      t.string :email, null: false
+      t.integer :action_type, null: false
+      t.integer :match_count, null: false, default: 0
+      t.datetime :last_match_at
+      t.timestamps
+    end
+    add_index :blocked_emails, :email, unique: true
+  end
+end
diff --git a/lib/validators/email_validator.rb b/lib/validators/email_validator.rb
new file mode 100644
index 0000000000..c2e4284b4e
--- /dev/null
+++ b/lib/validators/email_validator.rb
@@ -0,0 +1,24 @@
+class EmailValidator < ActiveModel::EachValidator
+
+  def validate_each(record, attribute, value)
+    if (setting = SiteSetting.email_domains_whitelist).present?
+      unless email_in_restriction_setting?(setting, value)
+        record.errors.add(attribute, I18n.t(:'user.email.not_allowed'))
+      end
+    elsif (setting = SiteSetting.email_domains_blacklist).present?
+      if email_in_restriction_setting?(setting, value)
+        record.errors.add(attribute, I18n.t(:'user.email.not_allowed'))
+      end
+    end
+    if record.errors[attribute].blank? and BlockedEmail.should_block?(value)
+      record.errors.add(attribute, I18n.t(:'user.email.blocked'))
+    end
+  end
+
+  def email_in_restriction_setting?(setting, value)
+    domains = setting.gsub('.', '\.')
+    regexp = Regexp.new("@(#{domains})", true)
+    value =~ regexp
+  end
+
+end
\ No newline at end of file
diff --git a/spec/components/validators/email_validator_spec.rb b/spec/components/validators/email_validator_spec.rb
new file mode 100644
index 0000000000..2591a1ec73
--- /dev/null
+++ b/spec/components/validators/email_validator_spec.rb
@@ -0,0 +1,23 @@
+require 'spec_helper'
+
+describe EmailValidator do
+
+  let(:record) { Fabricate.build(:user, email: "bad@spamclub.com") }
+  let(:validator) { described_class.new({attributes: :email}) }
+  subject(:validate) { validator.validate_each(record,:email,record.email) }
+
+  context "blocked email" do
+    it "doesn't add an error when email doesn't match a blocked email" do
+      BlockedEmail.stubs(:should_block?).with(record.email).returns(false)
+      validate
+      record.errors[:email].should_not be_present
+    end
+
+    it "adds an error when email matches a blocked email" do
+      BlockedEmail.stubs(:should_block?).with(record.email).returns(true)
+      validate
+      record.errors[:email].should be_present
+    end
+  end
+
+end
diff --git a/spec/fabricators/blocked_email_fabricator.rb b/spec/fabricators/blocked_email_fabricator.rb
new file mode 100644
index 0000000000..7e93250269
--- /dev/null
+++ b/spec/fabricators/blocked_email_fabricator.rb
@@ -0,0 +1,4 @@
+Fabricator(:blocked_email) do
+  email { sequence(:email) { |n| "bad#{n}@spammers.org" } }
+  action_type BlockedEmail.actions[:block]
+end
diff --git a/spec/models/blocked_email_spec.rb b/spec/models/blocked_email_spec.rb
new file mode 100644
index 0000000000..d1a6fe81eb
--- /dev/null
+++ b/spec/models/blocked_email_spec.rb
@@ -0,0 +1,48 @@
+require 'spec_helper'
+
+describe BlockedEmail do
+
+  let(:email) { 'block@spamfromhome.org' }
+
+  describe "new record" do
+    it "sets a default action_type" do
+      BlockedEmail.create(email: email).action_type.should == BlockedEmail.actions[:block]
+    end
+
+    it "last_match_at is null" do
+      # If we manually load the table with some emails, we can see whether those emails
+      # have ever been blocked by looking at last_match_at.
+      BlockedEmail.create(email: email).last_match_at.should be_nil
+    end
+  end
+
+  describe "#should_block?" do
+    subject { BlockedEmail.should_block?(email) }
+
+    it "returns false if a record with the email doesn't exist" do
+      subject.should be_false
+    end
+
+    shared_examples "when a BlockedEmail record matches" do
+      it "updates statistics" do
+        Timecop.freeze(Time.zone.now) do
+          expect { subject }.to change { blocked_email.reload.match_count }.by(1)
+          blocked_email.last_match_at.should be_within_one_second_of(Time.zone.now)
+        end
+      end
+    end
+
+    context "action_type is :block" do
+      let!(:blocked_email) { Fabricate(:blocked_email, email: email, action_type: BlockedEmail.actions[:block]) }
+      it { should be_true }
+      include_examples "when a BlockedEmail record matches"
+    end
+
+    context "action_type is :do_nothing" do
+      let!(:blocked_email) { Fabricate(:blocked_email, email: email, action_type: BlockedEmail.actions[:do_nothing]) }
+      it { should be_false }
+      include_examples "when a BlockedEmail record matches"
+    end
+  end
+
+end

Leaderboard for this case

easy · 7 of 9 bots fully caught it (78% solve rate) · 78% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 cursor solved 1/1 100.0% 2 0
2 Drape (Deep Review) solved 1/1 100.0% 4 0
3 Drape (Review) solved 1/1 100.0% 3 0
4 Mjolnir (Opus 5.5) solved 1/1 100.0% 3 0
5 Mjolnir (Sonnet 5.5) solved 1/1 100.0% 4 0
6 qodo solved 1/1 100.0% 3 0
7 Claude Code (Opus 5.5) solved 1/1 100.0% 4 1
8 Cubic miss 0/1 0.0% 2 0
9 greptile miss 0/1 0.0% 3 0

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ off by one
valid · impact medium
The new lookup is an exact equality match. Nothing in the User model, `new_from_params` or the validator lowercases the email first, so changing the letter case gets past the block list. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
invalid
The removed `email_validator` behaved the same way: it ran the whitelist check on a nil email (`self.email =~ regexp`) with no guard, under the same `if: :email_changed?` condition. The change only moved this logic into EachValidator, so the misleading error already existed before. [invalid: introduced=no] [consensus 3/3: invalid=3]
valid · impact low
The array is defined on the prototype, so all instances share it. Any server email error (`result.errors.email`) pushes the email into the list for good, and the client then shows the generic 'invalid' message for that email until the page reloads. Impact is low because the errors are mostly persistent server-side anyway. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
app/models/blocked_email.rb:12
`should_block?` looks up the email with an exact, case-sensitive match (`where(email: email)`), and nothing lowercases the value first in either the User model or the validator. A blocked address like `bad@spam.org` can still sign up as `Bad@Spam.org` or `BAD@spam.org`, so the block list is easy to get around.
app/models/blocked_email.rb:13
`should_block?` is a query, but it also updates `match_count` and `last_match_at`, and it runs on every validation. Calling `valid?` more than once on the same unsaved user (the create flow does this, and so does `change_username`) counts one attempt several times. The increment is also a read-modify-write, so concurrent requests lose counts; `update_all`/`increment_counter` would avoid that. It also writes to the database even when the surrounding user save fails.
lib/validators/email_validator.rb:3
The validator has no nil/blank guard, and the model declares it without `allow_blank`. When the email is missing and a domain whitelist is set, the user gets a misleading 'not allowed from that email provider' error on top of the presence error.
app/assets/javascripts/discourse/controllers/create_account_controller.js:17
`rejectedEmails: Em.A([])` is defined on the class prototype, so every controller instance shares the same array. Once an email is rejected, it stays marked invalid on the client for the rest of the page session, including after the modal is reopened. It also gets added for any email error, such as 'already taken', not only for blocked emails.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✗ —
valid · impact low
In Ember, an array literal passed to extend() lives on the prototype, so every instance shares the same array. That is a known pitfall. Ember controllers are usually singletons, though, so the real-world impact is small. [grounded: diff] [consensus 5/5: valid=5]
valid · impact medium
should_block? does an exact match on the raw email value. Neither User nor BlockedEmail lowercases the email, so changing the case of the address gets around the block. [grounded: diff] [consensus 5/5: valid=5]
raw comments (3)
app/assets/javascripts/discourse/controllers/create_account_controller.js:17
<!-- cubic:v=76117992-1aec-4ed2-9413-e34b8abeef93 --> <!-- cubic:review-run=1fc950b6-b84c-55ee-851b-b90853828f25 --> <!-- metadata:{"confidence":8} --> P2: Initialize `rejectedEmails` per controller instance instead of storing a mutable array on the prototype. Otherwise a rejected address from one controller instance leaks into every other instance and can make its email validation fail unexpectedly. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/javascripts/discourse/controllers/create_account_controller.js, line 17: <comment>Initialize `rejectedEmails` per controller instance instead of storing a mutable array on the prototype. Otherwise a rejected address from one controller instance leaks into every other instance and can make its email validation fail unexpectedly.</comment> <file context> @@ -14,6 +14,7 @@ Discourse.CreateAccountController = Discourse.Controller.extend(Discourse.ModalF accountPasswordConfirm: 0, accountChallenge: 0, formSubmitted: false, + rejectedEmails: Em.A([]), submitDisabled: function() { </file context> ``` </details>
app/models/blocked_email.rb:12
<!-- cubic:v=690c3c26-7891-4f7c-96c2-c224390cdb9e --> <!-- cubic:review-run=1fc950b6-b84c-55ee-851b-b90853828f25 --> <!-- metadata:{"confidence":6} --> P2: Blocked-email checks are case-sensitive, so a block can be bypassed. `should_block?` matches with an exact `where(email: email)`, the model stores the email unnormalized, and the unique index is case-sensitive, so signing up with a different case (e.g. `Spam@example.com` vs `spam@example.com`) creates a distinct row and is never blocked. Downcase emails before storing and before matching so a blocked address is blocked regardless of case. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At app/models/blocked_email.rb, line 12: <comment>Blocked-email checks are case-sensitive, so a block can be bypassed. `should_block?` matches with an exact `where(email: email)`, the model stores the email unnormalized, and the unique index is case-sensitive, so signing up with a different case (e.g. `Spam@example.com` vs `spam@example.com`) creates a distinct row and is never blocked. Downcase emails before storing and before matching so a blocked address is blocked regardless of case.</comment> <file context> @@ -0,0 +1,25 @@ + end + + def self.should_block?(email) + record = BlockedEmail.where(email: email).first + if record + record.match_count += 1 </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **2 issues found** across 10 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="app/assets/javascripts/discourse/controllers/create_account_controller.js"> <violation number="1" location="app/assets/javascripts/discourse/controllers/create_account_controller.js:17"> P2: Initialize `rejectedEmails` per controller instance instead of storing a mutable array on the prototype. Otherwise a rejected address from one controller instance leaks into every other instance and can make its email validation fail unexpectedly.</violation> </file> <file name="app/models/blocked_email.rb"> <violation number="1" location="app/models/blocked_email.rb:12"> P2: Blocked-email checks are case-sensitive, so a block can be bypassed. `should_block?` matches with an exact `where(email: email)`, the model stores the email unnormalized, and the unique index is case-sensitive, so signing up with a different case (e.g. `Spam@example.com` vs `spam@example.com`) creates a distinct row and is never blocked. Downcase emails before storing and before matching so a blocked address is blocked regardless of case.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/32/ai_pr_review_github_delivery_9f084c5bd5558176e122216c3414bbabbd98bd8065f592572c0664ef5cfa68fc?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F32)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_9f084c5bd5558176e122216c3414bbabbd98bd8065f592572c0664ef5cfa68fc:7de502a3ef27be297ca742b73de698954be69e18:1fc950b6-b84c-55ee-851b-b90853828f25 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ off by one
valid · impact medium
`should_block?` uses an exact `where(email: email)` lookup. Neither BlockedEmail nor User normalizes email case before this check: `new_from_params` assigns the raw `params[:email]`, and a grep of app/models finds no downcasing for User emails. A blocked address typed with different letter case therefore gets past the new block check, while the domain checks use a case-insensitive regexp. [grounded: tree app/models/blocked_email.rb] [consensus 5/5: valid=5]
valid · matches d3 · impact medium
raw comments (3)
app/models/blocked_email.rb:18
### Blocked email lookup is case-sensitive **Medium Severity** <!-- DESCRIPTION START --> `should_block?` looks up the candidate address with an exact string match. A blocked address still succeeds at signup if any character differs in case. Domain whitelist and blacklist checks in the same `EmailValidator` already ignore case, so this gap lets blocked addresses through. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: ca73d4cf-c40b-4a7b-a5c9-573a6a7b81c5 --> <!-- LOCATIONS START app/models/blocked_email.rb#L10-L18 lib/validators/email_validator.rb#L12-L15 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`lib/validators/email_validator.rb#L12-L15`](https://github.com/drape-io/crbench-cursor-2026-09/blob/d4807225b9199cfa7eb73e1c3e14fbb5a17d0617/lib/validators/email_validator.rb#L12-L15) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjY2OGY2OGRkLTM0MDktNDQ1ZC05NGNmLTU3YWJhMzQ3MWMwNiIsImVuY3J5cHRpb25LZXkiOiJlTjVJQzFxekpoWnJZaUl4bmJwV0xNYy1jNF9SeV9XSjJWR2xfYll5N0VZIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTMiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjY2OGY2OGRkLTM0MDktNDQ1ZC05NGNmLTU3YWJhMzQ3MWMwNiIsImVuY3J5cHRpb25LZXkiOiJlTjVJQzFxekpoWnJZaUl4bmJwV0xNYy1jNF9SeV9XSjJWR2xfYll5N0VZIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTMiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjozMywiY29tbWl0U2hhIjoiZDQ4MDcyMjViOTE5OWNmYTdlYjczZTFjM2UxNGZiYjVhMTdkMDYxNyIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d4807225b9199cfa7eb73e1c3e14fbb5a17d0617. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
app/models/blocked_email.rb:16
### Signup double-counts blocked matches **Low Severity** <!-- DESCRIPTION START --> `should_block?` increments `match_count` and writes `last_match_at` on every call. Account creation always runs validations twice (`user.valid?` then `user.save`), so each blocked signup attempt records two matches instead of one. Blocking itself still works; the stored statistics do not. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: c5bd16fd-721d-487e-a2b1-b94a794bd4cb --> <!-- LOCATIONS START app/models/blocked_email.rb#L12-L16 lib/validators/email_validator.rb#L12-L14 app/controllers/users_controller.rb#L167-L172 LOCATIONS END --> <details> <summary>Additional Locations (2)</summary> - [`lib/validators/email_validator.rb#L12-L14`](https://github.com/drape-io/crbench-cursor-2026-09/blob/d4807225b9199cfa7eb73e1c3e14fbb5a17d0617/lib/validators/email_validator.rb#L12-L14) - [`app/controllers/users_controller.rb#L167-L172`](https://github.com/drape-io/crbench-cursor-2026-09/blob/d4807225b9199cfa7eb73e1c3e14fbb5a17d0617/app/controllers/users_controller.rb#L167-L172) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjFhMTI0Y2I5LTU3NjctNGE3Ni1iODU5LWIzMzEzM2U5M2Q1YSIsImVuY3J5cHRpb25LZXkiOiJNd05iTmFvdklNc2t6NU5NM0V5N0Y2RFJjSlBxaVFSRElINlFoRm5ZSF9ZIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTMiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjFhMTI0Y2I5LTU3NjctNGE3Ni1iODU5LWIzMzEzM2U5M2Q1YSIsImVuY3J5cHRpb25LZXkiOiJNd05iTmFvdklNc2t6NU5NM0V5N0Y2RFJjSlBxaVFSRElINlFoRm5ZSF9ZIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTMiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjozMywiY29tbWl0U2hhIjoiZDQ4MDcyMjViOTE5OWNmYTdlYjczZTFjM2UxNGZiYjVhMTdkMDYxNyIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d4807225b9199cfa7eb73e1c3e14fbb5a17d0617. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTozOGZmMjEwYS0wNjQ0LTRhNmMtOGYzMi1mMjhkZWM4Yjk2ZDMiLCJlbmNyeXB0aW9uS2V5IjoiZjNnTFR0TnNLWExFNWQ0Z1FMOXgtTkVqWmxxVlFROUhWNWZMbUhYM0VobyIsImJyYW5jaCI6InQyLWRpc2NvdXJzZS1ncmFwaGl0ZS0zIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d4807225b9199cfa7eb73e1c3e14fbb5a17d0617. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ exact
valid · matches d3 · impact medium
valid · impact low
The new should_block? does an in-Ruby read-modify-write and then saves. Two concurrent matches on the same record can therefore lose an increment. This only affects statistics. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
valid · impact medium
The lookup is an exact match, and the User model never lowercases the email; new_from_params assigns params[:email] directly. Changing the letter case therefore gets past the new block list. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
valid · impact low
Any server email error, including 'taken' or 'blocked', adds the address to rejectedEmails, and the inline validation then shows the generic 'invalid' text. The server message is still flashed, which softens the 'never sees the real reason' wording, but the inline reason is still misleading. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
raw comments (4)
lib/validators/email_validator.rb:13
**Blocked-email match counted twice per signup** `UsersController#create` calls `user.valid?` and then `user.save`, which validates again. Each pass runs `BlockedEmail.should_block?`, and that call bumps `match_count` and saves the record, so one signup attempt counts as two matches. Keep statistics updates out of validation, or record the match only once per request (for example, after the save fails). ``` lib/validators/email_validator.rb:13 if record.errors[attribute].blank? and BlockedEmail.should_block?(value) lib/validators/email_validator.rb:14 record.errors.add(attribute, I18n.t(:'user.email.blocked')) lib/validators/email_validator.rb:15 end app/models/blocked_email.rb:11 def self.should_block?(email) app/controllers/users_controller.rb:168 if user.valid? && SiteSetting.call_discourse_hub? app/controllers/users_controller.rb:172 if user.save app/models/blocked_email.rb:13 if record app/models/blocked_email.rb:14 record.match_count += 1 app/models/blocked_email.rb:15 record.last_match_at = Time.zone.now app/models/blocked_email.rb:16 record.save ```
app/models/blocked_email.rb:14
**Concurrent matches lose match_count increments** `should_block?` reads `match_count`, adds one in Ruby, and saves it back. When two signups hit the same record at once, one increment overwrites the other. Use `BlockedEmail.update_counters` / an atomic SQL update to increment the count. ``` app/models/blocked_email.rb:13 if record app/models/blocked_email.rb:14 record.match_count += 1 app/models/blocked_email.rb:15 record.last_match_at = Time.zone.now app/models/blocked_email.rb:16 record.save ```
app/models/blocked_email.rb:12
**Blocked emails bypassed by changing letter case** `should_block?` matches the email exactly, and signup emails are not lowercased first. Someone can get past a block by typing `Bad@spammers.org` when `bad@spammers.org` is on the list. Lowercase the email (for example with `Email.downcase`) when storing and when looking it up. ``` app/models/blocked_email.rb:12 record = BlockedEmail.where(email: email).first app/models/user.rb:84 def self.new_from_params(params) app/models/user.rb:85 user = User.new app/models/user.rb:86 user.name = params[:name] app/models/user.rb:87 user.email = params[:email] app/models/user.rb:88 user.password = params[:password] app/models/user.rb:89 user.username = params[:username] app/models/user.rb:90 user app/models/user.rb:91 end app/models/user.rb:127 lower_email = Email.downcase(username_or_email) ```
app/assets/javascripts/discourse/controllers/create_account_controller.js:72
**Server-rejected email shows a misleading reason** An email the server rejected (blocked, already taken, or domain not allowed) shows the generic 'invalid' message, so the user is told a well-formed address is invalid and never sees the real reason. Store the server's email error message and display it as the reason. ``` app/assets/javascripts/discourse/controllers/create_account_controller.js:69 if (this.get('rejectedEmails').contains(email)) { app/assets/javascripts/discourse/controllers/create_account_controller.js:70 return Discourse.InputValidation.create({ app/assets/javascripts/discourse/controllers/create_account_controller.js:71 failed: true, app/assets/javascripts/discourse/controllers/create_account_controller.js:72 reason: I18n.t('user.email.invalid') ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ exact
valid · matches d3 · impact medium
valid · impact medium
Neither BlockedEmail nor User normalises the email (new_from_params assigns params[:email] as-is). The where lookup is an exact match, so a different casing slips past the new block check. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
valid · impact low
An Ember array literal on the extend() hash sits on the prototype and is shared by all instances. pushObject mutates it and nothing ever clears it. The impact is limited because Ember controllers are usually singletons. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
app/models/blocked_email.rb:14
**Validation increments match counters, twice per signup** `should_block?` writes `match_count` on every call, and the email validator calls it on every validation. Signup runs `user.valid?` then `user.save`, so one attempt counts twice. Keep validation read-only and record the match once, where the signup is rejected. ``` app/models/blocked_email.rb:11 def self.should_block?(email) app/models/blocked_email.rb:12 record = BlockedEmail.where(email: email).first app/models/blocked_email.rb:13 if record app/models/blocked_email.rb:14 record.match_count += 1 app/controllers/users_controller.rb:168 if user.valid? && SiteSetting.call_discourse_hub? ```
app/models/blocked_email.rb:13
**Blocked-email match is case-sensitive** `should_block?` looks up the email with an exact, case-sensitive match. A blocked address such as `bad@spam.com` is bypassed by registering as `Bad@Spam.com`, because the email is not normalised before the lookup or on insert. Downcase the email in BlockedEmail (before_validation) and in the lookup, e.g. Email.downcase(email). ``` app/models/blocked_email.rb:12 record = BlockedEmail.where(email: email).first app/models/blocked_email.rb:13 if record app/models/blocked_email.rb:14 record.match_count += 1 app/models/blocked_email.rb:15 record.last_match_at = Time.zone.now ```
app/assets/javascripts/discourse/controllers/create_account_controller.js:17
**rejectedEmails array shared across controller instances** `rejectedEmails: Em.A([])` is declared on the class prototype, so every instance shares one array and `pushObject` mutates it. Rejected emails are never cleared. Initialize the array in init() instead of on the prototype. ``` app/assets/javascripts/discourse/controllers/create_account_controller.js:17 rejectedEmails: Em.A([]), app/assets/javascripts/discourse/controllers/create_account_controller.js:274 if (result.errors && result.errors.email && result.values) { app/assets/javascripts/discourse/controllers/create_account_controller.js:275 createAccountController.get('rejectedEmails').pushObject(result.values.email); app/assets/javascripts/discourse/controllers/create_account_controller.js:276 } ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✗ —
valid · impact medium
The new lookup is a plain equality query. Neither User.new_from_params nor the validator lowercases the email first, so a case variant of a blocked address can skip the block. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The array is defined once in the class definition, items are only ever pushed onto it and nothing resets it. An address rejected for any email error keeps failing client-side validation until the page reloads. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The counter is read in Ruby, incremented and saved without an atomic update or a lock, so two concurrent matches can lose an increment. The impact is low because only statistics are affected. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
app/models/blocked_email.rb:12
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> <a href="#"><img alt="security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2" align="top"></a> **Case Variants Bypass Blocking** The lookup compares the raw signup email with a case-sensitive PostgreSQL string. Because signup does not normalize the address first, a blocked address such as `blocked@example.com` can be submitted as `blocked@EXAMPLE.COM` and avoid the block, allowing registration to continue. **How this was verified:** Signup passes the unnormalized email into a plain PostgreSQL varchar equality query with no case-insensitive column, index, or comparison.
app/assets/javascripts/discourse/controllers/create_account_controller.js:17
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Rejected Emails Persist** `rejectedEmails` is mutable controller state that is never cleared when the signup modal closes or reopens. Rejected addresses therefore remain cached for later signup sessions and continue failing client-side validation, even if the server would now accept them. Initialize or reset this list for each signup flow. Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
app/models/blocked_email.rb:14
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Concurrent Matches Lose Counts** The counter uses a read-modify-write sequence. If two signup validations match the same address concurrently, both can read the same value and save the same incremented result, losing one match from the statistics. Use an atomic database counter update or row locking so every match is recorded.
PR-level
<h3>Greptile Summary</h3> This PR introduces a persistent blocked-email model and validation path, returns structured signup validation details, and caches rejected addresses in the account-creation controller. - Adds blocked-email actions, match statistics, schema, fixtures, and model tests. - Moves domain allowlist/denylist validation into a reusable `EmailValidator`. - Extends failed signup responses with field errors and submitted values. - Adds client-side suppression of previously rejected email submissions. <h3>Confidence Score: 4/5</h3> The PR is not safe to merge until blocked-email matching cannot be bypassed with valid case variants. The new registration restriction compares raw email input with a case-sensitive database value, allowing a blocked domain-case variant to proceed; the retained controller state and non-atomic match counter are additional lower-impact correctness concerns. **Files Needing Attention:** app/models/blocked_email.rb, app/assets/javascripts/discourse/controllers/create_account_controller.js <details open><summary><h3>Security Review</h3></summary> The blocked-email restriction can be bypassed using a domain-case variant because signup values are not normalized and the new database lookup is case-sensitive. </details> <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | app/models/blocked_email.rb | Introduces blocked-address lookup and statistics, but matching is case-sensitive and counter updates are non-atomic. | | lib/validators/email_validator.rb | Centralizes domain and blocked-address validation while forwarding the unnormalized signup email to the exact-match lookup. | | app/assets/javascripts/discourse/controllers/create_account_controller.js | Caches rejected addresses for client validation, but the mutable state is not scoped or reset per signup flow. | | app/controllers/users_controller.rb | Adds structured validation errors and selected submitted values to ordinary failed-signup responses. | | db/migrate/20130724201552_create_blocked_emails.rb | Adds the blocked-email table and unique index, using a case-sensitive string representation for addresses. | </details> <details open><summary><h3>Flowchart</h3></summary> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A[Signup submits email] --> B[User email validation] B --> C[Domain allowlist or denylist check] C -->|passes| D[Exact BlockedEmail lookup] D -->|record found| E[Increment match statistics] E --> F{Action} F -->|block| G[Return email validation error] F -->|do_nothing| H[Continue signup] D -->|no exact match| H G --> I[Return errors and submitted values] I --> J[Cache rejected email in controller] ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update app/assets/javascripts/discourse/..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/19b8f304ad6a1c0c1c0a7d3d885473fc877c233a) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284368)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ off by one
valid · impact medium
The new should_block? does an exact where(email:) lookup. User.new_from_params assigns params[:email] unchanged, and User has no downcasing callback. A blocked address typed in different case therefore finds no record and passes validation, while the domain regexes next to it are case-insensitive. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · impact medium
This is the same claim: the exact-match lookup in the new BlockedEmail.should_block? lets a case-changed email through. Because no record is found, the match statistics are not updated either. Nothing in the signup path normalizes the case first. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
raw comments (3)
app/models/blocked_email.rb:11
[P2] Blocked email lookup is case-sensitive, so changing letter case gets around it `should_block?` does an exact `where(email: email)` match. Nothing normalizes the address: `User` has no downcasing callback, and `new_from_params` assigns `params[:email]` as-is. If `bad@spammers.org` is blocked, signing up as `Bad@Spammers.org` or `BAD@spammers.org` finds no record and passes validation. The domain whitelist and blacklist checks in the same validator match case-insensitively (`Regexp.new(..., true)`), so this check behaves differently from the ones next to it. Fixing it means normalizing the case on both sides, both when a blocked email is stored and when it is looked up.
lib/validators/email_validator.rb:13
[P3] Each blocked signup attempt adds 2 to `match_count` instead of 1 `BlockedEmail.should_block?` updates the record (increments `match_count`, sets `last_match_at`, saves) every time validation runs. `UsersController#create` validates a new user twice: once in `user.valid? && SiteSetting.call_discourse_hub?` (the `valid?` call runs even when the hub is off) and again in `user.save`. So one blocked signup counts as two matches, and any other repeated `valid?` call on a user whose email changed inflates the count further. That makes the statistics this table is meant to record wrong. Running a database write as a side effect of validation is also surprising behavior.
app/models/blocked_email.rb:11
[P2] Blocked-email lookup is case-sensitive, so the block is easy to get around `should_block?` looks up the record with `BlockedEmail.where(email: email)`, which is an exact match. The signup path does not normalise the email before it is validated: `User.new_from_params` assigns `params[:email]` as typed. So if `bad@spamclub.com` is blocked, signing up as `Bad@SpamClub.com` or `BAD@spamclub.com` gets past `EmailValidator`, and the match statistics are never updated. The domain whitelist and blacklist checks next to it already match case-insensitively (`Regexp.new(..., true)`), and the change-email flow lowercases with `Email.downcase`. The blocked-email check should also compare normalised values, for example by downcasing both the stored and the incoming email or by using a case-insensitive comparison.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ off by one
valid · impact medium
The new block lookup compares the raw value exactly. Neither User nor BlockedEmail downcases the email (User.new_from_params assigns params[:email] directly), so changing the letter case gets around the block. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · impact low
UsersController#create always evaluates `user.valid?` first in `user.valid? && SiteSetting.call_discourse_hub?`, then `user.save` validates again. On a new record email_changed? is true both times, so should_block? runs twice and bumps the counter twice. The read-modify-write is also not atomic, and the result of save is ignored. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
valid · impact medium
Same as finding 0: the lookup is an exact match and no code normalizes case, so a blocked address can be registered again with different letter case. [grounded: tree app/models/blocked_email.rb] [consensus 3/3: valid=3]
raw comments (4)
app/models/blocked_email.rb:12
[P2] Blocked-email lookup is case-sensitive BlockedEmail.where(email: email)` is an exact, case-sensitive match, and nothing in this diff downcases either the stored blocked email or the user's email (User does not normalize email). Someone blocked as `bad@spam.com` can register as `Bad@Spam.com` and bypass the block. Normalize both sides, for example with `Email.downcase` on write and on lookup
lib/validators/email_validator.rb:13
[P3] Validation has write side effects that inflate `match_count` should_block?` saves the record (`match_count += 1`, `last_match_at`) every time the validator runs. `UsersController#create` calls `user.valid?` (line 168) and then saves the user, which validates again, so one signup attempt by a blocked email counts twice. Any other `valid?` call with a changed email also bumps the stats. Consider recording the match only once, or outside the validation path, or making the lookup read-only
lib/validators/email_validator.rb:13
[P2] Match statistics are incremented on every validation run (with app/models/blocked_email.rb:13-17) `BlockedEmail.should_block?` writes `match_count` and `last_match_at` each time it is called, and the validator calls it on every `valid?` while `email_changed?` is true. `UsersController#create` calls `user.valid?` and then `user.save`, which validates again. So one signup attempt with a blocked email bumps `match_count` by 2, and any other path that validates more than once does the same. The counters are meant to show how often an email was blocked, so they will be inflated. The increment is also a non-atomic read-modify-write. Concurrent attempts can lose updates, and a failed `save` is ignored.
app/models/blocked_email.rb:13
[P3] Blocked-email lookup is an exact, case-sensitive match `BlockedEmail.where(email: email)` compares strings exactly, and `User` does not normalize email case in this diff. A blocked address such as `bad@spamclub.com` can be bypassed by registering `Bad@SpamClub.com` or `bad@SPAMCLUB.com`, so the block is easy to evade. Downcase the value, using `Email.downcase`, before looking it up and storing it.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d3 medium ✓ exact
valid · impact medium
should_block? looks up the raw submitted email by exact equality. new_from_params assigns params[:email] as-is, and User has no email normalization (grep found no email= override or downcase hook), so a case variant of a blocked address gets past the new block. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · impact low
The new rejectedEmails array is only ever pushed to and never cleared. The client therefore keeps rejecting an address on later modal opens until the page reloads, even after the server-side cause is gone. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
app/models/blocked_email.rb:12
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Uppercase domains bypass email blocks <code>🐞 Bug</code> <code>⛨ Security</code> <pre> <b><i>BlockedEmail.should_block?</i></b> queries the submitted email with exact string equality even though neither user creation path normalizes the address. Changing only the case of the domain produces a valid equivalent address that misses the blocked row and reaches normal account creation. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Blocked-email enforcement compares raw submitted addresses using exact equality, allowing domain-case variations to evade an existing block. ## Fix Focus Areas - app/models/blocked_email.rb[3-18] - app/models/user.rb[84-103] ## Recommended Fix Canonicalize blocked-email records and lookup values consistently, at minimum stripping whitespace and normalizing the domain with `Email.downcase`. Migrate or normalize existing rows and handle any resulting duplicates before relying on the unique index. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
app/models/blocked_email.rb:16
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 2\. Block statistics become inaccurate <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>BlockedEmail.should_block?</i></b> performs a non-atomic read-modify-save of <b><i>match_count</i></b>, while invoking it from validation records another hit on every validation pass. Concurrent validations can overwrite increments, and <b><i>UsersController#create</i></b> calls <b><i>valid?</i></b> before <b><i>save</i></b> validates again, so one blocked signup is counted twice. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Block-match statistics can lose concurrent increments and count one signup multiple times because persistence occurs as a side effect of each validation pass. ## Fix Focus Areas - app/models/blocked_email.rb[11-18] - lib/validators/email_validator.rb[13-15] - app/controllers/users_controller.rb[168-172] ## Recommended Fix Use an atomic database increment for match statistics and arrange for statistics to be recorded once per account attempt rather than once per Active Model validation invocation. Preserve a side-effect-free blocked-state lookup for repeated validation passes. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
app/assets/javascripts/discourse/controllers/create_account_controller.js:17
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 3\. Unblocked emails remain rejected <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>rejectedEmails</i></b> is stored on the long-lived create-account controller and is never cleared when the modal is opened for a new attempt. After any server-side email error, reopening the modal continues rejecting that address locally even if the server condition has changed or the block was removed. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Server-rejected addresses remain cached on the singleton create-account controller across separate modal sessions. ## Fix Focus Areas - app/assets/javascripts/discourse/controllers/create_account_controller.js[10-17] - app/assets/javascripts/discourse/controllers/create_account_controller.js[69-96] - app/assets/javascripts/discourse/routes/discourse_route.js[53-65] ## Recommended Fix Reset `rejectedEmails` to a fresh Ember array when a new create-account modal session begins, such as in an `onShow` hook, while retaining rejection caching only for retries within the current attempt. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Block configured email addresses during account creation <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>🕐 40+ Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Block exact configured email addresses during signup and record each matching attempt. >• Return structured validation failures so rejected emails stay invalid in the signup form. >• Centralize domain and blocked-address checks in reusable email validation. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD UI["Signup Form"] -->|"submit"| Controller["Users Controller"] -->|"validate"| User["User Model"] --> Validator["Email Validator"] -->|"check and record"| Blocked[("Blocked Emails")] Validator -->|"read restrictions"| Settings["Domain Settings"] Controller -->|"structured rejection"| UI ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Site-setting address blacklist</b></summary> <dl> <dd> - ➕ Avoids a new table and model - ➕ Provides simpler administration for a small static list - ➖ Cannot retain per-address actions or match statistics - ➖ Becomes cumbersome for a large or frequently modified list </dd> </dl> </details> <details> <summary><b>2. Request-layer blocking service</b></summary> <dl> <dd> - ➕ Keeps persistence side effects outside model validation - ➕ Can update counters atomically and support caching - ➖ Adds service-layer complexity - ➖ Risks inconsistent enforcement outside the account-creation endpoint </dd> </dl> </details> >**Recommendation:** The database-backed validator is appropriate because blocking must apply wherever users are validated while retaining per-address actions and usage statistics. A dedicated service would only be preferable if validation frequency or concurrent counter updates become significant. </dd> </dl> </details> <details> <summary> Files changed (10) <code> +155 / -23 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (5) <code> +66 / -2 </code></summary> <dl> <dd> <details> <summary>create_account_controller.js<code>Remember and invalidate server-rejected signup emails</code> <code>+13/-1</code></summary> <br/> >Remember and invalidate server-rejected signup emails > ><pre> >• Tracks email addresses rejected by account creation and marks them invalid on subsequent validation. Structured email failures from the server populate this collection and prevent repeated submission. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-8fe96b124d5795e4c1aa5eacd323d25574c72680ea05c4543f92500b885fbd9b'>app/assets/javascripts/discourse/controllers/create_account_controller.js</a> </details> <details> <summary>users_controller.rb<code>Return structured account validation failures</code> <code>+3/-1</code></summary> <br/> >Return structured account validation failures > ><pre> >• Extends failed user-creation responses with field-level errors and the submitted name, username, and email. This allows the signup client to associate server validation failures with the rejected email. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-cfdccd0a9d5df5a43aaad2a35d36ebbe187c52ad5fdc9846fa189d04537adb6e'>app/controllers/users_controller.rb</a> </details> <details> <summary>blocked_email.rb<code>Add persistent blocked-email rules and match tracking</code> <code>+25/-0</code></summary> <br/> >Add persistent blocked-email rules and match tracking > ><pre> >• Introduces exact-address blocking with block and do-nothing actions. Matching records increment their count and record the latest match timestamp. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-9e8ce9d7fffc1becf777956a4ae62f11f344f6ad54f79aad76c7090a76a0ffaa'>app/models/blocked_email.rb</a> </details> <details> <summary>server.en.yml<code>Add blocked-email validation message</code> <code>+1/-0</code></summary> <br/> >Add blocked-email validation message > ><pre> >• Adds the English server-side message returned when an exact email address is blocked. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-333c4c8cacc2f84633d4894f2aaddb130a6d74f42dd63199462b3d66278f6ce8'>config/locales/server.en.yml</a> </details> <details> <summary>email_validator.rb<code>Centralize domain and exact-address email restrictions</code> <code>+24/-0</code></summary> <br/> >Centralize domain and exact-address email restrictions > ><pre> >• Adds an ActiveModel validator that enforces existing domain whitelist or blacklist settings before consulting blocked-email records. Blocked matches receive a dedicated validation error. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-3e7b2fb7b8b3a42e184eb1f229b957a26385b9ca72ecde4f56a23267c1479feb'>lib/validators/email_validator.rb</a> </details> </dd> </dl> </details> <details> <summary>Refactor (1) <code> +2 / -21 </code></summary> <dl> <dd> <details> <summary>user.rb<code>Delegate user email restrictions to the reusable validator</code> <code>+2/-21</code></summary> <br/> >Delegate user email restrictions to the reusable validator > ><pre> >• Replaces the model-specific domain validation methods with standard presence, uniqueness, and custom email validation declarations. This centralizes email restriction behavior outside the User model. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-9802ca3c9c4cf89904fd44bc114e35ebdf2c5dd3d5b645491e2b253e1afef29b'>app/models/user.rb</a> </details> </dd> </dl> </details> <details> <summary>Tests (3) <code> +75 / -0 </code></summary> <dl> <dd> <details> <summary>email_validator_spec.rb<code>Test exact-address email validation</code> <code>+23/-0</code></summary> <br/> >Test exact-address email validation > ><pre> >• Verifies that the validator accepts unmatched addresses and adds an email error for blocked addresses. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-d64176ae5867ed3fc986b4da64f62662067664a3b1691fa3eee1d1d95d5c166c'>spec/components/validators/email_validator_spec.rb</a> </details> <details> <summary>blocked_email_fabricator.rb<code>Add blocked-email test records</code> <code>+4/-0</code></summary> <br/> >Add blocked-email test records > ><pre> >• Defines a fabricator that creates unique blocked addresses with the default block action. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-c953e23dd7d500504f77cf3ca4ebeadf96a0ca064c130066e9c18f1bfeb0a58e'>spec/fabricators/blocked_email_fabricator.rb</a> </details> <details> <summary>blocked_email_spec.rb<code>Test blocked-email actions and match statistics</code> <code>+48/-0</code></summary> <br/> >Test blocked-email actions and match statistics > ><pre> >• Covers default actions, unmatched addresses, block and do-nothing behavior, and updates to match counts and timestamps. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-5153197f5c0003aebb285c9bdca89f522b31b67f650fec625b883f1c8c8ead46'>spec/models/blocked_email_spec.rb</a> </details> </dd> </dl> </details> <details> <summary>Other (1) <code> +12 / -0 </code></summary> <dl> <dd> <details> <summary>20130724201552_create_blocked_emails.rb<code>Create blocked-emails persistence schema</code> <code>+12/-0</code></summary> <br/> >Create blocked-emails persistence schema > ><pre> >• Creates storage for unique email addresses, actions, match counts, and last-match timestamps. A unique index enforces one rule per email. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-7c274edb617a6026ecd5a321784e4e6d3cfdc2f3d090201bda21a197aaa91efd'>db/migrate/20130724201552_create_blocked_emails.rb</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (3)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Uppercase domains bypass email blocks <code>🐞 Bug</code> <code>⛨ Security</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>BlockedEmail.should_block?</i></b> queries the submitted email with exact string equality even though >neither user creation path normalizes the address. Changing only the case of the domain produces a >valid equivalent address that misses the blocked row and reaches normal account creation. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[app/models/blocked_email.rb[R11-12]](https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-9e8ce9d7fffc1becf777956a4ae62f11f344f6ad54f79aad76c7090a76a0ffaaR11-R12)</code> > >```diff >+ def self.should_block?(email) >+ record = BlockedEmail.where(email: email).first >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The new lookup uses the raw value, while both direct signup and email-based user creation assign >email input unchanged. Elsewhere, authentication explicitly uses <b><i>Email.downcase</i></b>, confirming that >normalized domain casing is used when identifying email addresses. ></pre> > > <code>[app/models/blocked_email.rb[11-18]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/models/blocked_email.rb/#L11-L18)</code> > <code>[app/models/user.rb[84-103]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/models/user.rb/#L84-L103)</code> > <code>[app/controllers/users_controller.rb[157-172]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/controllers/users_controller.rb/#L157-L172)</code> > <code>[app/controllers/session_controller.rb[13-18]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/controllers/session_controller.rb/#L13-L18)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Blocked-email enforcement compares raw submitted addresses using exact equality, allowing domain-case variations to evade an existing block. > >## Fix Focus Areas >- app/models/blocked_email.rb[3-18] >- app/models/user.rb[84-103] > >## Recommended Fix >Canonicalize blocked-email records and lookup values consistently, at minimum stripping whitespace and normalizing the domain with `Email.downcase`. Migrate or normalize existing rows and handle any resulting duplicates before relying on the unique index. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <br/> <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> <details> <summary> 2. Block statistics become inaccurate <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>BlockedEmail.should_block?</i></b> performs a non-atomic read-modify-save of <b><i>match_count</i></b>, while invoking >it from validation records another hit on every validation pass. Concurrent validations can >overwrite increments, and <b><i>UsersController#create</i></b> calls <b><i>valid?</i></b> before <b><i>save</i></b> validates again, so >one blocked signup is counted twice. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[app/models/blocked_email.rb[R14-16]](https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-9e8ce9d7fffc1becf777956a4ae62f11f344f6ad54f79aad76c7090a76a0ffaaR14-R16)</code> > >```diff >+ record.match_count += 1 >+ record.last_match_at = Time.zone.now >+ record.save >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The model reads the row, increments its in-memory value, and saves it without an atomic SQL >increment. The signup action first invokes <b><i>user.valid?</i></b> and then <b><i>user.save</i></b>, which runs the newly >attached email validator again for the unchanged new record. ></pre> > > <code>[app/models/blocked_email.rb[11-18]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/models/blocked_email.rb/#L11-L18)</code> > <code>[lib/validators/email_validator.rb[13-15]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/lib/validators/email_validator.rb/#L13-L15)</code> > <code>[app/models/user.rb[44-48]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/models/user.rb/#L44-L48)</code> > <code>[app/controllers/users_controller.rb[168-172]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/controllers/users_controller.rb/#L168-L172)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Block-match statistics can lose concurrent increments and count one signup multiple times because persistence occurs as a side effect of each validation pass. > >## Fix Focus Areas >- app/models/blocked_email.rb[11-18] >- lib/validators/email_validator.rb[13-15] >- app/controllers/users_controller.rb[168-172] > >## Recommended Fix >Use an atomic database increment for match statistics and arrange for statistics to be recorded once per account attempt rather than once per Active Model validation invocation. Preserve a side-effect-free blocked-state lookup for repeated validation passes. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 3. Unblocked emails remain rejected <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>rejectedEmails</i></b> is stored on the long-lived create-account controller and is never cleared when the >modal is opened for a new attempt. After any server-side email error, reopening the modal continues >rejecting that address locally even if the server condition has changed or the block was removed. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[app/assets/javascripts/discourse/controllers/create_account_controller.js[17]](https://github.com/drape-io/crbench-qodo-2026-09/pull/32/files#diff-8fe96b124d5795e4c1aa5eacd323d25574c72680ea05c4543f92500b885fbd9bR17-R17)</code> > >```diff >+ rejectedEmails: Em.A([]), >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Failed responses append the submitted address to the controller array, and the computed validation >subsequently rejects every contained address. Modal display reuses <b><i>controllerFor(name)</i></b> and does >not reset this property, while the login flow repopulates account fields on the same controller >before reopening it. ></pre> > > <code>[app/assets/javascripts/discourse/controllers/create_account_controller.js[17-17]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/assets/javascripts/discourse/controllers/create_account_controller.js/#L17-L17)</code> > <code>[app/assets/javascripts/discourse/controllers/create_account_controller.js[69-96]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/assets/javascripts/discourse/controllers/create_account_controller.js/#L69-L96)</code> > <code>[app/assets/javascripts/discourse/controllers/create_account_controller.js[268-277]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/assets/javascripts/discourse/controllers/create_account_controller.js/#L268-L277)</code> > <code>[app/assets/javascripts/discourse/routes/discourse_route.js[53-65]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/assets/javascripts/discourse/routes/discourse_route.js/#L53-L65)</code> > <code>[app/assets/javascripts/discourse/controllers/login_controller.js[150-157]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3a74c9d19a709bc31f2d9e61fd9be0a97655c497/app/assets/javascripts/discourse/controllers/login_controller.js/#L150-L157)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Server-rejected addresses remain cached on the singleton create-account controller across separate modal sessions. > >## Fix Focus Areas >- app/assets/javascripts/discourse/controllers/create_account_controller.js[10-17] >- app/assets/javascripts/discourse/controllers/create_account_controller.js[69-96] >- app/assets/javascripts/discourse/routes/discourse_route.js[53-65] > >## Recommended Fix >Reset `rejectedEmails` to a fresh Ember array when a new create-account modal session begins, such as in an `onShow` hook, while retaining rejection caching only for retries within the current attempt. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>⚖️ Balanced</code>: Downgraded extended -&gt; standard: change is below the extended eligibility bar (hunks 14/18, lines 178/200; both must reach the floor). Router rationale: This adds a new email-blocking model, migration, validator, validation flow, API response behavior, and client-side state across multiple independent paths, creating a dense set of easy-to-miss correctness and compatibility risks.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/3a74c9d19a709bc31f2d9e61fd9be0a97655c497 --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>