Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add a configurable password policy
Damian Legawiecf69f05a01360
diff --git a/spree/api/spec/controllers/spree/api/v3/store/customers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/customers_controller_spec.rbindex 6130e45a06..3343e5df0c 100644--- a/spree/api/spec/controllers/spree/api/v3/store/customers_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/customers_controller_spec.rb@@ -359,7 +359,7 @@ RSpec.describe Spree::Api::V3::Store::CustomersController, type: :controller doendit 'accepts correct current_password' do- patch :update, params: { email: '[email protected]', current_password: 'secret' }+ patch :update, params: { email: '[email protected]', current_password: 'secret123' }expect(response).to have_http_status(:ok)expect(user.reload.email).to eq('[email protected]')@@ -382,7 +382,7 @@ RSpec.describe Spree::Api::V3::Store::CustomersController, type: :controller doendit 'accepts correct current_password' do- patch :update, params: { password: 'newpassword123', password_confirmation: 'newpassword123', current_password: 'secret' }+ patch :update, params: { password: 'newpassword123', password_confirmation: 'newpassword123', current_password: 'secret123' }expect(response).to have_http_status(:ok)end@@ -390,7 +390,7 @@ RSpec.describe Spree::Api::V3::Store::CustomersController, type: :controller docontext 'validation errors' doit 'returns errors for blank email with current password' do- patch :update, params: { email: '', current_password: 'secret' }+ patch :update, params: { email: '', current_password: 'secret123' }expect(response).to have_http_status(:unprocessable_content)expect(json_response['error']['code']).to eq('validation_error')@@ -399,7 +399,7 @@ RSpec.describe Spree::Api::V3::Store::CustomersController, type: :controller doit 'returns errors for duplicate email with current password' doother_user = create(:user)- patch :update, params: { email: other_user.email, current_password: 'secret' }+ patch :update, params: { email: other_user.email, current_password: 'secret123' }expect(response).to have_http_status(:unprocessable_content)expect(json_response['error']['code']).to eq('validation_error')diff --git a/spree/core/app/models/concerns/spree/password_policy.rb b/spree/core/app/models/concerns/spree/password_policy.rbnew file mode 100644index 0000000000..6b7aa5b560--- /dev/null+++ b/spree/core/app/models/concerns/spree/password_policy.rb@@ -0,0 +1,37 @@+module Spree+ # Password policy for the default auth models (Customer, AdminUser).+ #+ # The policy itself lives in {Spree.password_validator} — by default+ # {Spree::PasswordLengthValidator}. Swap that to replace it wholesale.+ #+ # Validation runs only while a password is actually being set, so raising the+ # floor on an existing install invalidates no stored digest — short legacy+ # passwords keep working until their owner next changes them.+ module PasswordPolicy+ extend ActiveSupport::Concern++ included do+ validates :password, confirmation: true, allow_blank: true++ # Resolved per call rather than at include time so an integrator can swap+ # the validator after the models have loaded, and so a development reload+ # picks up changes to it.+ validate :validate_password_policy, if: :password_policy_applicable?+ end++ private++ # Only vet a password that is actually being set. +has_secure_password+ leaves+ # the virtual +password+ populated in memory after a save, so testing it alone+ # would re-validate an untouched record — and raising the floor on a live+ # install would then break saves for every existing user whose password is+ # shorter than the new minimum.+ def password_policy_applicable?+ password.present? && password_digest_changed?+ end++ def validate_password_policy+ Spree.password_validator.new(attributes: [:password]).validate(self)+ end+ end+enddiff --git a/spree/core/app/models/spree/admin_user.rb b/spree/core/app/models/spree/admin_user.rbindex fb26b2c6b9..03f25c15f9 100644--- a/spree/core/app/models/spree/admin_user.rb+++ b/spree/core/app/models/spree/admin_user.rb@@ -8,9 +8,9 @@ module Spreeinclude Spree::AdminUserMethodsinclude Spree::AccountLockout+ include Spree::PasswordPolicyvalidates :email, presence: true, uniqueness: { case_sensitive: false }- validates :password, confirmation: true, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, allow_blank: true# Back-compat with callers and auth strategies that check +valid_password?+.# Guards a blank digest (password-less accounts) so it returns false insteaddiff --git a/spree/core/app/models/spree/customer.rb b/spree/core/app/models/spree/customer.rbindex adf46a9116..a7e2fef4ae 100644--- a/spree/core/app/models/spree/customer.rb+++ b/spree/core/app/models/spree/customer.rb@@ -14,9 +14,9 @@ module Spreeinclude Spree::CustomerMethodsinclude Spree::AccountLockout+ include Spree::PasswordPolicyvalidates :email, presence: true, uniqueness: { case_sensitive: false }- validates :password, confirmation: true, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, allow_blank: trueattribute :accepts_email_marketing, :boolean, default: falsediff --git a/spree/core/app/validators/spree/password_length_validator.rb b/spree/core/app/validators/spree/password_length_validator.rbnew file mode 100644index 0000000000..03c60a056f--- /dev/null+++ b/spree/core/app/validators/spree/password_length_validator.rb@@ -0,0 +1,23 @@+module Spree+ # Default password policy: a length floor with no composition rules, following+ # NIST 800-63B (forced symbols and digits push people toward predictable+ # substitutions). Bounds are configurable via+ # +Spree::Config[:minimum_password_length]+ and +[:maximum_password_length]+.+ #+ # Replace the whole policy with {Spree.password_validator=}.+ class PasswordLengthValidator < ActiveModel::Validator+ def validate(record)+ password = record.password+ return if password.blank?++ minimum = Spree::Config[:minimum_password_length]+ maximum = Spree::Config[:maximum_password_length]++ if password.length < minimum+ record.errors.add(:password, :too_short, count: minimum)+ elsif password.length > maximum+ record.errors.add(:password, :too_long, count: maximum)+ end+ end+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 171130b893..46d349cb29 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -297,6 +297,26 @@ module SpreeRails.application.config.spree.tax_provider = valueend+ # Validator enforcing the password policy on the default auth models+ # ({Spree::Customer}, {Spree::AdminUser}). Defaults to+ # {Spree::PasswordLengthValidator}, which reads the configurable length bounds.+ #+ # Assign an +ActiveModel::Validator+ subclass to replace the policy wholesale —+ # corporate rules, breach-list lookups, entropy scoring. Errors it adds to+ # +:password+ reach API clients through the standard 422 path, so the+ # validator's message is the user-facing reason.+ #+ # Spree.password_validator = MyApp::PasswordValidator+ #+ # @return [Class]+ def self.password_validator+ Rails.application.config.spree.password_validator+ end++ def self.password_validator=(value)+ Rails.application.config.spree.password_validator = value+ end+def self.fulfillment_providersRails.application.config.spree.fulfillment_providersenddiff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rbindex c09ed8fb13..39957130b9 100644--- a/spree/core/lib/spree/core/configuration.rb+++ b/spree/core/lib/spree/core/configuration.rb@@ -128,6 +128,16 @@ module Spreepreference :max_failed_login_attempts, :integer, default: 5 # failed login attempts before an account is lockedpreference :lockout_duration, :integer, default: 1800 # lockout duration in seconds (30 minutes)+ # password policy+ # NIST 800-63B recommends a length floor with no composition rules (no forced+ # symbols/digits, which push users toward predictable substitutions).+ preference :minimum_password_length, :integer, default: 8+ # bcrypt silently truncates past 72 bytes — without a cap a long passphrase and+ # its 72-byte prefix are the same password. A correctness guard, not policy.+ preference :maximum_password_length, :integer, default: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED+ # To replace the policy itself, assign Spree.password_validator — a class,+ # not a preference.+# gift cardspreference :gift_card_batch_web_limit, :integer, default: 500 # number of gift card codes to be generated in the web process, more than this will be generated in a background jobpreference :gift_card_batch_limit, :integer, default: 50_000diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex 31e137ced4..ab64245add 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -11,6 +11,7 @@ module Spree:payment_methods,:adjusters,:tax_provider,+ :password_validator,:fulfillment_providers,:fulfillment_types,:stock_splitters,@@ -174,6 +175,10 @@ module Spree# The sanctioned TaxLine writer (see docs/plans/6.0-tax-provider.md).Rails.application.config.spree.tax_provider = Spree::TaxProvider::Internal+ # Password policy for the default auth models. Swap for corporate rules,+ # breach-list lookups or entropy scoring.+ Rails.application.config.spree.password_validator = Spree::PasswordLengthValidator+Rails.application.config.spree.fulfillment_providers = [Spree::FulfillmentProvider::Manual,Spree::FulfillmentProvider::Digital,diff --git a/spree/core/lib/spree/testing_support/factories/user_factory.rb b/spree/core/lib/spree/testing_support/factories/user_factory.rbindex 7a3fba244a..6c60f14a97 100644--- a/spree/core/lib/spree/testing_support/factories/user_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/user_factory.rb@@ -1,7 +1,7 @@FactoryBot.define dofactory :customer, aliases: [:user], class: Spree.customer_class doemail { generate(:random_email) }- password { 'secret' }+ password { 'secret123' }password_confirmation { password }first_name { FFaker::Name.first_name }@@ -19,7 +19,7 @@ FactoryBot.define dofactory :admin_user, class: Spree.admin_user_class doemail { generate(:random_email) }login { email }- password { 'secret' }+ password { 'secret123' }password_confirmation { password }first_name { FFaker::Name.first_name }last_name { FFaker::Name.last_name }diff --git a/spree/core/spec/models/concerns/spree/password_policy_spec.rb b/spree/core/spec/models/concerns/spree/password_policy_spec.rbnew file mode 100644index 0000000000..a9d6e93eef--- /dev/null+++ b/spree/core/spec/models/concerns/spree/password_policy_spec.rb@@ -0,0 +1,121 @@+require 'spec_helper'++RSpec.describe Spree::PasswordPolicy do+ # Run the same battery against both hosts — behavior shared by Customer and+ # AdminUser must not drift on either. Preferences set here are reset between+ # examples by the global reset_spree_preferences before(:each) hook.+ shared_examples 'a password-policy host' do+ describe 'length floor' do+ it 'rejects a password shorter than the configured minimum' do+ record = build(factory, password: 'short12', password_confirmation: 'short12')++ expect(record).not_to be_valid+ expect(record.errors[:password]).to include('is too short (minimum is 8 characters)')+ end++ it 'accepts a password at the minimum length' do+ record = build(factory, password: 'exactly8', password_confirmation: 'exactly8')++ expect(record).to be_valid+ end++ it 'respects a raised minimum' do+ Spree::Config[:minimum_password_length] = 12+ record = build(factory, password: 'exactly8', password_confirmation: 'exactly8')++ expect(record).not_to be_valid+ expect(record.errors[:password]).to include('is too short (minimum is 12 characters)')+ end+ end++ describe 'length ceiling' do+ it 'rejects a password past the bcrypt limit' do+ too_long = 'a' * 73+ record = build(factory, password: too_long, password_confirmation: too_long)++ expect(record).not_to be_valid+ expect(record.errors[:password]).to include('is too long (maximum is 72 characters)')+ end+ end++ describe 'confirmation' do+ it 'rejects a mismatched confirmation' do+ record = build(factory, password: 'password123', password_confirmation: 'different123')++ expect(record).not_to be_valid+ expect(record.errors[:password_confirmation]).to be_present+ end+ end++ describe 'when no password is being set' do+ # The policy runs only while the digest is changing, so raising the floor+ # must never invalidate an already-persisted record.+ it 'leaves a persisted record valid after the minimum is raised' do+ record = create(factory, password: 'exactly8', password_confirmation: 'exactly8')+ Spree::Config[:minimum_password_length] = 30++ expect(record.reload).to be_valid+ end++ it 'allows saving an unrelated attribute after the minimum is raised' do+ record = create(factory, password: 'exactly8', password_confirmation: 'exactly8')+ Spree::Config[:minimum_password_length] = 30++ reloaded = record.reload+ reloaded.first_name = 'Changed'++ expect(reloaded.save).to be true+ end++ it 'still rejects a new short password under the raised floor' do+ record = create(factory, password: 'exactly8', password_confirmation: 'exactly8')+ Spree::Config[:minimum_password_length] = 30++ fresh = record.class.find(record.id)+ fresh.password = 'short12'+ fresh.password_confirmation = 'short12'++ expect(fresh).not_to be_valid+ end++ it 'allows a password-less record' do+ record = build(factory, password: nil, password_confirmation: nil)++ expect(record).to be_valid+ end+ end++ describe 'a swapped validator' do+ before { Spree.password_validator = SpreeSpec::NoDigitsValidator }++ after { Spree.password_validator = Spree::PasswordLengthValidator }++ it 'replaces the built-in length policy' do+ # 'short' is below the 8-char floor but passes the custom rule, proving+ # the default validator no longer runs.+ record = build(factory, password: 'short', password_confirmation: 'short')++ expect(record).to be_valid+ end++ it 'surfaces the custom failure reason on :password' do+ record = build(factory, password: 'has1digit', password_confirmation: 'has1digit')++ expect(record).not_to be_valid+ expect(record.errors[:password]).to include('must not contain digits')+ end+ end+ end++ context 'with Spree::Customer' do+ let(:factory) { :customer }++ it_behaves_like 'a password-policy host'+ end++ context 'with Spree::AdminUser' do+ let(:factory) { :admin_user }++ it_behaves_like 'a password-policy host'+ end+enddiff --git a/spree/core/spec/support/password_validators.rb b/spree/core/spec/support/password_validators.rbnew file mode 100644index 0000000000..12de1998b6--- /dev/null+++ b/spree/core/spec/support/password_validators.rb@@ -0,0 +1,11 @@+# Support classes for Spree::PasswordPolicy specs — a stand-in for the custom+# password validator an integrator would assign to Spree.password_validator.+module SpreeSpec+ class NoDigitsValidator < ActiveModel::Validator+ def validate(record)+ return if record.password.blank?++ record.errors.add(:password, 'must not contain digits') if record.password.match?(/\d/)+ end+ end+end