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
Give sellers a panel of their own to sign in to
Damian Legawiec4b6166f06fa6
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6063a9139e..9363b18444 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -233,7 +233,7 @@ end``````ruby-class CreateSpreeMetafields < ActiveRecord::Migration[7.2]+class CreateSpreeMetafields < ActiveRecord::Migration[8.1]def changecreate_table :spree_metafields do |t|t.string :key, null: falsediff --git a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rbindex 0db7ca880e..b36264fffa 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb@@ -11,6 +11,11 @@ module SpreeJWT_AUDIENCE_STORE = 'store_api'.freezeJWT_AUDIENCE_ADMIN = 'admin_api'.freeze+ # Marketplace sellers share the admin user class, so the audience — not+ # the principal — is what keeps a seller's token off the admin API and+ # an admin's off the vendor panel. Enforced at decode, before any store+ # or vendor is resolved.+ JWT_AUDIENCE_VENDOR = 'vendor_api'.freezeJWT_ISSUER = 'spree'.freezeincluded dodiff --git a/spree/api/app/controllers/concerns/spree/api/v3/vendor/auth_cookies.rb b/spree/api/app/controllers/concerns/spree/api/v3/vendor/auth_cookies.rbnew file mode 100644index 0000000000..931b87eb27--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/vendor/auth_cookies.rb@@ -0,0 +1,62 @@+module Spree+ module Api+ module V3+ module Vendor+ # Cookie-based delivery for seller refresh tokens.+ #+ # Both the name and the path differ from the admin cookie, and both+ # matter: a shared name would let one browser's admin session be+ # redeemed on the seller panel, and the path is what stops each+ # surface's cookie being sent to the other's endpoints. Together with+ # the audience stamped on the token itself, a session belongs to+ # exactly one surface.+ #+ # The CSRF reasoning is the admin concern's, unchanged: SameSite plus+ # the Spree::AllowedOrigin allowlist. A seller dashboard served from an+ # origin outside that allowlist would need its own answer.+ module AuthCookies+ extend ActiveSupport::Concern++ # ActionController::API drops Cookies — re-include it on the auth+ # controller only; the rest of the branch stays stateless.+ included do+ include ActionController::Cookies+ end++ REFRESH_COOKIE_NAME = :spree_vendor_refresh_token+ COOKIE_PATH = '/api/v3/vendor/auth'.freeze++ private++ def set_refresh_cookie(refresh_token)+ cookies.signed[REFRESH_COOKIE_NAME] = base_cookie_attributes.merge(+ value: refresh_token.token,+ expires: refresh_token.expires_at,+ path: COOKIE_PATH,+ httponly: true+ )+ end++ def clear_refresh_cookie+ cookies.delete(REFRESH_COOKIE_NAME, path: COOKIE_PATH)+ end++ def refresh_token_from_cookie+ cookies.signed[REFRESH_COOKIE_NAME].presence+ end++ # Keyed off the request scheme, not the Rails env: Rails silently+ # refuses to write a Secure cookie on a non-SSL request, so an app+ # served over plain http would never receive one at all.+ def base_cookie_attributes+ if request.ssl?+ { secure: true, same_site: :none }+ else+ { secure: false, same_site: :lax }+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/vendor/vendor_context.rb b/spree/api/app/controllers/concerns/spree/api/v3/vendor/vendor_context.rbnew file mode 100644index 0000000000..89d23266a9--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/vendor/vendor_context.rb@@ -0,0 +1,112 @@+module Spree+ module Api+ module V3+ module Vendor+ # Resolves which seller a request acts as.+ #+ # The inverse of the admin branch's store context: there, the store is+ # named by a header or a key and falls back to the default. Here the+ # vendor is named by the header, membership is checked against it, and+ # the store is *derived* from the vendor — never sent, never defaulted.+ # A request that names no vendor the caller belongs to has no tenant at+ # all, which is an error rather than a default.+ #+ # Included into both branch anchors (BaseController and+ # ResourceController): they are parallel inheritance chains, so a+ # concern on one is not on the other.+ module VendorContext+ extend ActiveSupport::Concern++ VENDOR_HEADER = 'X-Spree-Vendor-Id'.freeze++ # Prepended, like the admin branch's store context, because the+ # shared base chain reads the store while setting up locale and+ # currency — before any ordinary callback runs.+ #+ # Resolving a vendor needs the caller, so this identifies them first+ # by calling `authenticate_user`, which is idempotent and is the same+ # method the authentication callback runs later. That later callback+ # remains the authority on whether the request may proceed; this only+ # establishes the tenant early enough for the chain beneath it.+ included do+ prepend_before_action :set_current_vendor_context+ end++ # The vendor this request acts as, or nil when the header names none+ # the caller belongs to.+ #+ # @return [Spree::Vendor, nil]+ def current_vendor+ return @current_vendor if defined?(@current_vendor)++ @current_vendor = resolve_current_vendor+ end++ # Derived from the vendor, so a seller can never widen their reach by+ # sending a store header.+ #+ # Falls back to the default store only when no vendor resolved — such+ # a request is already being rejected, and the chain beneath this+ # (locale and currency setup) reads the store before the rejection+ # renders. Nothing tenant-bearing is served through the fallback.+ #+ # @return [Spree::Store, nil]+ def current_store+ current_vendor&.store || Spree::Store.default+ end++ private++ def set_current_vendor_context+ # Identify the caller before resolving their vendor. Safe to call+ # here: it only populates @current_user, and the authentication+ # callback still decides whether an unidentified request proceeds.+ authenticate_user++ # Assigned even when nil: leaving the previous request's value on a+ # reused thread would expose another tenant to anything reading it+ # before the rejection lands.+ Spree::Current.store = current_store++ # An unauthenticated request has no vendor to resolve, and saying+ # so is authentication's job — let it answer with a 401 rather than+ # reporting a missing tenant.+ return true if current_user.nil?++ require_current_vendor!+ end++ def require_current_vendor!+ return true if current_vendor++ render_error(+ code: ErrorHandler::ERROR_CODES[:access_denied],+ message: Spree.t(:vendor_access_denied),+ status: :forbidden+ )+ false+ end++ # Membership is holding a role the vendor owns — the same question+ # the store back office asks, pointed at a different resource. A+ # header naming a vendor the caller has no role on resolves to+ # nothing, so it reads as "no such vendor" rather than "denied",+ # which is also what stops the header being used to enumerate.+ def resolve_current_vendor+ return nil if vendor_id_header.blank?+ return nil unless current_user.respond_to?(:vendors)++ id = Spree::Vendor.decode_own_prefixed_id(vendor_id_header)+ return nil if id.blank?++ current_user.vendors.find_by(id: id)+ end++ def vendor_id_header+ request.headers[VENDOR_HEADER]+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/vendor_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/vendor_authentication.rbnew file mode 100644index 0000000000..c5ee7e993c--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/vendor_authentication.rb@@ -0,0 +1,40 @@+module Spree+ module Api+ module V3+ # Authentication for the marketplace seller panel.+ #+ # Deliberately not a subclass or variant of AdminAuthentication: a seller+ # holds no secret API key (keys are store-bound and grant `manage :all`),+ # so this surface is JWT-only and the key path simply does not exist here.+ module VendorAuthentication+ extend ActiveSupport::Concern++ included do+ after_action :set_no_store_cache+ end++ protected++ # Rejects an admin or storefront token before any vendor is resolved.+ def expected_audience+ Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_VENDOR+ end++ # Capability comes from the roles the seller holds *on this vendor*.+ # Passing the resource is what stops a store role — or the store's+ # `admin` super-role — being read here (see Spree::Ability).+ def ability_options+ { store: current_store, resource: current_vendor }+ end++ def authenticate_vendor!+ require_authentication!+ end++ def set_no_store_cache+ response.headers['Cache-Control'] = 'private, no-store'+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/vendor/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/vendor/auth_controller.rbnew file mode 100644index 0000000000..3a190a015d--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/vendor/auth_controller.rb@@ -0,0 +1,169 @@+module Spree+ module Api+ module V3+ module Vendor+ # Sign-in for the marketplace seller panel.+ #+ # Its own surface rather than a reuse of the admin one, so login policy+ # can differ per panel: a store that requires SSO for its own staff can+ # still let sellers sign in with a password, because the two read+ # different strategy registries against the same user class.+ class AuthController < Vendor::BaseController+ include Spree::Api::V3::Vendor::AuthCookies+ include Spree::Api::V3::AuthenticationStrategies++ skip_scope_check!++ # A distinct `name:` per declaration — without one Rails keys every+ # counter in the controller on one cache entry, so the provider list+ # a login page fetches on every load would spend the login budget.+ rate_limit to: Spree::Api::Config[:rate_limit_login],+ within: Spree::Api::Config[:rate_limit_window].seconds,+ store: Rails.cache, only: :create, name: 'vendor_login',+ with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_login]) }+ rate_limit to: Spree::Api::Config[:rate_limit_refresh],+ within: Spree::Api::Config[:rate_limit_window].seconds,+ store: Rails.cache, only: :providers, name: 'vendor_providers',+ with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_refresh]) }+ rate_limit to: Spree::Api::Config[:rate_limit_refresh],+ within: Spree::Api::Config[:rate_limit_window].seconds,+ store: Rails.cache, only: [:refresh, :logout], name: 'vendor_refresh',+ with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_refresh]) }++ # Signing in is what establishes which vendors the caller may act as,+ # so these actions run before any vendor is known.+ skip_before_action :set_current_vendor_context, only: [:create, :refresh, :logout, :providers]+ skip_before_action :authenticate_vendor!, only: [:create, :refresh, :logout, :providers]++ # POST /api/v3/vendor/auth/login+ def create+ strategy = authentication_strategy+ return unless strategy++ result = strategy.authenticate+ return render_authentication_failed(result.error) unless result.success?++ user = result.value+ # A store's own staff share this user class, so authenticating is+ # not enough: without a role on some vendor there is no panel to+ # sign in to, and minting a token would hand out an audience the+ # holder can do nothing with.+ return render_authentication_failed(Spree.t(:vendor_membership_required)) unless user.vendor_member?++ set_refresh_cookie(+ Spree::RefreshToken.create_for(+ user,+ audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_VENDOR,+ request_env: request_env_for_token+ )+ )+ render json: auth_response(user)+ end++ # GET /api/v3/vendor/auth/providers+ def providers+ render json: { providers: Spree.vendor_authentication_strategies.describe }+ end++ # POST /api/v3/vendor/auth/refresh+ def refresh+ refresh_token_value = refresh_token_from_cookie++ if refresh_token_value.blank?+ return render_error(+ code: ErrorHandler::ERROR_CODES[:invalid_refresh_token],+ message: 'Refresh token cookie missing',+ status: :unauthorized+ )+ end++ # Narrowed by audience: a token minted on another surface must not+ # be exchangeable for a vendor one.+ refresh_token = Spree::RefreshToken.active.+ for_audience(Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_VENDOR).+ find_by(token: refresh_token_value)++ if refresh_token.nil?+ clear_refresh_cookie+ return render_error(+ code: ErrorHandler::ERROR_CODES[:invalid_refresh_token],+ message: 'Invalid or expired refresh token',+ status: :unauthorized+ )+ end++ user = refresh_token.user+ # Membership can be revoked while a session is live; the refresh is+ # where that takes effect.+ unless user.vendor_member?+ refresh_token.destroy+ clear_refresh_cookie+ return render_error(+ code: ErrorHandler::ERROR_CODES[:access_denied],+ message: Spree.t(:vendor_membership_required),+ status: :forbidden+ )+ end++ set_refresh_cookie(refresh_token.rotate!(request_env: request_env_for_token))+ render json: auth_response(user)+ end++ # POST /api/v3/vendor/auth/logout+ def logout+ refresh_token_value = refresh_token_from_cookie++ if refresh_token_value.present?+ Spree::RefreshToken.+ for_audience(Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_VENDOR).+ find_by(token: refresh_token_value)&.destroy+ end++ clear_refresh_cookie+ head :no_content+ end++ private++ def render_authentication_failed(message)+ render_error(+ code: ErrorHandler::ERROR_CODES[:authentication_failed],+ message: message,+ status: :unauthorized+ )+ end++ def auth_response(user)+ {+ token: generate_jwt(user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_VENDOR),+ user: Spree.api.admin_user_serializer.new(user, params: { store: user.vendors.first&.store }).to_h,+ vendors: serialized_vendors(user)+ }+ end++ # The panel needs these to choose an X-Spree-Vendor-Id before it can+ # make any other request.+ def serialized_vendors(user)+ user.vendors.map { |vendor| { id: vendor.prefixed_id, name: vendor.name, status: vendor.status } }+ end++ def authentication_strategies+ Spree.vendor_authentication_strategies+ end++ def authentication_user_class+ Spree.admin_user_class+ end++ def jwt_expiration+ Spree::Api::Config[:admin_jwt_expiration]+ end++ def request_env_for_token+ { ip_address: request.remote_ip, user_agent: request.user_agent&.truncate(255) }+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/vendor/base_controller.rb b/spree/api/app/controllers/spree/api/v3/vendor/base_controller.rbnew file mode 100644index 0000000000..cf478b87ca--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/vendor/base_controller.rb@@ -0,0 +1,25 @@+module Spree+ module Api+ module V3+ module Vendor+ # Anchor for the marketplace seller panel.+ #+ # Deliberately not a subclass of the admin anchor: the admin branch+ # resolves everything through `current_store`, and inheriting those+ # lookups is precisely how a seller would come to read the whole+ # store. Concerns and workflows are shared; controllers are not.+ #+ # Mirrors Vendor::ResourceController — they anchor parallel inheritance+ # branches, so a concern added to one must be added to the other.+ class BaseController < Spree::Api::V3::BaseController+ include Spree::Api::V3::Vendor::VendorContext+ include Spree::Api::V3::VendorAuthentication++ before_action :authenticate_vendor!++ include Spree::Api::V3::ScopedAuthorization+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/vendor/me_controller.rb b/spree/api/app/controllers/spree/api/v3/vendor/me_controller.rbnew file mode 100644index 0000000000..1115b8b102--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/vendor/me_controller.rb@@ -0,0 +1,64 @@+module Spree+ module Api+ module V3+ module Vendor+ # The signed-in seller: who they are, which vendors they act for, and+ # what they may do on the selected one.+ #+ # Structurally exempt from vendor scoping — this is what tells the+ # panel which X-Spree-Vendor-Id to send, so it has to answer before one+ # is chosen. Sending the header still narrows `permission_keys` to that+ # vendor.+ class MeController < Vendor::BaseController+ skip_scope_check!+ skip_before_action :set_current_vendor_context+ before_action :require_current_user!++ def show+ render json: me_response+ end++ private++ def me_response+ {+ user: Spree.api.admin_user_serializer.new(current_user, params: serializer_params).to_h,+ vendors: serialized_vendors,+ permission_keys: permission_keys+ }+ end++ def serialized_vendors+ current_user.vendors.map do |vendor|+ { id: vendor.prefixed_id, name: vendor.name, slug: vendor.slug, status: vendor.status }+ end+ end++ # Empty until a vendor is named: capability is per vendor, so there is+ # no meaningful answer spanning all of them.+ def permission_keys+ return [] if current_vendor.nil?++ ability = current_ability+ ability.respond_to?(:permission_keys) ? ability.permission_keys : []+ end++ def serializer_params+ { store: current_store || current_user.vendors.first&.store }+ end++ def require_current_user!+ return true if current_user++ render_error(+ code: ErrorHandler::ERROR_CODES[:record_not_found],+ message: Spree.t(:me_no_current_user),+ status: :not_found+ )+ false+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/vendor/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/vendor/resource_controller.rbnew file mode 100644index 0000000000..5f14ac124d--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/vendor/resource_controller.rb@@ -0,0 +1,57 @@+module Spree+ module Api+ module V3+ module Vendor+ # Anchor for seller-facing CRUD.+ #+ # Mirrors Vendor::BaseController's concerns; any concern added to one+ # must be added to the other, since they anchor parallel inheritance+ # branches rather than one chain.+ class ResourceController < Spree::Api::V3::ResourceController+ include Spree::Api::V3::Vendor::VendorContext+ include Spree::Api::V3::VendorAuthentication+ include Spree::Api::V3::ScopedAuthorization++ protected++ def authenticate_request!+ authenticate_vendor!+ end++ # Every collection is rooted in the seller's own records.+ #+ # The inherited implementation roots at `for_store(current_store)`,+ # which on this branch would hand a seller the whole marketplace —+ # so subclasses name a `vendor_association` and the root scope comes+ # from the vendor itself. Tenancy is this fetch, not the ability:+ # authorizing without it reads store-wide.+ def scope+ return super if @parent.present?++ base_scope = current_vendor.public_send(vendor_association)+ base_scope = base_scope.includes(scope_includes) if scope_includes.any?+ base_scope = base_scope.preload_associations_lazily+ model_class.include?(Spree::TranslatableResource) ? base_scope.i18n : base_scope+ end++ # The vendor association this controller reads through, defaulting to+ # the model's plural name (`Spree::Product` -> `products`). Override+ # when the association is named differently.+ #+ # @return [Symbol]+ def vendor_association+ model_class.table_name.delete_prefix('spree_').to_sym+ end++ def authorize_resource!(resource = @resource, action = action_name.to_sym)+ authorize!(action, resource)+ end++ def authorize_parent!(parent)+ authorize!(parent_ability_action, parent)+ end+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex fef5311c0d..b104b19e65 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -574,6 +574,21 @@ Spree::Core::Engine.add_routes doendend+ # The marketplace seller panel. A branch of its own rather than a+ # narrowing of :admin — every endpoint here scope-fetches through+ # current_vendor, which is what makes cross-seller access impossible by+ # construction rather than by rule.+ namespace :vendor do+ # Everything unauthenticated lives under auth/, so the refresh+ # cookie's path covers it and nothing else.+ post 'auth/login', to: 'auth#create'+ post 'auth/refresh', to: 'auth#refresh'+ post 'auth/logout', to: 'auth#logout'+ get 'auth/providers', to: 'auth#providers'++ get 'me', to: 'me#show'+ end+# Webhooks (outside of store namespace — no API key authentication)namespace :webhooks dopost 'payments/:payment_method_id', to: 'payments#create', as: :payment_webhookdiff --git a/spree/api/lib/spree/api/testing_support/v3/base.rb b/spree/api/lib/spree/api/testing_support/v3/base.rbindex 3462cdcd20..793903e1e5 100644--- a/spree/api/lib/spree/api/testing_support/v3/base.rb+++ b/spree/api/lib/spree/api/testing_support/v3/base.rb@@ -80,6 +80,33 @@ shared_context 'API v3 Admin authenticated' dolet(:headers) { bearer_headers }end+# The marketplace seller panel. Deliberately no `current_vendor` stub: the+# header and the membership lookup behind it are what these specs exist to+# exercise, so stubbing them would test nothing.+shared_context 'API v3 Vendor' do+ let(:store) { @default_store || create(:store, default: true) }+ let(:vendor) { create(:vendor, :approved, store: store) }+ let(:vendor_role) { create(:role, name: 'Seller', resource: vendor, permissions: %w[write_products]) }+ let(:vendor_user) do+ create(:admin_user, :without_admin_role).tap { |user| vendor.add_user(user, vendor_role) }+ end++ let(:vendor_jwt_token) do+ Spree::Api::V3::TestingSupport.generate_jwt(+ vendor_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_VENDOR+ )+ end+ let(:vendor_headers) do+ { 'Authorization' => "Bearer #{vendor_jwt_token}", 'X-Spree-Vendor-Id' => vendor.prefixed_id }+ end+end++shared_context 'API v3 Vendor authenticated' do+ include_context 'API v3 Vendor'++ let(:headers) { vendor_headers }+end+# Authenticates as an admin whose ability is restricted to specific catalog# permission keys, so authorization specs can assert what a limited role can# and cannot do. Define `custom_permissions` (an array of catalog keys, e.g.diff --git a/spree/api/spec/controllers/spree/api/v3/vendor/base_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/vendor/base_controller_spec.rbnew file mode 100644index 0000000000..3eb8dc82dc--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/vendor/base_controller_spec.rb@@ -0,0 +1,127 @@+require 'spec_helper'++# Anonymous controller so the branch's authentication and vendor resolution can+# be exercised without depending on any particular endpoint existing yet.+class Spree::Api::V3::Vendor::TestController < Spree::Api::V3::Vendor::BaseController+ skip_scope_check!++ def index+ render json: { ok: true, vendor_id: current_vendor&.prefixed_id, store_id: current_store&.prefixed_id }+ end+end++RSpec.describe Spree::Api::V3::Vendor::BaseController, type: :controller do+ controller(Spree::Api::V3::Vendor::TestController) do+ skip_scope_check!++ def index+ render json: { ok: true, vendor_id: current_vendor&.prefixed_id, store_id: current_store&.prefixed_id }+ end+ end++ render_views++ include_context 'API v3 Vendor'++ before { routes.draw { get 'index' => 'spree/api/v3/vendor/test#index' } }++ describe 'a seller signing in to their own panel' do+ before { request.headers.merge!(vendor_headers) }++ it 'resolves the vendor and derives the store from it' do+ get :index++ expect(response).to have_http_status(:ok)+ expect(json_response['vendor_id']).to eq(vendor.prefixed_id)+ expect(json_response['store_id']).to eq(store.prefixed_id)+ end+ end++ # The audience is checked at decode, before any vendor is resolved, so these+ # never reach the membership lookup at all.+ describe 'tokens minted for another surface' do+ it 'refuses an admin token' do+ admin = create(:admin_user)+ token = Spree::Api::V3::TestingSupport.generate_jwt(+ admin, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN+ )+ request.headers['Authorization'] = "Bearer #{token}"+ request.headers['X-Spree-Vendor-Id'] = vendor.prefixed_id++ get :index++ expect(response).to have_http_status(:unauthorized)+ end++ it 'refuses a storefront token' do+ token = Spree::Api::V3::TestingSupport.generate_jwt(+ vendor_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_STORE+ )+ request.headers['Authorization'] = "Bearer #{token}"+ request.headers['X-Spree-Vendor-Id'] = vendor.prefixed_id++ get :index++ expect(response).to have_http_status(:unauthorized)+ end++ it 'refuses a request with no token at all' do+ request.headers['X-Spree-Vendor-Id'] = vendor.prefixed_id++ get :index++ expect(response).to have_http_status(:unauthorized)+ end+ end++ describe 'acting as a vendor the caller does not belong to' do+ let(:other_vendor) { create(:vendor, :approved, store: store) }++ it 'is forbidden' do+ request.headers['Authorization'] = "Bearer #{vendor_jwt_token}"+ request.headers['X-Spree-Vendor-Id'] = other_vendor.prefixed_id++ get :index++ expect(response).to have_http_status(:forbidden)+ end++ # A vendor on another store is no more reachable than one on this store —+ # the membership lookup never consults the store at all.+ it 'is forbidden across stores too' do+ foreign = create(:vendor, :approved, store: create(:store))+ request.headers['Authorization'] = "Bearer #{vendor_jwt_token}"+ request.headers['X-Spree-Vendor-Id'] = foreign.prefixed_id++ get :index++ expect(response).to have_http_status(:forbidden)+ end+ end++ describe 'naming no vendor' do+ it 'is forbidden rather than falling back to a default' do+ request.headers['Authorization'] = "Bearer #{vendor_jwt_token}"++ get :index++ expect(response).to have_http_status(:forbidden)+ end+ end++ describe 'capability' do+ before { request.headers.merge!(vendor_headers) }++ # Capability comes from the roles held on THIS vendor, so the store's own+ # roles — including its admin super-role — confer nothing here.+ it 'reads the roles held on the vendor, not on the store' do+ store.add_user(vendor_user, Spree::Role.default_admin_role(store))++ get :index++ ability = controller.send(:current_ability)+ expect(ability.permission_keys).to eq(%w[read_products write_products])+ expect(ability.can?(:manage, :all)).to be(false)+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/user_roles.rb b/spree/core/app/models/concerns/spree/user_roles.rbindex 89a1667a33..dc0bbcddf2 100644--- a/spree/core/app/models/concerns/spree/user_roles.rb+++ b/spree/core/app/models/concerns/spree/user_roles.rb@@ -63,6 +63,16 @@ module Spreeinvitations.first&.inviterend+ # Whether this user belongs to any marketplace vendor. The vendor login+ # refuses anyone this is false for, so a store's own staff cannot mint a+ # vendor token — the same rule the admin SSO callback applies to+ # unprovisioned subjects.+ #+ # @return [Boolean]+ def vendor_member?+ spree_roles.where(resource_type: 'Spree::Vendor').exists?+ end+endendenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 47e7429832..4d5d27a70e 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1664,6 +1664,8 @@ en:variant: Variantvariants: Variantsvendor: Vendor+ vendor_access_denied: You do not have access to this vendor.+ vendor_membership_required: This account does not belong to any vendor.verified: Verifiedverified_at: Verified atversion: Versiondiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex ab7b8edcc3..18ab7632db 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -573,6 +573,26 @@ module SpreeRails.application.config.spree.admin_authentication_strategies = valueend+ # Registry of authentication strategy classes for the Vendor API.+ #+ # Login policy is per surface, not per principal: marketplace sellers and the+ # store's own staff are both Spree.admin_user_class, so a store that requires+ # SSO for staff can still let sellers sign in with a password by leaving this+ # registry's :email strategy in place.+ #+ # @return [Spree::Authentication::StrategyRegistry]+ # @example Registering an SSO strategy for vendor users+ # Spree.vendor_authentication_strategies.add(:okta, MyApp::Auth::OktaStrategy)+ def self.vendor_authentication_strategies+ Rails.application.config.spree.vendor_authentication_strategies+ end++ # @param value [Spree::Authentication::StrategyRegistry] the registry to use for Vendor API authentication dispatch+ # @return [Spree::Authentication::StrategyRegistry] the assigned registry+ def self.vendor_authentication_strategies=(value)+ Rails.application.config.spree.vendor_authentication_strategies = value+ end+def self.analytics@analytics ||= AnalyticsConfig.newenddiff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex fa265445e6..983f7180f4 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -44,7 +44,8 @@ module Spree:number_generators,:subscribers,:store_authentication_strategies,- :admin_authentication_strategies)+ :admin_authentication_strategies,+ :vendor_authentication_strategies)SpreeCalculators = Struct.new(:shipping_methods, :tax_rates, :promotion_actions_create_adjustments, :promotion_actions_create_item_adjustments)PromoEnvironment = Struct.new(:rules, :actions)PricingEnvironment = Struct.new(:rules)@@ -511,6 +512,9 @@ module SpreeRails.application.config.spree.admin_authentication_strategies = Spree::Authentication::StrategyRegistry.new(email: Spree::Authentication::Strategies::EmailPasswordStrategy)+ Rails.application.config.spree.vendor_authentication_strategies = Spree::Authentication::StrategyRegistry.new(+ email: Spree::Authentication::Strategies::EmailPasswordStrategy+ )endinitializer 'spree.promo.register.promotions.actions' do |app|diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex f4af418879..9f7f1d9a73 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -337,6 +337,12 @@ module Spree[Spree.admin_user_class, Spree::Invitation, Spree::Role, Spree::RoleUser]})+ # A seller's own record: profile, branding, addresses, onboarding. Only+ # ever granted on the vendor surface — the store's staff manage vendors+ # through the marketplace endpoints, which the `vendors` resource covers.+ register_resource(:vendor_profile, group: :access, subjects: -> { [Spree::Vendor] },+ audiences: %i[vendor])+register_resource(:dashboard, group: :analytics, subjects: -> { [:dashboard] },write: false, audiences: %i[vendor])enddiff --git a/spree/core/spec/models/spree/vendor_spec.rb b/spree/core/spec/models/spree/vendor_spec.rbindex f00f92465a..6dd686f3cd 100644--- a/spree/core/spec/models/spree/vendor_spec.rb+++ b/spree/core/spec/models/spree/vendor_spec.rb@@ -103,6 +103,22 @@ describe Spree::Vendor doexpect(staffer.stores).not_to include(store)expect(Spree::Ability.new(staffer, store: store).permission_keys).to be_emptyend++ # The vendor login refuses anyone this is false for, so a store's own staff+ # cannot mint a vendor token.+ it 'marks its team as vendor members' do+ expect(staffer).not_to be_vendor_member++ vendor.add_user(staffer, create(:role, name: 'Packer', resource: vendor))++ expect(staffer.reload).to be_vendor_member+ end++ it 'does not mark store staff as vendor members' do+ store.add_user(staffer, create(:role, name: 'Support', resource: store))++ expect(staffer.reload).not_to be_vendor_member+ endenddescribe 'products' do