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
Fix tenancy and data-loss bugs in the media services
Damian Legawiec0eba02019b53
diff --git a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rbindex 97ed1509cb..98104ce111 100644--- a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb@@ -68,11 +68,13 @@ module Spree@parent.send(parent_association).build(media_attributes)end- # Everything the client sent minus the transport keys — the file, the- # URL to fetch one from, and the library row to copy are ways of- # getting at a file, not attributes of the row.+ # Everything the client sent minus the transport keys — a direct file,+ # the URL to fetch one from, and the library row to copy are ways of+ # getting at a file, not attributes of the row. Leaving `attachment`+ # in let a request carrying it alongside `source_media_id` overwrite+ # the shared blob with an upload, defeating the reuse.def media_attributes- permitted_params.except(:url, :signed_id, :source_media_id)+ permitted_params.except(:attachment, :url, :signed_id, :source_media_id)end# The media file, a URL to fetch one from, and the library row to copydiff --git a/spree/api/app/controllers/spree/api/v3/admin/media_library_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/media_library_controller.rbindex f36a47f58e..1319e6455c 100644--- a/spree/api/app/controllers/spree/api/v3/admin/media_library_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/media_library_controller.rb@@ -46,7 +46,13 @@ module Spreeresult = Spree::Media::Destroy.call(media: @resource)return head :no_content if result.success?- render_service_error(result.error)+ # A rolled-back delete carries no validation errors, so+ # render_service_error would produce an empty message.+ render_error(+ code: ERROR_CODES[:processing_error],+ message: Spree.t('api.errors.media_not_deleted'),+ status: :unprocessable_content+ )end# Where this file is in use — other products it has been placed on,@@ -102,8 +108,15 @@ module Spree# and `usage` says where each one appears. But a row the grouping# hides is still a real record a client may hold the id of, so# narrowing every lookup would 404 it on show or destroy.+ # The library has no parent, so this is the one media endpoint where+ # the admin base's `accessible_by` would apply — a role's+ # record-level rules must still filter it. `super` is skipped+ # deliberately: the parent controller's scope reads @product, which+ # a library request does not have.def scope- media = current_store.media.order(created_at: :desc)+ media = current_store.media+ .accessible_by(current_ability, ability_action_for_request)+ .order(created_at: :desc)listing? ? media.distinct_by_file : mediaenddiff --git a/spree/api/config/locales/en.yml b/spree/api/config/locales/en.ymlindex 4d48f19979..ce2865ef5d 100644--- a/spree/api/config/locales/en.yml+++ b/spree/api/config/locales/en.yml@@ -14,6 +14,7 @@ en:channel_inactive: The channel this API key is bound to is not active.channel_mismatch: The requested channel does not match the channel this API key is bound to.guest_checkout_not_allowed: You must be signed in to complete checkout.+ media_not_deleted: "The file could not be deleted. Nothing was changed."media_in_use: "This file is still in use (%{places}). Pass detach=true to remove it everywhere and delete it, or clear those places first."media_url_import_requires_product: Importing media from a URL needs a product to import it into. Upload the file instead, or post it to a product's media.store_mismatch: The requested store does not match the store this API key belongs to.diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rbindex 81eb4fbb8c..ccd14a54a1 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb@@ -387,6 +387,22 @@ RSpec.describe Spree::Api::V3::Admin::MediaController, type: :controller doexpect(target.media.last.alt).to eq('Same shot, different product')end+ # `attachment` is a way of getting at a file, like the other transport+ # keys — honouring it here would overwrite the shared blob with an upload.+ it 'ignores an attachment sent alongside the source' do+ post :create, params: {+ product_id: target.prefixed_id,+ source_media_id: image.prefixed_id,+ attachment: Rack::Test::UploadedFile.new(+ Spree::Core::Engine.root + 'spec/fixtures' + 'thinking-cat.jpg',+ 'image/jpeg'+ )+ }, as: :json++ expect(response).to have_http_status(:created)+ expect(target.media.last.attachment.blob).to eq(image.attachment.blob)+ end+it 'leaves the source where it was' dopost :create, params: {product_id: target.prefixed_id,diff --git a/spree/core/app/models/spree/media.rb b/spree/core/app/models/spree/media.rbindex 1ea5a2ebec..faa5eb1d7e 100644--- a/spree/core/app/models/spree/media.rb+++ b/spree/core/app/models/spree/media.rb@@ -14,6 +14,17 @@ module Spree# upgrade could not reach; new rows always carry a store.include Spree::SingleStoreResource+ # SingleStoreResource refuses any store change on a persisted record. Media+ # predates its store column, so a legacy row carries nil until the upgrade+ # task fills it in — and between db:migrate and that task, every edit of an+ # existing row would otherwise fail validation. Adopting a store is not+ # changing one.+ def ensure_store_association_is_not_changed+ return if store_id_was.nil?++ super+ end+publishes_lifecycle_eventsEXTERNAL_URL_CUSTOM_FIELD_KEY = 'external.url'@@ -70,10 +81,14 @@ module Spree## Rows with no attachment at all (an external video) have no blob to group# by and are always kept.+ # Grouped over the rows this scope already covers, not over every store's:+ # a global winner can belong to another tenant, which hid the file from the+ # library that owns it — not listed, not searchable, not deletable.scope :distinct_by_file, lambda {attachments = ActiveStorage::Attachment.arel_tablenewest_per_blob = ActiveStorage::Attachment.where(record_type: name, name: 'attachment')+ .where(record_id: unscope(:order).select(:id)).group(:blob_id).select(attachments[:record_id].maximum)diff --git a/spree/core/app/services/spree/media/destroy.rb b/spree/core/app/services/spree/media/destroy.rbindex f6535e66b2..8b4aa30a99 100644--- a/spree/core/app/services/spree/media/destroy.rb+++ b/spree/core/app/services/spree/media/destroy.rb@@ -18,7 +18,11 @@ module Spree# @param media [Spree::Media] the library row being deleted# @return [Spree::ServiceModule::Result]def call(media:)- blob_ids = [media.attachment_blob&.id, media.poster_blob&.id].compact+ # Only the file this row *is*, never its poster: a poster is a still+ # another row may legitimately use as its own picture, and deleting a+ # video must not take that image with it. The row's own poster goes+ # when the row does.+ blob_ids = [media.attachment_blob&.id].compact# Detaching is collected inside the transaction and enqueued after it# commits: purge_later hands the file to a worker that may run before@@ -71,11 +75,13 @@ module Spreeendend- # Same rule as Spree::Media::Usage: a record that carries no store at all- # (the store itself) is this store's to manage.+ # Ownership must be proven, never assumed. A Spree::Store has no+ # store_id of its own, so treating a blank one as "mine" made every+ # other store's logo look local — and deleting a file would strip it.def owned_by_store?(owner, store_id)- owner_store_id = owner.try(:store_id)- owner_store_id.blank? || owner_store_id == store_id+ return owner.id == store_id if owner.is_a?(Spree::Store)++ owner.try(:store_id) == store_idendendenddiff --git a/spree/core/app/services/spree/media/usage.rb b/spree/core/app/services/spree/media/usage.rbindex 6e1e5fb021..2ba52a60c1 100644--- a/spree/core/app/services/spree/media/usage.rb+++ b/spree/core/app/services/spree/media/usage.rb@@ -78,14 +78,13 @@ module Spreeendend- # A record is this store's if it says so. One that carries no store at all- # (the store record itself, a global) is reported — it is not another- # tenant's data.+ # Ownership must be proven, never assumed. A Spree::Store carries no+ # store_id of its own, so a blank one is not evidence the record is+ # local — treating it as such reported another tenant's logo as a use.def owned_by_store?(owner, store_id)- owner_store_id = owner.try(:store_id)- return true if owner_store_id.blank?+ return owner.id == store_id if owner.is_a?(Spree::Store)- owner_store_id == store_id+ owner.try(:store_id) == store_idenddef build_reference(owner, field)diff --git a/spree/core/spec/models/spree/media_spec.rb b/spree/core/spec/models/spree/media_spec.rbindex be443cf1e6..db78d84c6e 100644--- a/spree/core/spec/models/spree/media_spec.rb+++ b/spree/core/spec/models/spree/media_spec.rb@@ -74,6 +74,29 @@ describe Spree::Media, type: :model doendend+ describe 'a row that predates the store column' do+ # Between db:migrate and spree:upgrade:backfill_media_store_ids every+ # existing row carries nil. Editing one must not fail validation.+ it 'adopts a store on its next save' do+ media = create(:image, viewable: create(:product))+ described_class.unscoped.where(id: media.id).update_all(store_id: nil)++ legacy = described_class.find(media.id)+ legacy.alt = 'Edited'++ expect(legacy.save).to be(true)+ expect(legacy.reload.store_id).to be_present+ end++ it 'still refuses moving a row between stores' do+ media = create(:image, viewable: create(:product))+ media.store = create(:store)++ expect(media.save).to be(false)+ expect(media.errors[:store]).to be_present+ end+ end+describe 'library scopes' dolet!(:placed) { create(:image, viewable: create(:product)) }let!(:unplaced) { create(:image, viewable: nil) }@@ -106,6 +129,15 @@ describe Spree::Media, type: :model doexpect(result).to contain_exactly(source, other)end+ # Grouping globally let another tenant's row win, which hid the file from+ # the library that owns it entirely.+ it 'keeps a file visible in its own store when another store shares it' do+ other_store = create(:store)+ source.duplicate_for(create(:product, store: other_store)).save!++ expect(source.store.media.distinct_by_file).to include(source)+ end+# An external video has no attachment to group by, so it can't be folded# into another row's file.it 'keeps external videos' dodiff --git a/spree/core/spec/services/spree/media/destroy_spec.rb b/spree/core/spec/services/spree/media/destroy_spec.rbindex aa07df8df5..f5e442f4bb 100644--- a/spree/core/spec/services/spree/media/destroy_spec.rb+++ b/spree/core/spec/services/spree/media/destroy_spec.rb@@ -67,6 +67,37 @@ describe Spree::Media::Destroy doexpect(category.reload.image).to be_attachedend+ # A Spree::Store has no store_id of its own, so a blank one must not read as+ # "mine" — deleting one store's file was stripping another store's logo.+ it 'leaves another store logo on the same file alone' do+ foreign_store = create(:store)+ foreign_store.logo.attach(media.attachment.blob)+ foreign_store.save!++ perform_enqueued_jobs { described_class.call(media: media) }++ expect(foreign_store.reload.logo).to be_attached+ end++ # A poster is a still another row may use as its own picture, so deleting a+ # video must not take that independent image with it.+ it 'leaves an image reusing the video poster alone' do+ video = create(:video_media, viewable: product)+ video.poster.attach(+ io: File.new(Spree::Core::Engine.root + 'spec/fixtures' + 'thinking-cat.jpg'),+ filename: 'still.jpg'+ )+ video.save!++ reuse = Spree::Media.new(store: product.store, viewable: product, media_type: 'image')+ reuse.attachment.attach(video.poster.blob)+ reuse.save!++ described_class.call(media: video)++ expect(Spree::Media.exists?(reuse.id)).to be(true)+ end+it 'leaves unrelated files alone' dounrelated = create(:image, viewable: create(:product))diff --git a/spree/core/spec/services/spree/media/usage_spec.rb b/spree/core/spec/services/spree/media/usage_spec.rbindex 4d98003430..ee108c57c0 100644--- a/spree/core/spec/services/spree/media/usage_spec.rb+++ b/spree/core/spec/services/spree/media/usage_spec.rb@@ -35,9 +35,7 @@ describe Spree::Media::Usage do# A file picked for a store logo shares the blob without going through# Spree::Media at all, so usage has to be a question about the blob.it 'reports a plain attachment sharing the blob' do- # A dedicated store, not the suite-wide default — attaching a logo to the- # shared record would leak into every later spec.- store = create(:store)+ store = media.storestore.logo.attach(media.attachment.blob)store.save!@@ -47,6 +45,16 @@ describe Spree::Media::Usage doexpect(reference.field).to eq('logo')end+ # A Spree::Store has no store_id of its own, so a blank one must not read as+ # "mine" — that reported another tenant's logo, and the delete stripped it.+ it 'ignores another store using the same file for its logo' do+ foreign_store = create(:store, name: 'Another tenant')+ foreign_store.logo.attach(media.attachment.blob)+ foreign_store.save!++ expect(usage.select { |candidate| candidate.kind == 'attachment' }).to be_empty+ end+# A category holds a file twice — its image slot and the slot's library# placement. The merchant should see the category once, as the placement,# which is what the dashboard can link to.