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
Decide an uploaded document by its bytes, and leave a place for a scanner
Damian Legawiec42ba3724a25e
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/requirement_submissions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/requirement_submissions_controller_spec.rbindex eefd44270b..0009bdb2ca 100644--- a/spree/api/spec/controllers/spree/api/v3/seller/requirement_submissions_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/seller/requirement_submissions_controller_spec.rb@@ -67,11 +67,16 @@ RSpec.describe Spree::Api::V3::Seller::RequirementSubmissionsController, type: :describe 'GET #download' dolet(:requirement) { create(:document_requirement, store: store) }+ # Real PDF magic bytes, not just a .pdf name: the model decides a file's+ # type by reading it, so a plain string declared as a PDF is refused.+ PDF_BYTES = "%PDF-1.4\npassport"+def submission_for(target_seller)create(:seller_requirement_submission, seller: target_seller, requirement: requirement).tap do |submission|submission.file.attach(- io: StringIO.new('passport'), filename: 'id.pdf', content_type: 'application/pdf'+ io: StringIO.new(PDF_BYTES), filename: 'id.pdf', content_type: 'application/pdf')+ submission.save!endend@@ -81,7 +86,7 @@ RSpec.describe Spree::Api::V3::Seller::RequirementSubmissionsController, type: :get :download, params: { id: submission.prefixed_id }expect(response).to have_http_status(:ok)- expect(response.body).to eq('passport')+ expect(response.body).to eq(PDF_BYTES)end# Identity documents: one seller reading another's is the thing thisdiff --git a/spree/core/app/models/spree/seller_requirement_submission.rb b/spree/core/app/models/spree/seller_requirement_submission.rbindex c8c180dd1f..4374bef134 100644--- a/spree/core/app/models/spree/seller_requirement_submission.rb+++ b/spree/core/app/models/spree/seller_requirement_submission.rb@@ -43,6 +43,27 @@ module Spree#validate :requirement_belongs_to_sellers_store+ # Sellers are the marketplace's lower-trust writers, and these files are+ # opened by an operator on their own machine — so the bytes decide what a+ # file is, not the header the uploader sent.+ #+ # `spoofing_protection` is what makes that true: without it the gem takes+ # the declared type and filename at face value, and a script named+ # `certificate.pdf` passes. With it, Marcel reads the magic bytes and the+ # two must agree.+ #+ # The list belongs to the kind that asks for files, which already+ # publishes it and whose value the seller API serializes so the panel's+ # picker can hint it. Resolved in a lambda rather than referenced at+ # class-definition time, which would pin the autoload order.+ validates :file,+ content_type: {+ in: ->(_record) { Spree::SellerRequirements::Document::ACCEPTED_CONTENT_TYPES },+ spoofing_protection: true+ },+ size: { less_than_or_equal_to: ->(_record) { Spree::Config.max_seller_document_upload_size } },+ if: -> { file.attached? }+## Scopes#diff --git a/spree/core/app/workflows/spree/seller_requirement_submissions/create.rb b/spree/core/app/workflows/spree/seller_requirement_submissions/create.rbindex e10984fafb..17c0270a19 100644--- a/spree/core/app/workflows/spree/seller_requirement_submissions/create.rb+++ b/spree/core/app/workflows/spree/seller_requirement_submissions/create.rb@@ -7,6 +7,34 @@ module Spree# Whether that settles the requirement or only queues it depends on the# kind: an attestation is the seller's word and is taken at face value, a# document or a manual check waits for someone to look at it.+ #+ # == Scanning an uploaded document+ #+ # Hook `after_create` and reject what the scanner does not like:+ #+ # Spree.hooks.register('seller_requirement_submissions.create.after_create') do |workflow|+ # submission = workflow.submission+ # next unless submission.file.attached?+ #+ # verdict = MyScanner.scan(submission.file.download)+ # if verdict.infected?+ # submission.update!(status: 'rejected', review_note: 'Failed a virus scan.')+ # end+ # end+ #+ # `after_create` rather than `validate`, which is where a rejection would+ # normally go: at validate time the blob is built but not yet uploaded, so+ # there is nothing in storage for a scanner to read. By `after_create` the+ # bytes are there, and the submission is `pending` — a state no operator+ # acts on — so moving it to `rejected` settles it before anyone opens it.+ # A scanner that answers slowly should do the same from a background job+ # keyed on the submission.+ #+ # Core ships no scanner: which one a marketplace runs is a deployment+ # decision, and the hook is the whole contract. What core does guarantee+ # is that a file's *type* is decided by its bytes rather than the header+ # the uploader sent, and that its size is bounded — see+ # Spree::SellerRequirementSubmission.class Create < Spree::Workflowhooks :validate, :after_create@@ -61,22 +89,16 @@ module Spree# it is refused here rather than reaching a reviewer empty — and a file# in a format the operator said they cannot open is refused with it,# since the setting is shown to sellers as a promise.+ # Only that a file is here at all. What the file *is* — its real type+ # and its size — is the model's business, where the validation reads+ # the bytes rather than the header the uploader sent; repeating a+ # weaker version of that check here is how the two drift apart.def ensure_file_acceptablereturn unless requirement.class.requires_file?+ return if submission.file.attached?- unless submission.file.attached?- errors.add(:file, :blank, message: Spree.t('seller_requirements.file_required',- default: 'A file is required for this requirement'))- failure(submission, errors)- end-- accepted = requirement.accepted_content_types- return if accepted.blank? || accepted.include?(submission.file.content_type)-- errors.add(:file, :invalid,- message: Spree.t('seller_requirements.file_type_not_accepted',- types: accepted.join(', '),- default: "This requirement accepts #{accepted.join(', ')}"))+ errors.add(:file, :blank, message: Spree.t('seller_requirements.file_required',+ default: 'A file is required for this requirement'))failure(submission, errors)enddiff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rbindex d66a7cae61..0e0e8c9eee 100644--- a/spree/core/lib/spree/core/configuration.rb+++ b/spree/core/lib/spree/core/configuration.rb@@ -114,6 +114,11 @@ module Spree# Maximum size of an uploaded product video, in bytes.preference :max_video_upload_size, :integer, default: 524_288_000 # 500 MB++ # Maximum size of a document a seller uploads for an onboarding+ # requirement, in bytes. Small on purpose: these are certificates and+ # registrations, and an unbounded upload is a way to fill a disk.+ preference :max_seller_document_upload_size, :integer, default: 20_971_520 # 20 MBpreference :non_expiring_credit_types, :array, default: [], deprecated: 'Nothing reads this in Spree 6 — store credits no longer carry a category, and expiry lives on Spree::GiftCard'preference :products_per_page, :integer, default: 12, deprecated: 'Nothing reads this in Spree 6 — pass per_page to the API instead'preference :restock_inventory, :boolean, default: true, deprecated: 'Restocking is decided per line item by Spree::ReturnLineItem#resellable'diff --git a/spree/core/spec/workflows/spree/seller_requirement_submissions/lifecycle_spec.rb b/spree/core/spec/workflows/spree/seller_requirement_submissions/lifecycle_spec.rbindex 76b0eec983..72a69fe9ab 100644--- a/spree/core/spec/workflows/spree/seller_requirement_submissions/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/seller_requirement_submissions/lifecycle_spec.rb@@ -56,7 +56,100 @@ RSpec.describe 'seller requirement submission workflows' do)expect(result).to be_failure- expect(result.error.value.full_messages.join).to match(/accepts/i)+ expect(result.error.value.full_messages.join).to match(/invalid content type/i)+ end++ # The header is the uploader's word for what a file is. A seller is the+ # marketplace's lower-trust writer and an operator opens these documents+ # on their own machine, so the bytes have to decide.+ it 'refuses a script wearing a PDF content type and filename' do+ requirement = create(:document_requirement, store: store)++ result = described_class.call(+ seller: seller,+ requirement: requirement,+ file: {+ io: StringIO.new("#!/bin/sh\nrm -rf /\n"),+ filename: 'certificate.pdf',+ content_type: 'application/pdf'+ }+ )++ expect(result).to be_failure+ expect(result.error.value.full_messages.join).to match(/content type/i)+ end++ it 'refuses a document larger than the configured limit' do+ requirement = create(:document_requirement, store: store)+ allow(Spree::Config).to receive(:max_seller_document_upload_size).and_return(64)++ result = described_class.call(+ seller: seller,+ requirement: requirement,+ file: {+ io: StringIO.new("%PDF-1.4\n#{'a' * 500}"),+ filename: 'big.pdf',+ content_type: 'application/pdf'+ }+ )++ expect(result).to be_failure+ expect(result.error.value.full_messages.join).to match(/size|large/i)+ end++ context 'with a scanner registered' do+ # Registrations outlive an example, so this one is torn down rather than+ # left firing inside every test that follows.+ after { Spree.hooks.clear! }++ # The documented injection point for a virus scanner. Proven here so the+ # example in the workflow's own docs is one that runs.+ #+ # `after_create` rather than `validate`: at validate time the blob is+ # built but not yet uploaded, so a scanner has nothing in storage to+ # read. By here the bytes are there — and the submission is `pending`,+ # a state no operator acts on, so quarantining it is a status change+ # rather than a race.+ it 'lets a handler quarantine a file it has read' do+ requirement = create(:document_requirement, store: store)+ scanned = nil++ Spree.hooks.register('seller_requirement_submissions.create.after_create') do |workflow|+ scanned = workflow.submission.file.download+ workflow.submission.update!(status: 'rejected', review_note: 'Failed a virus scan.')+ end++ result = described_class.call(+ seller: seller,+ requirement: requirement,+ file: {+ io: StringIO.new("%PDF-1.4\ninfected"),+ filename: 'certificate.pdf',+ content_type: 'application/pdf'+ }+ )++ expect(result).to be_success+ expect(scanned).to include('infected')+ expect(result.value.reload).to be_rejected+ end+ end++ it 'accepts a real PDF' do+ requirement = create(:document_requirement, store: store)++ result = described_class.call(+ seller: seller,+ requirement: requirement,+ file: {+ io: StringIO.new("%PDF-1.4\ntrailer<</Root 1 0 R>>"),+ filename: 'certificate.pdf',+ content_type: 'application/pdf'+ }+ )++ expect(result).to be_success+ expect(result.value.file).to be_attachedendit 'takes a scan of one' do