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
Added `serialized_preferences` and `serialized_preference_schema` hel… (#14032)
Damian Legawiecdbf4c15ad2b3
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rbindex f73a288ee3..bd8b2632a7 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb@@ -110,10 +110,17 @@ module Spreeenddef apply_preferences(resource, preferences)- preferences.each do |key, value|- next unless resource.has_preference?(key.to_sym)+ password_keys = resource.password_preference_keys- resource.set_preference(key.to_sym, value)+ preferences.each do |key, value|+ pref_name = key.to_sym+ next unless resource.has_preference?(pref_name)+ # Round-trip guard: clients fetching a record see masked+ # `:password` values. Submitting the mask back unchanged+ # must NOT overwrite the real secret with `••••cret`.+ next if password_keys.include?(pref_name) && Spree::Preferences::Masking.masked?(value)++ resource.set_preference(pref_name, value)endenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rbindex 1c246dc340..de476b1e03 100644--- a/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb@@ -34,7 +34,7 @@ module Spree{type: calc.to_s,label: calc.respond_to?(:description) ? calc.description : calc.to_s.demodulize.titleize,- preference_schema: calc.respond_to?(:preference_schema) ? calc.preference_schema : []+ preference_schema: calc.respond_to?(:serialized_preference_schema) ? calc.serialized_preference_schema : []}end.sort_by { |entry| entry[:label].to_s }diff --git a/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rbindex 51848ec0a2..cf56b147d4 100644--- a/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb@@ -14,15 +14,8 @@ module Spreeattributes :metadata, :active, :auto_capture, :display_on, :position,created_at: :iso8601, updated_at: :iso8601- attribute :preferences do |payment_method|- payment_method.preferences.to_h- end-- # Class-level schema so admin UIs can render the configuration form- # without a separate /types fetch per record.- attribute :preference_schema do |payment_method|- payment_method.class.preference_schema- end+ attribute :preferences, &:serialized_preferences+ attribute :preference_schema, &:serialized_preference_schemaendendenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rbindex 775230dab9..5792c48539 100644--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb@@ -27,13 +27,8 @@ module Spreeaction.promotion&.prefixed_idend- attribute :preferences do |action|- action.preferences.to_h- end-- attribute :preference_schema do |action|- action.class.preference_schema- end+ attribute :preferences, &:serialized_preferences+ attribute :preference_schema, &:serialized_preference_schemaattribute :label do |action|action.respond_to?(:human_name) ? action.human_name : action.type.to_s.demodulize@@ -51,8 +46,8 @@ module Spree{type: calc.class.api_type,label: calc.class.respond_to?(:description) ? calc.class.description : calc.class.to_s.demodulize.titleize,- preferences: calc.preferences.to_h,- preference_schema: calc.class.preference_schema+ preferences: calc.serialized_preferences,+ preference_schema: calc.serialized_preference_schema}enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rbindex 8b1c42033f..6d81adc842 100644--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb@@ -27,13 +27,8 @@ module Spreerule.promotion&.prefixed_idend- attribute :preferences do |rule|- rule.preferences.to_h- end-- attribute :preference_schema do |rule|- rule.class.preference_schema- end+ attribute :preferences, &:serialized_preferences+ attribute :preference_schema, &:serialized_preference_schemaattribute :label do |rule|rule.respond_to?(:human_name) ? rule.human_name : rule.class.to_s.demodulizediff --git a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rbindex 41f5ade8d5..fb04879e9c 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb@@ -37,6 +37,39 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlleexpect(response).to have_http_status(:ok)expect(json_response['id']).to eq(payment_method.prefixed_id)end++ context 'when the payment method has a :password preference' do+ let!(:payment_method) do+ bogus = create(:bogus_payment_method, stores: [store])+ bogus.set_preference(:dummy_secret_key, 'sk_live_super_secret_value')+ bogus.set_preference(:dummy_key, 'pk_live_visible_key')+ bogus.save!+ bogus+ end++ it 'masks the password preference and never leaks the plaintext secret' do+ get :show, params: { id: payment_method.prefixed_id }, as: :json++ secret = json_response.dig('preferences', 'dummy_secret_key')+ expect(secret).to start_with(Spree::Preferences::Masking::TOKEN)+ expect(secret).to eq("#{Spree::Preferences::Masking::TOKEN}alue")+ expect(response.body).not_to include('sk_live_super_secret_value')+ end++ it 'returns non-password preferences in plaintext' do+ get :show, params: { id: payment_method.prefixed_id }, as: :json++ expect(json_response.dig('preferences', 'dummy_key')).to eq('pk_live_visible_key')+ end++ it 'masks the password preference in the index response too' do+ get :index, as: :json++ entry = json_response['data'].find { |pm| pm['id'] == payment_method.prefixed_id }+ expect(entry.dig('preferences', 'dummy_secret_key')).to start_with(Spree::Preferences::Masking::TOKEN)+ expect(response.body).not_to include('sk_live_super_secret_value')+ end+ endenddescribe 'POST #create' do@@ -78,6 +111,56 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlleexpect(payment_method.reload.name).to eq('Updated')expect(payment_method.reload.active).to be falseend++ context 'when the payment method has a :password preference' do+ let!(:payment_method) do+ bogus = create(:bogus_payment_method, stores: [store])+ bogus.set_preference(:dummy_secret_key, 'sk_live_existing_secret')+ bogus.save!+ bogus+ end++ it 'preserves the existing secret when the submitted value is a masked round-trip' do+ patch :update,+ params: {+ id: payment_method.prefixed_id,+ preferences: { dummy_secret_key: "#{Spree::Preferences::Masking::TOKEN}cret" }+ },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(payment_method.reload.preferred_dummy_secret_key).to eq('sk_live_existing_secret')+ end++ it 'replaces the secret when the submitted value is a new plaintext' do+ patch :update,+ params: {+ id: payment_method.prefixed_id,+ preferences: { dummy_secret_key: 'sk_live_brand_new_secret' }+ },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(payment_method.reload.preferred_dummy_secret_key).to eq('sk_live_brand_new_secret')+ end++ it 'still updates non-password preferences alongside a masked password round-trip' do+ patch :update,+ params: {+ id: payment_method.prefixed_id,+ preferences: {+ dummy_secret_key: "#{Spree::Preferences::Masking::TOKEN}cret",+ dummy_key: 'pk_live_new_public_key'+ }+ },+ as: :json++ expect(response).to have_http_status(:ok)+ payment_method.reload+ expect(payment_method.preferred_dummy_secret_key).to eq('sk_live_existing_secret')+ expect(payment_method.preferred_dummy_key).to eq('pk_live_new_public_key')+ end+ endenddescribe 'DELETE #destroy' do@@ -109,6 +192,18 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlleexpect(types).not_to include('check')end+ # Bogus declares `preference :dummy_secret_key, :password, default: 'SECRETKEY123'`.+ # The discovery endpoint must not leak the default — that's a secret+ # the gateway author shipped, just like a saved value would be.+ it 'redacts password defaults in each provider\'s preference_schema' do+ get :types, as: :json++ bogus = json_response['data'].find { |entry| entry['type'] == 'bogus' }+ secret_field = bogus['preference_schema'].find { |f| f['key'] == 'dummy_secret_key' }+ expect(secret_field['default']).to be_nil+ expect(response.body).not_to include('SECRETKEY123')+ end+context 'with provider gems that ship a top-level Gateway class' do# Reproduces the duplicate-key bug from the admin SPA: two providers# whose demodulized leaf is `"Gateway"` must still get unique `type`diff --git a/spree/api/spec/serializers/spree/api/v3/admin/payment_method_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/payment_method_serializer_spec.rbnew file mode 100644index 0000000000..4e3d2291ea--- /dev/null+++ b/spree/api/spec/serializers/spree/api/v3/admin/payment_method_serializer_spec.rb@@ -0,0 +1,52 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::PaymentMethodSerializer do+ let(:store) { @default_store }+ let(:base_params) { { store: store, currency: 'USD' } }++ describe 'preferences masking' do+ let(:payment_method) do+ pm = create(:bogus_payment_method, stores: [store])+ pm.set_preference(:dummy_secret_key, 'sk_live_super_secret_value')+ pm.set_preference(:dummy_key, 'pk_live_visible_key')+ pm.save!+ pm+ end++ subject(:payload) { described_class.new(payment_method, params: base_params).to_h }++ it 'masks `:password` preferences in the serialized payload' do+ expect(payload['preferences']['dummy_secret_key']).to eq("#{Spree::Preferences::Masking::TOKEN}alue")+ end++ it 'never includes the plaintext secret anywhere in the payload' do+ expect(payload.to_json).not_to include('sk_live_super_secret_value')+ end++ it 'returns non-password preferences in plaintext' do+ expect(payload['preferences']['dummy_key']).to eq('pk_live_visible_key')+ end++ # Bogus declares `preference :dummy_secret_key, :password, default: 'SECRETKEY123'`.+ # A non-empty default on a password preference is itself a secret —+ # `serialized_preference_schema` must nil it out before it hits the wire.+ it 'redacts password defaults in preference_schema' do+ password_field = payload['preference_schema'].find { |f| f[:key] == :dummy_secret_key }+ expect(password_field).not_to be_nil+ expect(password_field[:default]).to be_nil+ expect(payload.to_json).not_to include('SECRETKEY123')+ end++ # `:key_string` is an internal cache used by `Masking.serialize` to+ # avoid `to_s` allocations per request. It must not leak into the+ # wire payload — the documented shape is `{ key, type, default }`.+ it 'does not expose the internal :key_string cache in preference_schema entries' do+ expect(payload['preference_schema']).to all(have_key(:key))+ expect(payload['preference_schema']).to all(have_key(:type))+ expect(payload['preference_schema']).to all(have_key(:default))+ expect(payload['preference_schema']).not_to include(have_key(:key_string))+ end+ end+enddiff --git a/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rbnew file mode 100644index 0000000000..bb9b42d459--- /dev/null+++ b/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb@@ -0,0 +1,75 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::PromotionActionSerializer do+ let(:store) { @default_store }+ let(:promotion) { create(:promotion, stores: [store]) }+ let(:base_params) { { store: store, currency: 'USD' } }++ describe 'preferences masking' do+ # FreeShipping is the simplest concrete subclass of PromotionAction.+ # We splice a `:password` preference into its schema for the duration+ # of the example so the masking behaviour can be asserted without+ # needing a full new STI subclass + registry registration.+ let(:action) do+ action = Spree::Promotion::Actions::FreeShipping.create!(promotion: promotion)+ action.preferences[:api_secret] = 'sk_action_super_secret_value'+ action.preferences[:webhook_url] = 'https://example.com/hook'++ stubbed_schema = [+ { key: :api_secret, type: :password, default: nil },+ { key: :webhook_url, type: :string, default: nil }+ ]+ allow(action.class).to receive(:preference_schema).and_return(stubbed_schema)+ action+ end++ subject(:payload) { described_class.new(action, params: base_params).to_h }++ it 'masks `:password` preferences in the serialized payload' do+ expect(payload['preferences']['api_secret']).to eq("#{Spree::Preferences::Masking::TOKEN}alue")+ end++ it 'never includes the plaintext secret anywhere in the payload' do+ expect(payload.to_json).not_to include('sk_action_super_secret_value')+ end++ it 'returns non-password preferences in plaintext' do+ expect(payload['preferences']['webhook_url']).to eq('https://example.com/hook')+ end+ end++ describe 'nested calculator preferences masking' do+ let(:action) do+ Spree::Promotion::Actions::CreateAdjustment.create!(+ promotion: promotion,+ calculator: Spree::Calculator::FlatRate.new(preferred_amount: 5)+ )+ end++ before do+ # Splice a `:password` preference into the calculator's schema so+ # the nested-calculator masking path is exercised end-to-end.+ action.calculator.preferences[:api_secret] = 'sk_calc_super_secret_value'+ stubbed_schema = [+ { key: :api_secret, type: :password, default: nil },+ { key: :amount, type: :decimal, default: 0 }+ ]+ allow(action.calculator.class).to receive(:preference_schema).and_return(stubbed_schema)+ end++ # The `calculator` attribute is a plain Ruby Hash returned from an+ # Alba block — its keys are symbols, while the inner `preferences`+ # hash is string-keyed (it's the wire-shape from `Masking.serialize`).+ subject(:payload) { described_class.new(action, params: { store: store, currency: 'USD' }).to_h }++ it 'masks `:password` preferences on the nested calculator' do+ expect(payload['calculator'][:preferences]['api_secret']).to eq('••••alue')+ end++ it 'never includes the plaintext calculator secret anywhere in the payload' do+ expect(payload.to_json).not_to include('sk_calc_super_secret_value')+ end+ end+enddiff --git a/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rbnew file mode 100644index 0000000000..7b4ca17005--- /dev/null+++ b/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb@@ -0,0 +1,41 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::PromotionRuleSerializer do+ let(:store) { @default_store }+ let(:promotion) { create(:promotion, stores: [store]) }+ let(:base_params) { { store: store, currency: 'USD' } }++ describe 'preferences masking' do+ # Currency is the simplest concrete subclass of PromotionRule. As+ # with the action serializer spec, we splice a `:password` preference+ # into its schema for the duration of the example so the masking+ # path can be asserted without a full new STI subclass.+ let(:rule) do+ rule = Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')+ rule.preferences[:api_secret] = 'sk_rule_super_secret_value'++ stubbed_schema = [+ { key: :currency, type: :string, default: nil },+ { key: :api_secret, type: :password, default: nil }+ ]+ allow(rule.class).to receive(:preference_schema).and_return(stubbed_schema)+ rule+ end++ subject(:payload) { described_class.new(rule, params: base_params).to_h }++ it 'masks `:password` preferences in the serialized payload' do+ expect(payload['preferences']['api_secret']).to eq("#{Spree::Preferences::Masking::TOKEN}alue")+ end++ it 'never includes the plaintext secret anywhere in the payload' do+ expect(payload.to_json).not_to include('sk_rule_super_secret_value')+ end++ it 'returns non-password preferences in plaintext' do+ expect(payload['preferences']['currency']).to eq('USD')+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rbindex a224f38246..11a3b4af67 100644--- a/spree/core/app/models/concerns/spree/preference_schema.rb+++ b/spree/core/app/models/concerns/spree/preference_schema.rb@@ -8,22 +8,57 @@ module Spreemodule PreferenceSchemaextend ActiveSupport::Concern+ delegate :preference_schema, :serialized_preference_schema, :password_preference_keys, to: :class++ # Wire-safe view of `preferences` with `:password`-typed values+ # masked. Lives here (not in the serializer) so any consumer holding+ # a Preferable instance gets the same safety guarantee — secrets+ # must never leave the server in plaintext. Keys are stringified to+ # match the wire shape expected by JSON clients.+ #+ # @return [Hash{String => Object}]+ def serialized_preferences+ Spree::Preferences::Masking.serialize(self)+ end+class_methods do# Returns `[{ key:, type:, default: }]` for every preference declared# on this class (and its ancestors). Skips deprecated preferences.#- # The shape is intentionally narrow: the frontend only needs the type- # (`string`, `text`, `integer`, `decimal`, `boolean`, `array`, etc.) and- # the default to render a sensible field. Validation lives server-side.- ## Memoized at class load — the schema is derived from the static# `preference :name, :type` declarations, so it can never change at- # runtime. This keeps index responses cheap (the serializer embeds- # `preference_schema` on every row).+ # runtime. Each entry also caches `key_string` (frozen) so hot-path+ # serializers don't allocate `pref.to_s` per request.def preference_schema@preference_schema ||= compute_preference_schemaend+ # Wire-safe variant of `preference_schema` with `:password`+ # defaults nilled out. A gateway author can set a non-empty+ # default for a `:password` preference; without this redaction the+ # default leaks alongside the masked live value. Memoized so admin+ # index responses don't re-allocate per row.+ #+ # Strips `:key_string` — that's a server-only cache used by+ # `Masking.serialize` to avoid `to_s` allocations per request, not+ # part of the documented `{ key, type, default }` wire shape.+ def serialized_preference_schema+ @serialized_preference_schema ||= preference_schema.map do |field|+ wire = { key: field[:key], type: field[:type], default: field[:default] }+ wire[:default] = nil if field[:type] == :password+ wire.freeze+ end.freeze+ end++ # Set of `:password`-typed preference keys for this class. Memoized+ # so write-side guards (e.g. the masked-round-trip check) don't+ # walk the schema or fall back to a `rescue NoMethodError`.+ def password_preference_keys+ @password_preference_keys ||= preference_schema+ .each_with_object(Set.new) { |field, set| set << field[:key] if field[:type] == :password }+ .freeze+ end+def compute_preference_schemainstance = newinstance.defined_preferences.filter_map do |pref|@@ -31,9 +66,10 @@ module Spree{key: pref,+ key_string: pref.to_s.freeze,type: instance.preference_type(pref),default: safe_preference_default(instance, pref)- }+ }.freezeendrescue StandardError[]@@ -50,14 +86,16 @@ module Spree# Returns a `[{ type:, label:, description:, preference_schema: }]`# array for every concrete subclass in `subclasses`. Sorted by label- # for stable output.+ # for stable output. Uses `serialized_preference_schema` so+ # `:password` defaults are redacted — `/types` is an unauthenticated+ # discovery surface and must never leak gateway-shipped defaults.def subclasses_with_preference_schemaregistered_subclasses.map do |klass|{type: klass.api_type,label: subclass_label(klass),description: klass.respond_to?(:description) ? klass.description : nil,- preference_schema: klass.respond_to?(:preference_schema) ? klass.preference_schema : []+ preference_schema: klass.respond_to?(:serialized_preference_schema) ? klass.serialized_preference_schema : []}end.sort_by { |entry| entry[:label] }enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 2bf7154998..39d54387b5 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -459,6 +459,7 @@ require 'spree/core/controller_helpers/turbo'require 'spree/core/preferences/store'require 'spree/core/preferences/scoped_store'require 'spree/core/preferences/runtime_configuration'+require 'spree/core/preferences/masking'require 'spree/core/permission_configuration'require 'spree/core/ransack_configuration'diff --git a/spree/core/lib/spree/core/preferences/masking.rb b/spree/core/lib/spree/core/preferences/masking.rbnew file mode 100644index 0000000000..cf7fb51ede--- /dev/null+++ b/spree/core/lib/spree/core/preferences/masking.rb@@ -0,0 +1,47 @@+# frozen_string_literal: true++module Spree+ module Preferences+ # Masks `:password`-typed preferences so secrets (API keys, OAuth+ # tokens, signing secrets, …) never leave the server in plaintext.+ #+ # The mask token is a bullet sequence followed by the last 4+ # characters of the original value — Stripe's "stored, here's the+ # last 4" pattern.+ module Masking+ TOKEN = '••••'++ # @param value [Object] the preference value to mask+ # @return [String, nil] masked string, or nil if value is blank+ def self.mask(value)+ return nil if value.blank?++ "#{TOKEN}#{value.to_s.last(4)}"+ end++ # @param value [Object] a value previously returned by `mask`+ # @return [Boolean] true if value carries the mask token+ def self.masked?(value)+ value.is_a?(String) && value.start_with?(TOKEN)+ end++ # Serializes a Preferable's `preferences` hash for the wire,+ # masking `:password` values. Keys are stringified to match the+ # wire shape expected by JSON clients — schema entries built by+ # `compute_preference_schema` cache `:key_string` to avoid a+ # `to_s` allocation per field per request.+ #+ # @param preferable [#preferences, #preference_schema, nil] any object+ # that includes `Spree::Preferences::Preferable` and `Spree::PreferenceSchema`+ # @return [Hash{String => Object}]+ def self.serialize(preferable)+ return {} if preferable.nil?++ preferable.preference_schema.each_with_object({}) do |field, hash|+ value = preferable.preferences[field[:key]]+ hash[field[:key_string] || field[:key].to_s] = field[:type] == :password ? mask(value) : value+ end+ end+ end+ end+enddiff --git a/spree/core/spec/models/spree/preferences/masking_spec.rb b/spree/core/spec/models/spree/preferences/masking_spec.rbnew file mode 100644index 0000000000..948c42f360--- /dev/null+++ b/spree/core/spec/models/spree/preferences/masking_spec.rb@@ -0,0 +1,101 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Preferences::Masking do+ describe '.mask' do+ it 'returns nil for blank values' do+ expect(described_class.mask(nil)).to be_nil+ expect(described_class.mask('')).to be_nil+ end++ it 'masks long secrets, preserving only the last 4 characters' do+ expect(described_class.mask('sk_test_abcdef1234')).to eq('••••1234')+ end++ it 'masks short secrets without exposing the whole value when shorter than 4' do+ expect(described_class.mask('abc')).to eq('••••abc')+ end++ it 'coerces non-string values to a string before masking' do+ expect(described_class.mask(1234567890)).to eq('••••7890')+ end+ end++ describe '.masked?' do+ it 'detects a masked string by its leading token' do+ expect(described_class.masked?('••••1234')).to be true+ end++ it 'returns false for plaintext values' do+ expect(described_class.masked?('sk_test_abcdef1234')).to be false+ expect(described_class.masked?('')).to be false+ expect(described_class.masked?(nil)).to be false+ expect(described_class.masked?(42)).to be false+ end+ end++ describe '.serialize' do+ # A throwaway Preferable — keeps the test focused on the masking+ # helper instead of coupling to whichever production model happens+ # to expose a :password preference today. Provides its own+ # `preferences` hash since Preferable is normally mixed into an+ # ActiveRecord model that supplies the serialized column.+ let(:preferable_class) do+ Class.new do+ include Spree::Preferences::Preferable+ include Spree::PreferenceSchema++ preference :api_key, :string, default: 'PUBLIC123'+ preference :api_secret, :password, default: 'SECRET456'+ preference :ratio, :decimal, default: 0.5+ preference :enabled, :boolean, default: true++ def preferences+ @preferences ||= {}+ end++ def self.name+ 'TestPreferable'+ end+ end+ end++ let(:preferable) { preferable_class.new }++ it 'returns {} when the receiver is nil' do+ expect(described_class.serialize(nil)).to eq({})+ end++ # Wire shape: keys are stringified so the output matches what JSON+ # consumers expect, regardless of whether the underlying preference+ # hash uses symbol or string keys internally.+ it 'returns plaintext for non-password preferences with string keys' do+ preferable.set_preference(:api_key, 'pk_live_visible')+ preferable.set_preference(:ratio, 0.25)+ preferable.set_preference(:enabled, false)++ result = described_class.serialize(preferable)++ expect(result['api_key']).to eq('pk_live_visible')+ expect(result['ratio']).to eq(0.25)+ expect(result['enabled']).to be false+ end++ it 'masks password-typed preferences' do+ preferable.set_preference(:api_secret, 'sk_live_extremely_secret_value')++ expect(described_class.serialize(preferable)['api_secret']).to eq('••••alue')+ end++ it 'returns nil for unset password preferences (no default leakage)' do+ preferable.preferences.delete(:api_secret)++ result = described_class.serialize(preferable)++ expect(result.fetch('api_secret')).to be_nil+ # Sanity check: the unmasked default would have leaked here.+ expect(result.fetch('api_secret')).not_to eq('SECRET456')+ end+ end+end