Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Replace `Spree::PermittedAttributes` with a better solution (#14472)

Damian Legawiec722468dd17a6
diff --git a/CLAUDE.md b/CLAUDE.md
index 3d84098ee2..6aac3145e7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -268,7 +268,15 @@ The Store API (customer-facing) and Admin API (back-office) are two halves of th
#### Flat request/response structure
-API v3 uses flat params — no nested Rails-style wrapping. **For new controllers, prefer enumerating attributes directly with `params.permit(...)`** rather than reaching into `Spree::PermittedAttributes`. Existing controllers that use the global allowlist remain valid until migrated as part of the 6.0 transition.
+API v3 uses flat params — no nested Rails-style wrapping. Declare a controller's writable attributes by overriding **`resource_permitted_attributes`** (a plain list). The base `permitted_attributes` appends extension-contributed attributes to it, and `permitted_params` permits and normalizes the result. `Spree::PermittedAttributes` and its model-name inference are **removed in 6.0** — a controller that declares neither `resource_permitted_attributes` nor `permitted_params` raises `NotImplementedError` on its first write.
+
+Extensions add writable attributes to a core resource from an initializer, appending to the model's `additional_permitted_attributes` (a `class_attribute` on `Spree::Base`, default `[]`): `Spree::Product.additional_permitted_attributes += [:brand_id]`. Always `+=`, never `=` — assigning replaces what another extension added. Core STI subclasses set theirs with `self.additional_permitted_attributes = [...]` in the class body. Three rules that matter:
+
+- **Override `resource_permitted_attributes`, never `permitted_attributes`** — the latter is where the extension union happens, so overriding it silently drops extension attributes.
+- **A controller that overrides `permitted_params` outright opts out of the union.** If it needs both, splat `model_additional_permitted_attributes` into its own `params.permit`.
+- **`normalize_params` is not free.** It recurses into nested hashes decoding anything matching the prefixed-ID shape, so a controller carrying opaque provider values (gateway `preferences`, merchant `metadata`) must NOT normalize — a Stripe `we_1MqJ8b...` id would be decoded to an integer. `Admin::PaymentMethodsController` is the worked example. Conversely, a controller that *does* normalize receives already-decoded primary keys, so read raw `params` when you need a prefix-checked `find_by_prefix_id!`.
+
+Prefer Custom Fields for merchant-managed data; the hook is for extensions adding real columns.
```ruby
# ✅ Flat params
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index bb9e8553c9..08b3e99739 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -394,10 +394,123 @@ The `compare_at_price` **reader** (which resolves against `cost_currency`) is un
Also note:
- **Ransack:** `default_price` is no longer a searchable association on `Variant`; query `prices` instead.
-- **`Spree::PermittedAttributes`:** the dead `:price` and `:compare_at_price` entries are dropped from `product_attributes` and `variant_attributes`. Prices were already written as nested `prices: [{ amount:, currency: }]` under variants — the top-level keys had no writer behind them.
+- **Prices in permitted params:** the dead `:price` and `:compare_at_price` entries are gone. Prices were already written as nested `prices: [{ amount:, currency: }]` under variants — the top-level keys had no writer behind them. (`Spree::PermittedAttributes` itself is removed in 6.0 — see below.)
- Localized number parsing still happens: `Spree::Price#amount=` runs `Spree::LocalizedNumber.parse`, so `set_price(currency, '1,599.99')` works as `price=` did.
- The variant validation that inferred a missing price from the product's default variant is gone. Set prices explicitly (the product and variant factories already do).
+### `Spree::PermittedAttributes` is removed
+
+The global permitted-attributes registry is gone, with no deprecation bridge. It
+existed so the Rails admin and storefront could share one allowlist; both are
+removed in 6.0, and API v3 declares its attributes in the controller.
+
+Removed alongside it: `Spree::Core::ControllerHelpers::StrongParameters` (the
+`permitted_*_attributes` helper methods it mixed into controllers) and the
+fallback that inferred an attribute list from the model name.
+
+Attributes you pushed from an initializer are now declared on the model, and
+standard resource endpoints append them to their own allowlist — so one
+declaration still covers the model's create and update endpoints.
+
+#### How to migrate
+
+**1. Find every call site.** The constant and the helper methods are both gone,
+so a missed reference raises `NameError` or `NoMethodError` the first time that
+code runs — loudly, but not necessarily at boot:
+
+```bash
+grep -rn "PermittedAttributes" app config lib
+grep -rnE "permitted_[[:alnum:]_]+_attributes" app config lib
+```
+
+The second pattern is deliberately broad: the helper module generated one
+`permitted_*_attributes` method per registry key, so there were dozens of them.
+
+**2. Decide what each attribute actually is.** Most fall into one of three
+buckets, and only the last needs this hook:
+
+| What you were adding | Where it goes in 6.0 |
+| --- | --- |
+| A merchant-managed field (text, number, dropdown) | [Custom Fields](/developer/core-concepts/custom-fields) — no code, and filterable/sortable |
+| Config for an STI type you register (promotion rule, delivery method rule, …) | `additional_permitted_attributes` on that subclass, as before — unchanged |
+| A real database column your extension added to a core model | `additional_permitted_attributes` on the model |
+
+**3. Point each declaration at the model.** It stays in your initializer — only
+the receiver changes, from the global registry to the model itself:
+
+```ruby config/initializers/spree.rb
+# Before
+Spree::PermittedAttributes.product_attributes << :brand_id
+
+# After
+Spree::Product.additional_permitted_attributes += [:brand_id]
+```
+
+Use `+=`, not `=` — the list is per model, and assigning replaces whatever
+another extension already added. `<<` raises a `FrozenError`: the default is a
+frozen shared array, so mutating it in place would leak your attribute onto every
+other model.
+
+Declare only attributes of your own. Redeclaring a key the controller already
+permits (`metadata`, `prices`) does not widen it — strong parameters keeps the
+last filter for that key, so the controller's own would be replaced by yours.
+
+Entries are `params.permit` fragments, so collections and nested structures keep
+the shapes you already know: `[:brand_id, { region_ids: [] }]`.
+
+**4. Fix your own controllers.** If you subclassed a Spree v3 resource
+controller and relied on the attribute list being inferred from the model name,
+declare it now:
+
+```ruby
+class BrandsController < Spree::Api::V3::Admin::ResourceController
+ protected
+
+ def model_class
+ Spree::Brand
+ end
+
+ # Before: no such method — the base class inferred `brand_attributes`
+ # from the model name. Now you say what you accept.
+ def resource_permitted_attributes
+ [:name, :slug, :description]
+ end
+end
+```
+
+Declaring neither `resource_permitted_attributes` nor `permitted_params` raises
+`NotImplementedError` on the first write, so this surfaces in your test suite
+rather than silently permitting a stale list.
+
+**5. Verify a write actually persists.** A declaration that never reaches a
+controller fails silently — strong parameters drop the unpermitted key, the
+request still returns 200, and the column keeps its old value. Assert on the
+saved record, not the response status:
+
+```ruby
+patch "/api/v3/admin/products/#{product.prefixed_id}",
+ params: { brand_id: brand.id }, headers: headers
+
+expect(product.reload.brand_id).to eq(brand.id)
+```
+
+If that assertion fails, the endpoint is not consulting your declaration. Check
+whether the controller overrides `permitted_attributes` — that method is where
+the extension attributes are appended, so overriding it replaces them. Override
+`resource_permitted_attributes` instead.
+
+<Warning>
+ Two endpoints deliberately ignore the hook because their parameters are
+ authorization data rather than resource data: API keys (`scopes`, `key_type`)
+ and invitations (`role_id`). Adding attributes there needs a controller
+ decorator, not a model declaration.
+</Warning>
+
+STI types registered through a Spree registry (promotion rules and actions,
+delivery method rules, commission rules) already used
+`additional_permitted_attributes` and need no changes — the hook simply moved up
+to `Spree::Base`.
+
### `StateChange` and `LogEntry` are gone
`Spree::StateChange` and `Spree::LogEntry` are removed — the models, the `state_changes` associations on `Order`, `Payment` and `Fulfillment`, the `log_entries` associations on `Payment` and `Refund`, and everything that wrote to them. Both were write-only: nothing in Spree read the rows back, and the admin screens that displayed them are gone.
diff --git a/docs/docs.json b/docs/docs.json
index f352b0567c..a244c87353 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -1095,7 +1095,7 @@
"v6/developer/customization/permissions",
"developer/customization/workflows",
"developer/customization/validations",
- "developer/customization/api",
+ "v6/developer/customization/api",
"developer/customization/model-preferences",
"developer/customization/metadata",
"v6/developer/customization/dependencies",
diff --git a/docs/plans/6.0-duties-and-custom-fees.md b/docs/plans/6.0-duties-and-custom-fees.md
index db09ee5d2e..49af72eae6 100644
--- a/docs/plans/6.0-duties-and-custom-fees.md
+++ b/docs/plans/6.0-duties-and-custom-fees.md
@@ -38,7 +38,7 @@ New columns on `spree_variants`:
`hs_code` is normalized to digits only and `country_of_origin` upcased, so a merchant pasting `6404.11` or `vn` stores the canonical value; the dashboard mirrors both normalizations client-side (`normalize-customs.ts`, shared by the variant edit sheet and the bulk editor) so a dotted tariff code pasted from a broker's spreadsheet is accepted rather than bounced by the format validation.
-**`country_of_origin` stores an ISO 3166-1 alpha-2 code, never a country record id**, and every picker is bound to ISO accordingly (the edit sheet's `CountryCombobox`, the bulk editor's select cell). Customs classification has to outlive the `spree_countries` table — an id would dangle, a code will not. That table was **dropped on 2026-08-15** (`Spree::Country` is now reference data from the `countries` gem, `.by_iso` rather than `.find_by`), and this work needed no data change at all as a result. It is also what carriers expect on the declaration, so no lookup sits between the stored value and the EasyPost payload. Readers on `Spree::Variant` fall back to the product-type/product level only if a later plan adds it there — in 6.0 they are variant-local. Admin API v3 variant endpoints permit and serialize the three fields (admin serializer only — the Store API never exposes customs data); note that a variant attribute must be permitted in **three** places — the shared `PermittedAttributes`, the nested `Admin::Products::VariantsController` (which enumerates its own list), and the inline `variants: [...]` list on `Admin::ProductsController`. The last is the one the dashboard's product Save actually uses, and it was missed on the first pass: the nested-controller spec passed while every customs edit made through the product form was silently discarded. The inline-variants spec on the products controller now covers it. CSV import columns follow. No validation requires them: customs data is optional until an international label or a duties provider needs it, at which point the consumer raises its own actionable error.
+**`country_of_origin` stores an ISO 3166-1 alpha-2 code, never a country record id**, and every picker is bound to ISO accordingly (the edit sheet's `CountryCombobox`, the bulk editor's select cell). Customs classification has to outlive the `spree_countries` table — an id would dangle, a code will not. That table was **dropped on 2026-08-15** (`Spree::Country` is now reference data from the `countries` gem, `.by_iso` rather than `.find_by`), and this work needed no data change at all as a result. It is also what carriers expect on the declaration, so no lookup sits between the stored value and the EasyPost payload. Readers on `Spree::Variant` fall back to the product-type/product level only if a later plan adds it there — in 6.0 they are variant-local. Admin API v3 variant endpoints permit and serialize the three fields (admin serializer only — the Store API never exposes customs data); note that a variant attribute must be permitted in **two** places — the nested `Admin::Products::VariantsController` (which enumerates its own list) and the inline `variants: [...]` list on `Admin::ProductsController`. (It was three until `Spree::PermittedAttributes` was removed; see `6.0-permitted-attributes-removal.md`.) The last is the one the dashboard's product Save actually uses, and it was missed on the first pass: the nested-controller spec passed while every customs edit made through the product form was silently discarded. The inline-variants spec on the products controller now covers it. CSV import columns follow. No validation requires them: customs data is optional until an international label or a duties provider needs it, at which point the consumer raises its own actionable error.
### 2. `duty` fee kind
diff --git a/docs/plans/6.0-permitted-attributes-removal.md b/docs/plans/6.0-permitted-attributes-removal.md
new file mode 100644
index 0000000000..7d5144c830
--- /dev/null
+++ b/docs/plans/6.0-permitted-attributes-removal.md
@@ -0,0 +1,173 @@
+# Drop Spree::PermittedAttributes, add a model-level extension hook
+
+**Status:** Complete
+**Target:** Spree 6.0
+**Depends on:** `6.0-admin-api.md` (v3 flat-params conventions), `6.0-store-scoped-custom-field-definitions.md`
+**Author:** Damian
+**Last updated:** 2026-08-20
+
+## Summary
+
+`Spree::PermittedAttributes` is a global mutable allowlist of 66 attribute lists, created so host apps and extensions could add writable attributes from an initializer instead of decorating controllers. It was built for the Rails admin and storefront, both of which are gone. API v3 permits attributes inline in controllers, and merchant-added data is now served by Custom Fields, which are sortable and filterable. The registry is close to dead already: only five of its 66 keys are read by name anywhere in the codebase, and the composed `ControllerHelpers::StrongParameters` helpers built on top of it are called from nowhere at all.
+
+We delete the registry and the helper module, and replace the one capability they still uniquely provided — declaring an extra writable attribute on a plain core resource — with an `additional_permitted_attributes` `class_attribute` on `Spree::Base` that v3 controllers append to their inline allowlist. Extensions still declare from an initializer — the ergonomics that made the registry popular — but against the model rather than a global hash, so the list is scoped, discoverable, and cannot be reached by code that has no business touching another resource. It also generalizes a convention already copy-pasted into four rule base classes.
+
+## Key Decisions (do not deviate without discussion)
+
+- **`Spree::PermittedAttributes` is deleted outright at 6.0, with no deprecation bridge.** This is a recorded exception to the deprecation-bridges convention. The constant is not being renamed — it is being removed along with the mechanism that consumed it, so there is nothing to warn-and-delegate to. Handled as a documented clean break in the upgrade guide, like the CSV `shipping_category` removal in `6.0-fulfillment-and-delivery.md`.
+- **`Spree::Core::ControllerHelpers::StrongParameters` is deleted** and its `include` removed from `Spree::BaseController` and `Api::V3::BaseController`. Nothing in the codebase calls any of its methods.
+- **`additional_permitted_attributes` is a `class_attribute` on `Spree::Base`**, defaulting to `[]`. Extensions append from an initializer — `Spree::Product.additional_permitted_attributes += [:brand_id]` — which keeps the ergonomics of the registry it replaces (one line, no decorator) while scoping the list to one model instead of a global hash. Always `+=`, never `=`: assigning replaces what another extension added.
+- **The union happens in `ResourceController#permitted_attributes`, which appends `model_additional_permitted_attributes` to the subclass's `resource_permitted_attributes`.** Subclasses override `resource_permitted_attributes` (the plain list); overriding `permitted_attributes` bypasses the union and is wrong.
+- **`normalize_params` is NOT the union point, and normalization is not universal.** An early cut applied the union inside `normalize_params` on the theory that every write funnels through it. It does not: 63 write controllers deliberately never normalize. Worse, normalization is not a neutral pass — `resolve_prefixed_ids` recurses into nested hashes decoding anything matching `/\A[a-z]+_[a-zA-Z0-9]+\z/` under a `*_id` key, so enrolling a controller into it corrupts opaque provider values. A Stripe `webhook_endpoint_id` of `we_1MqJ8bLkdIwHu7ixIhqHQfbo` decodes to `2345514981514645561106`. Controllers carrying gateway `preferences` or merchant `metadata` must never normalize.
+- **Controllers that override `permitted_params` splat `model_additional_permitted_attributes` into their own `params.permit`.** This preserves each controller's existing normalization behavior — a one-line addition, not a restructuring. Two credential endpoints (`api_keys`, `invitations`) are deliberately excluded: their parameters are the authorization surface, not extensible resource data.
+- **The registry's name-inference fallback is removed.** `resource_permitted_attributes` raises `NotImplementedError` when undeclared, matching `model_class` and `serializer_class`. Silent inference from a model name is what let attribute lists drift out of sight.
+- **Core STI subclasses assign in the class body** (`self.additional_permitted_attributes = [product_ids: []]`), which `class_attribute` scopes to that subclass while leaving the parent's value alone. The eight existing method-style overrides were converted to assignments so one mechanism covers both core declarations and extension appends.
+- **The hook is for extension-added columns only.** Core attributes stay in the controller's inline `params.permit`. A core model must never declare its own base attributes through this hook — that would recreate the registry one class at a time.
+- **Custom Fields remain the recommended path for merchant-added data.** The hook is documented as the fallback for extensions that add real database columns, not as the default extension story.
+
+## Design Details
+
+### Current state
+
+The registry has three consumer paths, all of which are being removed:
+
+1. **Five explicit Store API reads** — `wishlists`, `wishlist_items`, `carts/payment_sessions`, `carts/items`, `customer/payment_setup_sessions`. Plus one in `Spree::Carts::AddItem`, which flattens `line_item_attributes` to filter incoming options.
+2. **The inference fallback** in `ResourceController#permitted_attributes`, which derives a key from the model name via `public_send`. Nearly every admin controller that reaches it is read-only; the four with real write actions (`customers/addresses`, `orders`, `admin_users`, `stock_transfers`) all define their own inline permits and never touch it.
+3. **`ControllerHelpers::StrongParameters`**, which delegates all 66 keys and defines six composed helpers (`permitted_checkout_attributes`, `permitted_product_attributes`, …). Zero callers. Its composed helpers describe nested-attributes payload shapes (`bill_address_attributes`, `payments_attributes`) that v3 explicitly rejected with its flat-params rule.
+
+The registry also has a demonstrated failure mode: because the same attribute must be listed in several disconnected places, a variant attribute had to be permitted in three of them or one write path silently discarded it — see `6.0-duties-and-custom-fees.md`. A single global list that is not actually the single source of truth is worse than no list.
+
+### The hook
+
+On `Spree::Base`:
+
+```ruby
+# Extra writable attributes contributed by extensions, appended to the v3
+# controller allowlist for this resource.
+#
+# Spree::Product.additional_permitted_attributes += [:brand_id]
+#
+# Entries are `params.permit` fragments: bare symbols, or hashes for
+# collections and nested structures (`{ region_ids: [] }`).
+class_attribute :additional_permitted_attributes, instance_writer: false, default: [].freeze
+```
+
+Extensions declare from an initializer, the same place the old registry was fed:
+
+```ruby
+# config/initializers/spree.rb
+Spree::Product.additional_permitted_attributes += [:brand_id]
+```
+
+No decorator, no registration step. `class_attribute` gives per-class storage
+with inheritance, so appending to `Spree::Product` leaves `Spree::Variant` and
+`Spree::Base` untouched, and a core STI subclass can assign its own value
+(`self.additional_permitted_attributes = [product_ids: []]`) without disturbing
+its parent.
+
+### Controller wiring
+
+`ResourceController` gains a two-level split: the subclass declares its own list,
+the base appends what extensions contributed.
+
+```ruby
+def permitted_params
+ normalize_params(params.permit(*permitted_attributes))
+end
+
+# Resource list + extension contributions. Subclasses override
+# `resource_permitted_attributes`, never this.
+def permitted_attributes
+ resource_permitted_attributes + model_additional_permitted_attributes
+end
+
+def resource_permitted_attributes
+ raise NotImplementedError, 'Subclass must implement resource_permitted_attributes or permitted_params'
+end
+
+def model_additional_permitted_attributes
+ return [] unless respond_to?(:model_class, true)
+
+ model = model_class
+ return [] unless model.respond_to?(:additional_permitted_attributes)
+
+ Array(model.additional_permitted_attributes)
+rescue NotImplementedError
+ []
+end
+```
+
+A controller that overrides `permitted_params` outright bypasses that path, so it
+splats the extras into its own call:
+
+```ruby
+def permitted_params
+ params.permit(*model_additional_permitted_attributes, :name, :active)
+end
+```
+
+Three consequences to handle deliberately:
+
+- **Overriding `permitted_attributes` silently drops extension attributes.** That
+ method is the union; `resource_permitted_attributes` is the override point.
+ Nothing enforces this, which is why it is called out in CLAUDE.md.
+- **Do not enroll a controller into `normalize_params` to get the union.** The
+ splat gets the same result without changing parameter semantics. Normalization
+ decodes prefixed IDs recursively through nested hashes, which corrupts gateway
+ `preferences` and merchant `metadata` (see Key Decisions), and hands the action
+ already-decoded primary keys — so a `find_by_prefix_id!` in that action must
+ read raw `params` or become a plain `find`.
+- **Both guards in `model_additional_permitted_attributes` are load-bearing:** a
+ controller need not define `model_class` (the `respond_to?` check plus the
+ `NotImplementedError` rescue), and `Spree.base_class` is host-overridable, so
+ the hook is not guaranteed to be inherited from `Spree::Base`.
+
+### The four existing rule classes
+
+`Spree::PromotionRule`, `Spree::PromotionAction`, `Spree::DeliveryMethodRule` and `Spree::CommissionRule` each define their own identical `additional_permitted_attributes` default. Once `Spree::Base` carries it, those four definitions are redundant and get deleted; the inherited default takes over. Their STI subclasses keep their overrides untouched.
+
+Their consuming controllers are a *different* mechanism and stay as they are: `PromotionsController#subclassed_collection_attributes` and the delivery-method-rules equivalent walk a subclass **registry** and union across every registered type, because the controller writes an STI base and cannot know which subclass a request targets. The new `ResourceController` union asks a single `model_class`. Both can coexist — the registry walk is for polymorphic writes, the model hook is for the concrete resource. The three `respond_to?` guards in those controllers become redundant and can be dropped in the same pass.
+
+### What replaces each old use
+
+| Old use | Replacement |
+|---|---|
+| Merchant adds a data field | Custom Fields (sortable/filterable since 5.6) |
+| Extension adds a column to a core model | `additional_permitted_attributes` on the model |
+| Extension adds an STI rule/action type | `additional_permitted_attributes` + registry registration (unchanged) |
+| Core attribute lists | Inline `params.permit` in the controller (unchanged) |
+
+## Migration Path
+
+1. **Add the hook.** Define `additional_permitted_attributes` on `Spree::Base`. Delete the four redundant copies on the rule base classes.
+2. **Wire the union into `ParamsNormalizer#normalize_params`**, and replace the inference fallback in `ResourceController#permitted_attributes` with `NotImplementedError`. Run the API suite: any write controller that was silently relying on inference now fails loudly, which is the point. One did — `admin/tax_categories_controller` had full CRUD and no allowlist of its own; it now declares `[:name, :tax_code, :description, :is_default]`.
+3. **Inline the five Store API reads.** `wishlists`, `wishlist_items`, `carts/payment_sessions`, `carts/items`, `customer/payment_setup_sessions`. Each list is short and moves verbatim into the controller.
+4. **Handle `Carts::AddItem`.** It reads `line_item_attributes` to filter incoming option keys, so it needs a home for that list that is not a controller. Put it on `Spree::LineItem` as a constant and have both the workflow and `carts/items_controller` read it.
+5. **Convert `params.permit` call sites that skip `normalize_params`** so the union reaches them — these opt out otherwise. Controllers that already normalize need no change regardless of how they build their list.
+6. **Delete `ControllerHelpers::StrongParameters`**, its `include` in both base controllers, its `require_dependency`, and `spree/core/spec/lib/spree/core/controller_helpers/strong_parameters_spec.rb`.
+7. **Delete `spree/core/lib/spree/permitted_attributes.rb`** and any `require` of it.
+8. **Docs.** Rewrite the `Permitted Attributes` section of `docs/developer/customization/api.mdx`; update the `brand_id` examples in `docs/developer/tutorial/extending-models.mdx` (two places) and `docs/developer/tutorial/api.mdx`.
+9. **Upgrade guide.** Add a breaking-change entry to `docs/developer/upgrades/5.6-to-6.0.mdx` covering the constant removal, the helper-module removal, and the `additional_permitted_attributes` replacement with a before/after example.
+10. **Specs.** Cover the union in `ResourceController` (an extension-declared attribute is writable; an undeclared one is dropped), and confirm `NotImplementedError` when neither `permitted_attributes` nor `permitted_params` is defined.
+
+## Constraints on Current Work
+
+- Do not add new keys to `Spree::PermittedAttributes`, and do not read it in new code.
+- New v3 controllers declare `permitted_attributes` (a plain list) rather than overriding `permitted_params`, unless the controller genuinely needs a bespoke builder. Overriding `permitted_params` opts out of the extension union.
+- Do not rely on the model-name inference fallback — it is being removed. Every write controller states its own list.
+- A core model must not declare its own base attributes via `additional_permitted_attributes`. That hook is for extensions.
+- Extensions being written now against `PermittedAttributes` should be pointed at `additional_permitted_attributes` instead.
+
+## Open Questions
+
+- Whether the two `admin/products_controller` inline `variants: [...]` lists and the nested `Admin::Products::VariantsController` list should be consolidated as part of this work. The three-places problem from `6.0-duties-and-custom-fees.md` is adjacent but not caused by the registry, and fixing it here would widen the change. Leaning toward a separate follow-up.
+- Whether the remaining `params.permit` call sites that bypass `normalize_params` should be converted in bulk. They opt out of the extension union, but converting them is unrelated churn; the position taken here is to convert them as they are touched.
+
+**Resolved during implementation:** the option-key list `Carts::AddItem` needs now lives on `Spree::LineItem::WRITABLE_ATTRIBUTES`, read by both the workflow and the Store API items controller. Note that the old code did `line_item_attributes.flatten`, which left the literal `{ metadata: {} }` hash as an options key — meaningless, and surviving only because a later `delete_if` dropped nils. The constant holds the three scalar keys that were actually doing work.
+
+## References
+
+- `docs/plans/6.0-admin-api.md` — v3 flat-params conventions
+- `docs/plans/6.0-duties-and-custom-fees.md` — the three-places failure that motivated distrusting the global list
+- `docs/plans/6.0-delivery-method-rules.md`, `docs/plans/6.0-extendable-validations.md` — the `additional_permitted_attributes` precedent and the decorators-stay-the-additive-path position
+- `spree/core/lib/spree/permitted_attributes.rb`, `spree/core/lib/spree/core/controller_helpers/strong_parameters.rb` — the code being removed
diff --git a/docs/v6/developer/customization/api.mdx b/docs/v6/developer/customization/api.mdx
new file mode 100644
index 0000000000..6c236d778e
--- /dev/null
+++ b/docs/v6/developer/customization/api.mdx
@@ -0,0 +1,221 @@
+---
+title: Customizing the Spree API
+description: Add new Store API endpoints, customize existing JSON responses with serializer decorators, and extend Spree's REST API to fit your storefront needs.
+---
+
+Before you start customizing Spree API endpoints, make sure you reviewed all existing API endpoints in the [Spree API docs](/api-reference/admin-api/endpoints).
+
+For a step-by-step walkthrough of adding a complete new resource (model, serializer, controller, routes), see the [API tutorial](/developer/tutorial/api).
+
+## Customizing JSON Responses
+
+Spree uses [Alba](https://github.com/okuramasafumi/alba) serializers to build API v3 responses. You can replace any serializer via [Spree Dependencies](dependencies).
+
+### Adding Custom Attributes
+
+Let's say you want to add a `my_custom_attribute` column to the Product API response.
+
+Create a custom serializer that inherits from the core one:
+
+```ruby app/serializers/my_app/product_serializer.rb
+module MyApp
+ class ProductSerializer < Spree::Api::V3::ProductSerializer
+ attribute :my_custom_attribute
+ end
+end
+```
+
+Register it in `config/initializers/spree.rb`:
+
+```ruby
+Spree::Api::Dependencies.product_serializer = 'MyApp::ProductSerializer'
+```
+
+Restart the server and the Product API will include your new attribute.
+
+### Adding an Association
+
+Let's say you've created a `Spree::Brand` model that belongs to `Product` (see the [tutorial](/developer/tutorial/api) for the full example).
+
+Create a serializer for the new model:
+
+```ruby app/serializers/spree/api/v3/brand_serializer.rb
+module Spree
+ module Api
+ module V3
+ class BrandSerializer < BaseSerializer
+ typelize name: :string, slug: [:string, nullable: true]
+
+ attributes :name, :slug
+ end
+ end
+ end
+end
+```
+
+Then subclass the Product serializer to include the brand association:
+
+```ruby app/serializers/my_app/product_serializer.rb
+module MyApp
+ class ProductSerializer < Spree::Api::V3::ProductSerializer
+ typelize brand_id: [:string, nullable: true]
+
+ attribute :brand_id do |product|
+ product.brand&.prefixed_id
+ end
+
+ one :brand,
+ resource: Spree::Api::V3::BrandSerializer,
+ if: proc { expand?('brand') }
+ end
+end
+```
+
+Register it in `config/initializers/spree.rb`:
+
+```ruby
+Spree::Api::Dependencies.product_serializer = 'MyApp::ProductSerializer'
+```
+
+The brand data is available via `?expand=brand`:
+
+```
+GET /api/v3/store/products/prod_86Rf07xd4z?expand=brand
+```
+
+### Serializer Dependency Keys
+
+Here are the most commonly customized v3 serializers:
+
+| Key | Default |
+|-----|---------|
+| `product_serializer` | `Spree::Api::V3::ProductSerializer` |
+| `variant_serializer` | `Spree::Api::V3::VariantSerializer` |
+| `cart_serializer` | `Spree::Api::V3::CartSerializer` |
+| `order_serializer` | `Spree::Api::V3::OrderSerializer` |
+| `line_item_serializer` | `Spree::Api::V3::LineItemSerializer` |
+| `category_serializer` | `Spree::Api::V3::CategorySerializer` |
+| `customer_serializer` | `Spree::Api::V3::CustomerSerializer` |
+| `address_serializer` | `Spree::Api::V3::AddressSerializer` |
+| `payment_serializer` | `Spree::Api::V3::PaymentSerializer` |
+| `fulfillment_serializer` | `Spree::Api::V3::FulfillmentSerializer` |
+
+See `Spree::Api::ApiDependencies` for the full list.
+
+## Adding New Endpoints
+
+### Controller
+
+Inherit from `Spree::Api::V3::Store::ResourceController` for Store API endpoints:
+
+```ruby app/controllers/spree/api/v3/store/brands_controller.rb
+module Spree
+ module Api
+ module V3
+ module Store
+ class BrandsController < ResourceController
+ protected
+
+ def model_class
+ Spree::Brand
+ end
+
+ def serializer_class
+ Spree::Api::V3::BrandSerializer
+ end
+
+ def scope
+ Spree::Brand.all
+ end
+ end
+ end
+ end
+ end
+end
+```
+
+The base `ResourceController` provides:
+
+| Feature | How |
+|---------|-----|
+| Pagination | [Pagy](https://github.com/ddnexus/pagy) — `?page=2&limit=25` |
+| Filtering | [Ransack](https://github.com/activerecord-hackery/ransack) — `?q[name_cont]=nike` |
+| Sorting | JSON:API style — `?sort=-name` |
+| Authorization | [CanCanCan](https://github.com/CanCanCommunity/cancancan) |
+| Prefixed IDs | Stripe-style — `brand_k5nR8xLq` |
+
+Override these methods to customize:
+
+| Method | Purpose |
+|--------|---------|
+| `model_class` | ActiveRecord model (required) |
+| `serializer_class` | Alba serializer (required) |
+| `scope` | Base query — add `.where()` to filter |
+| `find_resource` | Custom ID lookup (slug fallback, etc.) |
+| `permitted_params` | Custom strong params |
+| `collection_includes` | Eager loading for `index` |
+
+### Routes
+
+Add routes in your app's `config/routes.rb`:
+
+```ruby
+Spree::Core::Engine.add_routes do
+ namespace :api, defaults: { format: 'json' } do
+ namespace :v3 do
+ namespace :store do
+ resources :brands, only: [:index, :show]
+ end
+ end
+ end
+end
+```
+
+### Permitted Attributes
+
+For endpoints that accept writes (create/update), declare the attributes in your
+controller:
+
+```ruby
+def resource_permitted_attributes
+ [:name, :slug, :description, :logo]
+end
+```
+
+Entries are `params.permit` fragments, so collections and nested structures use
+the shapes you would pass there directly — `[:name, { region_ids: [] }]`.
+
+<Note>
+ Declare `resource_permitted_attributes`, not `permitted_attributes`. The
+ latter is what appends extension-contributed attributes to your list, so
+ overriding it replaces them.
+</Note>
+
+### Adding an Attribute to a Core Resource
+
+To make a new column writable on a Spree model without decorating the
+controllers that write it, append to the model's permitted attributes:
+
+```ruby config/initializers/spree.rb
+Spree::Product.additional_permitted_attributes += [:brand_id]
+```
+
+Standard resource endpoints append these to their own allowlist, so one
+declaration covers the model's create and update endpoints.
+
+Use `+=`, never `=` — assigning replaces what another extension added — and
+declare only attributes of your own, since redeclaring a key the controller
+already permits replaces its filter rather than widening it.
+
+<Note>
+ For merchant-managed data, prefer [Custom Fields](/developer/core-concepts/metafields),
+ which need no code and are filterable and sortable. This is for extensions
+ that add real database columns.
+</Note>
+
+Two endpoints deliberately ignore this hook because their parameters are
+authorization data rather than resource data: API keys and invitations.
+
+## Consuming Custom Endpoints with the SDK
+
+See the [SDK tutorial](/developer/tutorial/sdk) for how to call custom endpoints from TypeScript and extend the generated types.
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.rb
index bd8b2632a7..225a74ccc6 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
@@ -76,16 +76,16 @@ module Spree
private
- # Per-subclass permitted params. Calls `permitted_params` (the base
- # allowlist with `type` + `preferences`) and merges in extras the
- # subclass has declared via `additional_permitted_attributes`.
- # Controllers can override this hook directly if their subclasses
- # expose extras through a different mechanism.
+ # Per-subclass permitted params: the controller's own allowlist plus
+ # whatever the concrete subclass declares through
+ # `additional_permitted_attributes`. Controllers can override this
+ # hook directly if their subclasses expose extras through a different
+ # mechanism.
def permitted_params_for(klass)
extras = klass.respond_to?(:additional_permitted_attributes) ? klass.additional_permitted_attributes : []
return permitted_params if extras.blank?
- params.permit(:type, { preferences: {} }, *extras)
+ permitted_params.merge(params.permit(:type, *extras, preferences: {}))
end
# Default build: top-level resource. Nested controllers (actions,
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb b/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
index 09cb04bcef..01e6f86b4a 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
@@ -10,8 +10,11 @@ module Spree
# to Rails `_attributes` format (e.g. `variants_attributes: [...]`) based on
# the model's `accepts_nested_attributes_for` declarations.
#
- # Uses `prepend` so it always wraps `permitted_params` regardless of which
- # controller in the hierarchy defines it — no manual calls needed.
+ # `normalize_params` is called explicitly by a controller's
+ # `permitted_params`. It is deliberately NOT applied to every write: it
+ # recurses into nested hashes decoding anything shaped like a prefixed ID,
+ # which would corrupt opaque provider values (see
+ # Admin::PaymentMethodsController).
module ParamsNormalizer
extend ActiveSupport::Concern
diff --git a/spree/api/app/controllers/spree/api/v3/admin/allowed_origins_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/allowed_origins_controller.rb
index 0757abafe8..9cf7b853d3 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/allowed_origins_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/allowed_origins_controller.rb
@@ -16,7 +16,7 @@ module Spree
end
def permitted_params
- params.permit(:origin)
+ params.permit(*model_additional_permitted_attributes, :origin)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/api_keys_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/api_keys_controller.rb
index b3a8f70b57..94f3ec8424 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/api_keys_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/api_keys_controller.rb
@@ -98,6 +98,8 @@ module Spree
# lives on Spree::ApiKey); update is limited to the human-facing `name`.
# Stripping them here keeps them out of mass assignment so a rename
# returns 200 rather than 422.
+ # No extension union: an API key's scopes and type are the authorization
+ # surface itself, not extensible resource data.
def permitted_params
return params.permit(:name) if action_name == 'update'
diff --git a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
index 21f05ce6f6..5736b6d2b4 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
@@ -67,6 +67,7 @@ module Spree
# can't be targeted).
def permitted_params
permitted = params.permit(
+ *model_additional_permitted_attributes,
:name, :description, :permalink,
:meta_title, :meta_description, :meta_keywords,
:image, :square_image,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
index 3fdbd2e90a..8a56f13598 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
@@ -65,7 +65,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :code, :active, :default, :preferred_order_routing_strategy,
+ params.permit(*model_additional_permitted_attributes, :name, :code, :active, :default, :preferred_order_routing_strategy,
:preferred_storefront_access, :preferred_guest_checkout,
stock_location_ids: [])
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/claim_reasons_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/claim_reasons_controller.rb
index ce04c13000..a9f6cac7c1 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/claim_reasons_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/claim_reasons_controller.rb
@@ -16,7 +16,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :active)
+ params.permit(*model_additional_permitted_attributes, :name, :active)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
index dc5266d14b..33d3e05882 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
@@ -26,7 +26,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :external_id, metadata: {})
+ params.permit(*model_additional_permitted_attributes, :name, :external_id, metadata: {})
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/company_locations/contacts_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/company_locations/contacts_controller.rb
index 960a4e8f50..2dc989403e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/company_locations/contacts_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/company_locations/contacts_controller.rb
@@ -49,7 +49,7 @@ module Spree
end
def permitted_params
- params.permit(:customer_id, :role)
+ params.permit(*model_additional_permitted_attributes, :customer_id, :role)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
index 2629b69091..79524de2db 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
@@ -21,7 +21,7 @@ module Spree
end
def permitted_params
- params.permit(:namespace, :key, :label, :field_type,
+ params.permit(*model_additional_permitted_attributes, :namespace, :key, :label, :field_type,
:resource_type, :storefront_visible,
:searchable, :sortable)
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
index 73ed5dedc4..aa59fedc44 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
@@ -86,7 +86,7 @@ module Spree
# `custom_field_definition_id` is an alias_attribute on Spree::CustomField;
# AR resolves the prefixed-ID and the alias to the canonical FK on assign.
def permitted_params
- params.permit(:custom_field_definition_id, :value)
+ params.permit(*model_additional_permitted_attributes, :custom_field_definition_id, :value)
end
def update_permitted_params
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customer_groups_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customer_groups_controller.rb
index 32f4706730..bb3929814c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customer_groups_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customer_groups_controller.rb
@@ -22,7 +22,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :description, customer_ids: [])
+ params.permit(*model_additional_permitted_attributes, :name, :description, customer_ids: [])
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
index ae3d9a7f6e..3a60505998 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
@@ -91,6 +91,7 @@ module Spree
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
:email, :first_name, :last_name, :phone,
:password, :password_confirmation, :selected_locale,
:avatar, :accepts_email_marketing, :internal_note,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
index 8b9ec24db8..6a46b8a68c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
@@ -24,6 +24,7 @@ module Spree
@resource = rule_class.new(delivery_method: parent, active: active_param)
assign_rule_preferences(@resource)
assign_rule_products(@resource)
+ assign_extension_attributes(@resource)
authorize_resource!(@resource, :create)
if @resource.save
@@ -37,6 +38,7 @@ module Spree
@resource.active = active_param unless params[:active].nil?
assign_rule_preferences(@resource)
assign_rule_products(@resource)
+ assign_extension_attributes(@resource)
if @resource.save
render json: serialize_resource(@resource)
@@ -60,7 +62,7 @@ module Spree
end
def permitted_params
- params.permit(:type, :active, preferences: {}, product_ids: [])
+ params.permit(*model_additional_permitted_attributes, :type, :active, preferences: {}, product_ids: [])
end
private
@@ -73,6 +75,16 @@ module Spree
params[:active].nil? ? true : params[:active].to_b
end
+ # This controller assigns each field by hand rather than mass-assigning,
+ # so attributes an extension contributed have to be forwarded too or
+ # permitting them would have no effect.
+ def assign_extension_attributes(rule)
+ keys = model_additional_permitted_attributes.flat_map { |a| a.is_a?(Hash) ? a.keys : a }
+ return if keys.empty?
+
+ rule.assign_attributes(permitted_params.to_h.slice(*keys.map(&:to_s)))
+ end
+
def assign_rule_preferences(rule)
(permitted_params[:preferences] || {}).each do |key, value|
next unless rule.has_preference?(key)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
index 5a82777689..0fcec6e89a 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
@@ -126,6 +126,7 @@ module Spree
# sheet in one round-trip.
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
:name, :admin_name, :code, :fulfillment_provider,
:pickup_point_provider, :rate_provider, :storefront_visible, :tracking_url,
:estimated_transit_business_days_min, :estimated_transit_business_days_max,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_profiles/origin_groups_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_profiles/origin_groups_controller.rb
index a4bb55e496..89c95b0fdc 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_profiles/origin_groups_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_profiles/origin_groups_controller.rb
@@ -46,7 +46,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :position, stock_location_ids: [])
+ params.permit(*model_additional_permitted_attributes, :name, :position, stock_location_ids: [])
end
def collection_includes
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_profiles_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_profiles_controller.rb
index 26574f3821..51314dde29 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_profiles_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_profiles_controller.rb
@@ -59,7 +59,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :default, :position, :kind, stock_location_ids: [])
+ params.permit(*model_additional_permitted_attributes, :name, :default, :position, :kind, stock_location_ids: [])
end
def collection_includes
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_zones_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_zones_controller.rb
index 3cb9f7aa1c..3c2f59b4d2 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_zones_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_zones_controller.rb
@@ -51,6 +51,7 @@ module Spree
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
:name, :description, :delivery_profile_id, :delivery_origin_group_id,
members: [:member_type, :country_code, :state_code, :postal_code_prefix, :postal_code_from, :postal_code_to]
)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb
index 6a45440ffd..cebd25fd2e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb
@@ -98,7 +98,7 @@ module Spree
# is intentionally dropped — only CSV is supported and Rails' request
# format would otherwise overwrite the model's enum.
def permitted_params
- attrs = params.permit(:type, :record_selection, :results_url)
+ attrs = params.permit(*model_additional_permitted_attributes, :type, :record_selection, :results_url)
raw = params[:search_params]
attrs[:search_params] = raw.respond_to?(:to_unsafe_h) ? raw.to_unsafe_h : raw if raw.present?
attrs
diff --git a/spree/api/app/controllers/spree/api/v3/admin/gift_card_batches_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/gift_card_batches_controller.rb
index 3edd4e52bb..c115ea641a 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/gift_card_batches_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/gift_card_batches_controller.rb
@@ -22,7 +22,7 @@ module Spree
end
def permitted_params
- params.permit(:prefix, :codes_count, :amount, :expires_at, :currency)
+ params.permit(*model_additional_permitted_attributes, :prefix, :codes_count, :amount, :expires_at, :currency)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb
index 1be72aff48..e4dbce5488 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb
@@ -24,7 +24,7 @@ module Spree
end
def permitted_params
- params.permit(:code, :amount, :expires_at, :user_id, :currency)
+ params.permit(*model_additional_permitted_attributes, :code, :amount, :expires_at, :user_id, :currency)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
index f0590efb83..10188af415 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
@@ -234,7 +234,7 @@ module Spree
end
def permitted_params
- params.permit(:type, :attachment, :preferred_delimiter, :results_url)
+ params.permit(*model_additional_permitted_attributes, :type, :attachment, :preferred_delimiter, :results_url)
end
# Returns the registered Import subclass matching `name`, or nil.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/integrations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/integrations_controller.rb
index 6f2bc5bcdf..3ec201d473 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/integrations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/integrations_controller.rb
@@ -47,7 +47,7 @@ module Spree
end
def permitted_params
- params.permit(:type, :active, preferences: {})
+ params.permit(*model_additional_permitted_attributes, :type, :active, preferences: {})
end
# `types` is read-only discovery — maps to the read scope.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/invitations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/invitations_controller.rb
index fb3f396724..04a6ead3e4 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/invitations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/invitations_controller.rb
@@ -69,6 +69,8 @@ module Spree
end
# `email` and `role_id` are flat — `role_id` accepts a prefixed ID.
+ # No extension union: an invitation carries only the role grant, which is
+ # the authorization surface itself, not extensible resource data.
def permitted_params
attrs = params.permit(:email, :role_id)
if attrs[:role_id].present? && Spree::PrefixedId.prefixed_id?(attrs[:role_id])
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.rb
index 967a9e1ce6..da5b2d31fc 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
@@ -77,6 +77,7 @@ module Spree
# attributes — everything a client can set lives on the model.
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
*Spree::Media::WRITABLE_ATTRIBUTES,
:attachment, :url, :signed_id,
variant_ids: []
diff --git a/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb
index b9383545cd..a8f52f6c4e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb
@@ -21,6 +21,7 @@ module Spree
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
:name, :label, :position, :filterable, :kind,
option_values: [
:id, :name, :label, :position, :color_code, :image
diff --git a/spree/api/app/controllers/spree/api/v3/admin/order_routing_rules_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/order_routing_rules_controller.rb
index 24df26f3c8..8474636364 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/order_routing_rules_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/order_routing_rules_controller.rb
@@ -30,7 +30,7 @@ module Spree
end
def permitted_params
- params.permit(:type, :active, :position, preferences: {})
+ params.permit(*model_additional_permitted_attributes, :type, :active, :position, preferences: {})
end
# `types` is read-only discovery — maps to the read scope + :show ability.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
index d4c1a4f28f..1ba09bbb4b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
@@ -43,12 +43,19 @@ module Spree
Spree.api.admin_payment_method_serializer
end
- # Explicit allowlist per the v3 convention — flat params, no
- # reach into the global `Spree::PermittedAttributes` registry
- # (which is the legacy Rails admin's surface). `type` and
+ # Explicit allowlist per the v3 convention — flat params. `type` and
# `preferences` are added by `SubclassedResource` on top.
+ # Deliberately NOT routed through `normalize_params`: gateway
+ # `preferences` are opaque provider values, and prefixed-ID resolution
+ # recurses into nested hashes — a Stripe `webhook_endpoint_id` like
+ # `we_1MqJ8b...` matches the prefixed-ID shape and would be decoded to
+ # an integer. `type` and `preferences` are added by `SubclassedResource`.
def permitted_params
- params.permit(:name, :description, :active, :storefront_visible, :auto_capture, :capture_method, :position, metadata: {}, preferences: {})
+ params.permit(
+ :name, :description, :active, :storefront_visible, :auto_capture, :capture_method, :position,
+ *model_additional_permitted_attributes,
+ metadata: {}, preferences: {}
+ )
end
# `types` is read-only discovery — maps to the read scope + :show ability.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb
index d1a0f2b431..217061375a 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb
@@ -101,7 +101,7 @@ module Spree
# scopes so a foreign or unknown id 404s instead of binding the
# price to another store's record.
def permitted_params
- permitted = params.permit(:variant_id, :currency, :amount, :compare_at_amount, :price_list_id)
+ permitted = params.permit(*model_additional_permitted_attributes, :variant_id, :currency, :amount, :compare_at_amount, :price_list_id)
permitted[:variant_id] = store_variants.find_by_prefix_id!(permitted[:variant_id]).id if permitted[:variant_id].present?
permitted[:price_list_id] = store_price_lists.find_by_prefix_id!(permitted[:price_list_id]).id if permitted[:price_list_id].present?
permitted
diff --git a/spree/api/app/controllers/spree/api/v3/admin/product_types_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/product_types_controller.rb
index 0708709486..e1b936a00b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/product_types_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/product_types_controller.rb
@@ -51,6 +51,7 @@ module Spree
def permitted_params
attrs = params.permit(
+ *model_additional_permitted_attributes,
:name,
:delivery_profile_id,
option_type_ids: [],
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
index 16f3dd8037..9ec9ddbe04 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
@@ -31,6 +31,7 @@ module Spree
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
:sku, :barcode,
:cost_price, :cost_currency,
:weight, :height, :width, :depth, :weight_unit, :dimensions_unit,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index cc85e1a056..a773096926 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -201,6 +201,7 @@ module Spree
# variant, so they ship prices alongside name/status and the
# `Spree::Product#prices=` setter forwards them to it.
params.permit(
+ *model_additional_permitted_attributes,
:name, :description, :slug, :status,
:meta_title, :meta_description, :meta_keywords,
:tax_category_id, :product_type_id, :delivery_profile_id,
diff --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.rb
index f8161e76b4..14b096cfb2 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
@@ -52,7 +52,7 @@ module Spree
end
def permitted_params
- params.permit(:type, preferences: {})
+ params.permit(*model_additional_permitted_attributes, :type, preferences: {})
end
# `types`/`calculators` are read-only discovery — read scope + :show ability.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/promotion_rules_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/promotion_rules_controller.rb
index 9aa9dd5bee..2674a1e493 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/promotion_rules_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/promotion_rules_controller.rb
@@ -30,7 +30,7 @@ module Spree
end
def permitted_params
- params.permit(:type, preferences: {})
+ params.permit(*model_additional_permitted_attributes, :type, preferences: {})
end
# `types` is read-only discovery — maps to the read scope + :show ability.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
index 124cba47e8..0cb6282d2d 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
@@ -29,11 +29,7 @@ module Spree
# every built-in rule/action's expected keys. Plugin-defined
# subclasses can add to it — see `additional_permitted_attributes`
# below.
- def permitted_params
- normalize_params(params.permit(*permitted_attributes))
- end
-
- def permitted_attributes
+ def resource_permitted_attributes
[
:name, :description, :code, :path,
:starts_at, :expires_at, :usage_limit, :match_policy,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/refund_reasons_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/refund_reasons_controller.rb
index 07b67ac25c..5de70654ce 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/refund_reasons_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/refund_reasons_controller.rb
@@ -16,7 +16,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :active)
+ params.permit(*model_additional_permitted_attributes, :name, :active)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/return_reasons_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/return_reasons_controller.rb
index 0d6889ab39..c66dccdb05 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/return_reasons_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/return_reasons_controller.rb
@@ -16,7 +16,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :active)
+ params.permit(*model_additional_permitted_attributes, :name, :active)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/roles_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/roles_controller.rb
index 29b2af623f..e39c622539 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/roles_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/roles_controller.rb
@@ -58,7 +58,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :description, permissions: [])
+ params.permit(*model_additional_permitted_attributes, :name, :description, permissions: [])
end
private
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
index 92202e89b5..9655d03642 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
@@ -93,7 +93,7 @@ module Spree
# optional so an audit requirement never turns an existing endpoint
# into a 422; omitting it falls back to a translated default.
def permitted_params
- params.permit(:count_on_hand, :backorderable, :reason, metadata: {})
+ params.permit(*model_additional_permitted_attributes, :count_on_hand, :backorderable, :reason, metadata: {})
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
index 7d3a28d57d..72d902ddb6 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
@@ -27,6 +27,7 @@ module Spree
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
:name, :admin_name, :active, :default,
:kind, :propagate_all_variants, :backorderable_default,
:address1, :address2, :city, :zipcode, :phone, :company,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb
index df08636ab7..556fac0ff4 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb
@@ -14,6 +14,10 @@ module Spree
def serializer_class
Spree.api.admin_tax_category_serializer
end
+
+ def resource_permitted_attributes
+ [:name, :tax_code, :description, :is_default]
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb
index 0aa0e9c50d..81343535eb 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb
@@ -22,7 +22,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :amount, :amount_percentage, :included_in_price,
+ params.permit(*model_additional_permitted_attributes, :name, :amount, :amount_percentage, :included_in_price,
:show_rate_in_label, :tax_category_id,
:country_code, :state_code, metadata: {})
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/webhook_endpoints_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/webhook_endpoints_controller.rb
index 402e18035e..43ecd6b9fd 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/webhook_endpoints_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/webhook_endpoints_controller.rb
@@ -66,7 +66,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :url, :active, subscriptions: [])
+ params.permit(*model_additional_permitted_attributes, :name, :url, :active, subscriptions: [])
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rb
index 90ff273b60..fceea32730 100644
--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb
@@ -7,7 +7,6 @@ module Spree
include ActiveStorage::SetCurrent
include CanCan::ControllerAdditions
- include Spree::Core::ControllerHelpers::StrongParameters
include Spree::Core::ControllerHelpers::Store
include Spree::Api::V3::LocaleAndCurrency
include Spree::Api::V3::JwtAuthentication
diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
index 8697eab39d..7a21eb7ea8 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -330,25 +330,38 @@ module Spree
raise NotImplementedError, 'Subclass must implement serializer_class'
end
- # Permit flat parameters based on model class
- # Automatically infers attribute list from Spree::PermittedAttributes
- # e.g., ProductsController -> Spree::PermittedAttributes.product_attributes
- #
- # Override in subclass for custom parameter handling
def permitted_params
- normalize_params(params.permit(permitted_attributes))
+ normalize_params(params.permit(*permitted_attributes))
end
- # Returns the permitted attributes list for the model
- # Override in subclass for custom attributes
+ # This resource's writable attributes, plus anything extensions have
+ # declared on the model. Override +resource_permitted_attributes+ rather
+ # than this, so the extension union is not lost.
def permitted_attributes
- Spree::PermittedAttributes.public_send(permitted_attributes_key)
+ resource_permitted_attributes + model_additional_permitted_attributes
+ end
+
+ # Override in subclass to declare the resource's writable attributes.
+ def resource_permitted_attributes
+ raise NotImplementedError, 'Subclass must implement resource_permitted_attributes or permitted_params'
end
- # Infers the PermittedAttributes key from model class
- # e.g., Spree::Product -> :product_attributes
- def permitted_attributes_key
- :"#{model_class.model_name.element}_attributes"
+ # Attributes extensions have declared on the model via
+ # +Spree::Product.additional_permitted_attributes += [...]+.
+ #
+ # Guarded on both sides: a controller need not define +model_class+
+ # (and one that does may raise NotImplementedError), and
+ # `Spree.base_class` is host-overridable, so the class_attribute is not
+ # guaranteed to be inherited from Spree::Base.
+ def model_additional_permitted_attributes
+ return [] unless respond_to?(:model_class, true)
+
+ model = model_class
+ return [] unless model.respond_to?(:additional_permitted_attributes)
+
+ Array(model.additional_permitted_attributes)
+ rescue NotImplementedError
+ []
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
index f39f21caec..233fb33af6 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
@@ -17,7 +17,7 @@ module Spree
variant: variant,
quantity: permitted_params[:quantity] || 1,
metadata: permitted_params[:metadata] || {},
- options: permitted_params[:options] || {}
+ options: item_options
)
if result.success?
@@ -96,8 +96,21 @@ module Spree
@variant ||= current_store.variants.find_by_prefix_id!(permitted_params[:variant_id])
end
+ # Extension attributes ride in `options`, which is how AddItem
+ # forwards per-line-item values onto the record.
+ def item_options
+ keys = Spree::LineItem.additional_permitted_attributes.flat_map { |a| a.is_a?(Hash) ? a.keys : a }
+ extras = permitted_params.to_h.slice(*keys.map(&:to_s)).symbolize_keys
+
+ (permitted_params[:options] || {}).to_h.symbolize_keys.merge(extras)
+ end
+
def permitted_params
- params.permit(Spree::PermittedAttributes.line_item_attributes + [{ options: {} }])
+ params.permit(
+ :id, :variant_id, :quantity,
+ *Spree::LineItem.additional_permitted_attributes,
+ { metadata: {}, options: {} }
+ )
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb
index 0d0fef27e6..f7ca3eb645 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb
@@ -85,7 +85,11 @@ module Spree
end
def permitted_params
- params.permit(Spree::PermittedAttributes.payment_session_attributes)
+ params.permit(
+ :amount, :payment_method_id,
+ *Spree::PaymentSession.additional_permitted_attributes,
+ { external_data: {} }
+ )
end
def complete_params
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
index ff8bde8174..710b7f7eae 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
@@ -162,6 +162,7 @@ module Spree
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
:email,
:customer_note,
:market_id,
diff --git a/spree/api/app/controllers/spree/api/v3/store/customer/addresses_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/addresses_controller.rb
index c4e8537aae..5ee0bc0a69 100644
--- a/spree/api/app/controllers/spree/api/v3/store/customer/addresses_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/customer/addresses_controller.rb
@@ -63,6 +63,7 @@ module Spree
def permitted_params
params.permit(
+ *model_additional_permitted_attributes,
:first_name, :last_name, :address1, :address2, :city,
# country_iso and state_abbr are the legacy write names, accepted until 6.1.
:postal_code, :phone, :company, :country_code, :country_iso, :state_code, :state_abbr, :state_name,
diff --git a/spree/api/app/controllers/spree/api/v3/store/customer/payment_setup_sessions_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/payment_setup_sessions_controller.rb
index 470c9451b6..d9334f10cc 100644
--- a/spree/api/app/controllers/spree/api/v3/store/customer/payment_setup_sessions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/customer/payment_setup_sessions_controller.rb
@@ -11,7 +11,7 @@ module Spree
# POST /api/v3/store/customer/payment_setup_sessions
def create
- payment_method = current_store.payment_methods.find_by_prefix_id!(permitted_params[:payment_method_id])
+ payment_method = current_store.payment_methods.find_by_prefix_id!(params[:payment_method_id])
@payment_setup_session = payment_method.create_payment_setup_session(
customer: current_user,
@@ -62,8 +62,8 @@ module Spree
Spree.api.payment_setup_session_serializer
end
- def permitted_params
- params.permit(Spree::PermittedAttributes.payment_setup_session_attributes)
+ def resource_permitted_attributes
+ [:payment_method_id, { external_data: {} }]
end
def complete_params
diff --git a/spree/api/app/controllers/spree/api/v3/store/wishlist_items_controller.rb b/spree/api/app/controllers/spree/api/v3/store/wishlist_items_controller.rb
index 4652f5bb18..3db6e7d5df 100644
--- a/spree/api/app/controllers/spree/api/v3/store/wishlist_items_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/wishlist_items_controller.rb
@@ -26,8 +26,8 @@ module Spree
Spree.api.wished_item_serializer
end
- def permitted_params
- params.permit(Spree::PermittedAttributes.wished_item_attributes)
+ def resource_permitted_attributes
+ [:variant_id, :quantity]
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/wishlists_controller.rb b/spree/api/app/controllers/spree/api/v3/store/wishlists_controller.rb
index 8b30469ef0..b31afd8ded 100644
--- a/spree/api/app/controllers/spree/api/v3/store/wishlists_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/wishlists_controller.rb
@@ -31,8 +31,8 @@ module Spree
Spree.api.wishlist_serializer
end
- def permitted_params
- params.permit(Spree::PermittedAttributes.wishlist_attributes)
+ def resource_permitted_attributes
+ [:name, :is_default, :is_private]
end
end
end
diff --git a/spree/api/config/brakeman.ignore b/spree/api/config/brakeman.ignore
index bb82152149..28c4ab41d2 100644
--- a/spree/api/config/brakeman.ignore
+++ b/spree/api/config/brakeman.ignore
@@ -22,13 +22,13 @@
{
"warning_type": "Mass Assignment",
"warning_code": 105,
- "fingerprint": "17068dd5ef916d4f3a1af654de9c2dc642b1c231e44b6b07ee72e7db1051c1e6",
+ "fingerprint": "26cd4e4bf0db3c32251ebb3814f52d4a72f612b20c6a668f17b3a385526c5663",
"check_name": "PermitAttributes",
"message": "Potentially dangerous key allowed for mass assignment",
"file": "app/controllers/spree/api/v3/admin/company_locations/contacts_controller.rb",
"line": 52,
"link": "https://brakemanscanner.org/docs/warning_types/mass_assignment/",
- "code": "params.permit(:customer_id, :role)",
+ "code": "params.permit(*model_additional_permitted_attributes, :customer_id, :role)",
"render_path": null,
"location": {
"type": "method",
@@ -40,7 +40,7 @@
"cwe_id": [
915
],
- "note": "Spree::CompanyContact#role names the buyer's role at a company branch (buyer, approver) and grants nothing — permissions and purchase authority are not modelled in 6.0. Staff-only endpoint behind the write_customers permission, so it cannot be reached by the customer it describes."
+ "note": "Spree::CompanyContact#role names the buyer's role at a company branch (buyer, approver) and grants nothing \u2014 permissions and purchase authority are not modelled in 6.0. Staff-only endpoint behind the write_customers permission, so it cannot be reached by the customer it describes."
}
],
"brakeman_version": "7.1.0"
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
index 41f4007c05..12519b62ac 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -2169,4 +2169,42 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
expect(product.reload.deleted_at).to be_nil
end
end
+
+ # The documented extension path: declare the attribute on the model, and every
+ # v3 endpoint that writes it accepts the attribute. Products is the worked
+ # example in the docs AND a controller that builds its allowlist by hand, so
+ # it is the regression that matters.
+ describe 'extension-contributed attributes' do
+ before { request.headers.merge!(headers) }
+
+ around do |example|
+ original = Spree::Product.additional_permitted_attributes
+ example.run
+ Spree::Product.additional_permitted_attributes = original
+ end
+
+ it 'permits an attribute the model declares' do
+ # The documented extension contract, exercised for real.
+ Spree::Product.additional_permitted_attributes += [:brand_id]
+
+ expect_any_instance_of(described_class).to receive(:permitted_params).at_least(:once).and_wrap_original do |original|
+ result = original.call
+ expect(result.keys).to include('brand_id')
+ result.except('brand_id')
+ end
+
+ patch :update, params: { id: product.prefixed_id, brand_id: 'acme' }, as: :json
+ end
+
+ it 'drops an attribute nobody declared' do
+ expect_any_instance_of(described_class).to receive(:permitted_params).at_least(:once).and_wrap_original do |original|
+ result = original.call
+ expect(result.keys).not_to include('sneaky')
+ result
+ end
+
+ patch :update, params: { id: product.prefixed_id, sneaky: 'nope' }, as: :json
+ end
+ end
+
end
diff --git a/spree/api/spec/controllers/spree/api/v3/params_normalizer_spec.rb b/spree/api/spec/controllers/spree/api/v3/params_normalizer_spec.rb
index fd116f3cf9..e686566a02 100644
--- a/spree/api/spec/controllers/spree/api/v3/params_normalizer_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/params_normalizer_spec.rb
@@ -114,4 +114,5 @@ RSpec.describe Spree::Api::V3::ParamsNormalizer do
expect(result).to eq(hash)
end
end
+
end
diff --git a/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb
index 840dfd14fc..e6e9216383 100644
--- a/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb
@@ -45,4 +45,35 @@ RSpec.describe Spree::Api::V3::ResourceController, type: :controller do
expect(controller.scope.klass).to eq(Spree::PromotionRule)
end
end
+
+ # A controller that declares neither must fail loudly on its first write
+ # rather than silently permitting a list inferred from the model name.
+ describe '#resource_permitted_attributes' do
+ it 'raises unless the subclass declares one' do
+ expect { controller.send(:resource_permitted_attributes) }.to raise_error(NotImplementedError)
+ end
+ end
+
+ # Extensions declare extra writable attributes on the model rather than
+ # decorating every controller that writes it — see Spree::Base.
+ describe '#permitted_attributes' do
+ before do
+ allow(controller).to receive(:resource_permitted_attributes).and_return([:name])
+ end
+
+ it 'is just the resource list when the model declares nothing extra' do
+ expect(controller.send(:permitted_attributes)).to eq([:name])
+ end
+
+ # Exercises the real extension contract rather than stubbing the reader:
+ # an initializer appends to the model's class_attribute.
+ it 'appends attributes the model contributes' do
+ original = Spree::TaxCategory.additional_permitted_attributes
+ Spree::TaxCategory.additional_permitted_attributes += [:brand_id]
+
+ expect(controller.send(:permitted_attributes)).to eq([:name, :brand_id])
+ ensure
+ Spree::TaxCategory.additional_permitted_attributes = original
+ end
+ end
end
diff --git a/spree/core/app/models/spree/base.rb b/spree/core/app/models/spree/base.rb
index 73fe5ae28c..9b0b7c29f9 100644
--- a/spree/core/app/models/spree/base.rb
+++ b/spree/core/app/models/spree/base.rb
@@ -10,6 +10,18 @@ class Spree::Base < ApplicationRecord
include Spree::HasIsoGeography
include Spree::TypedAssociations
+ # Extra writable attributes contributed by extensions, appended to the v3
+ # controller allowlist for this resource. Core attributes belong in the
+ # controller's own list — this exists so an extension that adds a column can
+ # make it writable without decorating a controller:
+ #
+ # Spree::Product.additional_permitted_attributes += [:brand_id]
+ #
+ # Entries are `params.permit` fragments: bare symbols, or hashes for
+ # collections and nested structures (`{ region_ids: [] }`). Append with `+=`
+ # rather than assigning, so extensions don't clobber each other.
+ class_attribute :additional_permitted_attributes, instance_writer: false, default: [].freeze
+
# Backfills preferences added to the class after this row was last saved, so
# a reader never sees nil for a newly defined preference. Assigning
# unconditionally would dirty every record on load: `preferences` is a
diff --git a/spree/core/app/models/spree/commission_rule.rb b/spree/core/app/models/spree/commission_rule.rb
index 150c487165..8d84c1ed48 100644
--- a/spree/core/app/models/spree/commission_rule.rb
+++ b/spree/core/app/models/spree/commission_rule.rb
@@ -47,15 +47,6 @@ module Spree
registers_subclasses_via { Spree.commission_rules }
- # Extra params a subclass accepts beyond `type` and `preferences` —
- # association-backed config declares itself here so the nested rules API
- # stays generic (mirrors Spree::DeliveryMethodRule).
- #
- # @return [Array]
- def self.additional_permitted_attributes
- []
- end
-
# @return [String] the name an operator picks this rule kind by
def self.human_name
Spree.t("commission_rule_types.#{api_type}.name", default: name.demodulize.titleize)
diff --git a/spree/core/app/models/spree/commission_rules/product_rule.rb b/spree/core/app/models/spree/commission_rules/product_rule.rb
index a9b9568073..f5a2b2ecf8 100644
--- a/spree/core/app/models/spree/commission_rules/product_rule.rb
+++ b/spree/core/app/models/spree/commission_rules/product_rule.rb
@@ -18,9 +18,7 @@ module Spree
# of the serializer.
validate :products_belong_to_the_store
- def self.additional_permitted_attributes
- [product_ids: []]
- end
+ self.additional_permitted_attributes = [product_ids: []]
# The chosen products in prefixed form, read through the association so
# a soft-deleted product drops out — a client resubmitting this list must
diff --git a/spree/core/app/models/spree/delivery_method_rule.rb b/spree/core/app/models/spree/delivery_method_rule.rb
index 10e310f850..8d21030bef 100644
--- a/spree/core/app/models/spree/delivery_method_rule.rb
+++ b/spree/core/app/models/spree/delivery_method_rule.rb
@@ -25,15 +25,6 @@ module Spree
scope :active, -> { where(active: true) }
- # Extra params a subclass accepts beyond `type`/`active`/`preferences` —
- # association-backed config declares itself here so the nested rules API
- # stays generic (mirrors {Spree::PromotionRule.additional_permitted_attributes}).
- #
- # @return [Array]
- def self.additional_permitted_attributes
- []
- end
-
registers_subclasses_via { Spree.delivery_method_rules }
# @return [String] localized display name for the rule kind, used by admin pickers
diff --git a/spree/core/app/models/spree/delivery_method_rules/excluded_products_rule.rb b/spree/core/app/models/spree/delivery_method_rules/excluded_products_rule.rb
index 1591b9f0fe..8363b928be 100644
--- a/spree/core/app/models/spree/delivery_method_rules/excluded_products_rule.rb
+++ b/spree/core/app/models/spree/delivery_method_rules/excluded_products_rule.rb
@@ -11,9 +11,7 @@ module Spree
inverse_of: :delivery_method_rule
has_many :products, class_name: 'Spree::Product', through: :delivery_method_rule_products
- def self.additional_permitted_attributes
- [product_ids: []]
- end
+ self.additional_permitted_attributes = [product_ids: []]
# Excluded product ids in prefixed form. Plucked rather than hydrating N
# Product rows just to re-encode their ids, but read through the products
diff --git a/spree/core/app/models/spree/promotion/actions/create_adjustment.rb b/spree/core/app/models/spree/promotion/actions/create_adjustment.rb
index 3b9d0064cd..33c8cd62aa 100644
--- a/spree/core/app/models/spree/promotion/actions/create_adjustment.rb
+++ b/spree/core/app/models/spree/promotion/actions/create_adjustment.rb
@@ -9,9 +9,7 @@ module Spree
before_validation -> { self.calculator ||= Calculator::FlatPercentItemTotal.new }
- def self.additional_permitted_attributes
- [calculator: [:type, { preferences: {} }]]
- end
+ self.additional_permitted_attributes = [calculator: [:type, { preferences: {} }]]
def discount_scope
:order
diff --git a/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb b/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb
index 0ce1f61c33..e2b96daaa5 100644
--- a/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb
+++ b/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb
@@ -8,9 +8,7 @@ module Spree
before_validation -> { self.calculator ||= Calculator::PercentOnLineItem.new }
- def self.additional_permitted_attributes
- [calculator: [:type, { preferences: {} }]]
- end
+ self.additional_permitted_attributes = [calculator: [:type, { preferences: {} }]]
def discount_scope
:line_item
diff --git a/spree/core/app/models/spree/promotion/actions/create_line_items.rb b/spree/core/app/models/spree/promotion/actions/create_line_items.rb
index a762124f83..03532b4cd0 100644
--- a/spree/core/app/models/spree/promotion/actions/create_line_items.rb
+++ b/spree/core/app/models/spree/promotion/actions/create_line_items.rb
@@ -8,9 +8,7 @@ module Spree
after_save :handle_promotion_action_line_items
- def self.additional_permitted_attributes
- [line_items: [:variant_id, :quantity]]
- end
+ self.additional_permitted_attributes = [line_items: [:variant_id, :quantity]]
# API v3 flat alias for `promotion_action_line_items_attributes`.
# Accepts an array of `{ variant_id:, quantity: }` rows; the list
diff --git a/spree/core/app/models/spree/promotion/rules/category.rb b/spree/core/app/models/spree/promotion/rules/category.rb
index cfc2155f5e..6b567065ab 100644
--- a/spree/core/app/models/spree/promotion/rules/category.rb
+++ b/spree/core/app/models/spree/promotion/rules/category.rb
@@ -14,9 +14,7 @@ module Spree
dependent: :destroy
has_many :categories, through: :promotion_rule_categories, class_name: 'Spree::Category', source: :category
- def self.additional_permitted_attributes
- [category_ids: []]
- end
+ self.additional_permitted_attributes = [category_ids: []]
# Wire-format shorthand is `category`. `key` (instance) cascades through `api_type`.
def self.api_type
diff --git a/spree/core/app/models/spree/promotion/rules/product.rb b/spree/core/app/models/spree/promotion/rules/product.rb
index e6e6cea47a..b54915dcff 100644
--- a/spree/core/app/models/spree/promotion/rules/product.rb
+++ b/spree/core/app/models/spree/promotion/rules/product.rb
@@ -13,9 +13,7 @@ module Spree
dependent: :destroy
has_many :products, through: :product_promotion_rules, class_name: 'Spree::Product'
- def self.additional_permitted_attributes
- [product_ids: []]
- end
+ self.additional_permitted_attributes = [product_ids: []]
#
# Preferences
diff --git a/spree/core/app/models/spree/promotion/rules/user.rb b/spree/core/app/models/spree/promotion/rules/user.rb
index 9efe6d03f9..3b66516c48 100644
--- a/spree/core/app/models/spree/promotion/rules/user.rb
+++ b/spree/core/app/models/spree/promotion/rules/user.rb
@@ -13,9 +13,7 @@ module Spree
# Customers, not admin users — the rule keys off `Spree::Order#customer_id`.
# The data layer keeps the `users` association name (deferred model rename);
# the API exposes the same set as `customer_ids`.
- def self.additional_permitted_attributes
- [customer_ids: []]
- end
+ self.additional_permitted_attributes = [customer_ids: []]
# Wire-format shorthand is `customer` (the model is still `User`
# pre-6.0 rename, see docs/plans/6.0-platform-auth.md).
diff --git a/spree/core/app/models/spree/promotion_action.rb b/spree/core/app/models/spree/promotion_action.rb
index 8bd26444c0..4b72fc7cf7 100644
--- a/spree/core/app/models/spree/promotion_action.rb
+++ b/spree/core/app/models/spree/promotion_action.rb
@@ -14,15 +14,6 @@ module Spree
scope :of_type, ->(t) { where(type: t) }
- # Per-subclass permitted attributes beyond `type` and `preferences`.
- # Override in STI subclasses that accept nested attributes (e.g.
- # CreateLineItems needs `promotion_action_line_items_attributes`,
- # CreateAdjustment needs `calculator_type` + `calculator_attributes`).
- # The Admin API merges these into its `params.permit(...)` allowlist.
- def self.additional_permitted_attributes
- []
- end
-
# This method should be overridden in subclass
# Updates the state of the order or performs some other action depending on the subclass
# options will contain the payload from the event that activated the promotion. This will include
diff --git a/spree/core/app/models/spree/promotion_rule.rb b/spree/core/app/models/spree/promotion_rule.rb
index b61bf7daa8..02600fec21 100644
--- a/spree/core/app/models/spree/promotion_rule.rb
+++ b/spree/core/app/models/spree/promotion_rule.rb
@@ -14,14 +14,6 @@ module Spree
validates :promotion, presence: true
validates :type, uniqueness: { scope: [:promotion_id, *spree_base_uniqueness_scope] }
- # Per-subclass permitted attributes beyond `type` and `preferences`.
- # Override in STI subclasses that accept association IDs (e.g.
- # Rules::Product needs `product_ids`). The Admin API merges these
- # into its `params.permit(...)` allowlist.
- def self.additional_permitted_attributes
- []
- end
-
def self.for(promotable)
all.select { |rule| rule.applicable?(promotable) }
end
diff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rb
index c5ec213493..b9ca406c70 100644
--- a/spree/core/app/workflows/spree/carts/add_item.rb
+++ b/spree/core/app/workflows/spree/carts/add_item.rb
@@ -1,6 +1,9 @@
module Spree
module Carts
class AddItem < Spree::Workflow
+ # Line item attributes a caller may set through `options`.
+ ITEM_OPTIONS = [:id, :variant_id, :quantity].freeze
+
hooks :validate, :after_item_added
# Hook handlers read these plus the argument readers. Both are nil
@@ -45,9 +48,15 @@ module Spree
@line_item_created = @line_item.nil?
if @line_item.nil?
- opts = ::Spree::PermittedAttributes.line_item_attributes.flatten.each_with_object({}) do |attribute, result|
- result[attribute] = item_options[attribute]
- end.merge(currency: cart.currency).delete_if { |_key, value| value.nil? }
+ # `LineItem#options=` mass-assigns, so the caller's hash is narrowed
+ # first — `options` must not be a way to set arbitrary attributes.
+ # Extensions widen this through the model's permitted attributes.
+ writable = ITEM_OPTIONS +
+ ::Spree::LineItem.additional_permitted_attributes.flat_map { |a| a.is_a?(Hash) ? a.keys : a }
+
+ opts = item_options.symbolize_keys.slice(*writable).
+ merge(currency: cart.currency).
+ delete_if { |_key, value| value.nil? }
@line_item = cart.line_items.new(quantity: requested_quantity,
variant: variant,
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 2a19e9abbb..fe73db5cd7 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -726,7 +726,6 @@ require 'spree/iso_data'
require 'spree/localized_number'
require 'spree/translations'
require 'spree/money'
-require 'spree/permitted_attributes'
require 'spree/service_module'
require 'spree/workflow'
require 'spree/analytics'
@@ -734,7 +733,6 @@ require 'spree/events'
require 'spree/store_scope_guard'
require 'spree/core/controller_helpers/store'
-require 'spree/core/controller_helpers/strong_parameters'
require 'spree/core/preferences/store'
require 'spree/core/preferences/scoped_store'
diff --git a/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb b/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb
deleted file mode 100644
index b0763a25b0..0000000000
--- a/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb
+++ /dev/null
@@ -1,47 +0,0 @@
-module Spree
- module Core
- module ControllerHelpers
- module StrongParameters
- def permitted_attributes
- Spree::PermittedAttributes
- end
-
- delegate *Spree::PermittedAttributes::ATTRIBUTES,
- to: :permitted_attributes,
- prefix: :permitted
-
- def permitted_payment_attributes
- permitted_attributes.payment_attributes + [
- source_attributes: permitted_source_attributes
- ]
- end
-
- def permitted_checkout_attributes
- permitted_attributes.checkout_attributes + [
- bill_address_attributes: permitted_address_attributes,
- ship_address_attributes: permitted_address_attributes,
- payments_attributes: permitted_payment_attributes,
- shipments_attributes: permitted_shipment_attributes
- ]
- end
-
- def permitted_order_attributes
- permitted_checkout_attributes + [
- line_items_attributes: permitted_line_item_attributes
- ]
- end
-
- def permitted_product_attributes
- permitted_attributes.product_attributes + [
- removed_variant_ids: [],
- variants_attributes: permitted_variant_attributes + ['id', :_destroy]
- ]
- end
-
- def permitted_store_attributes
- permitted_attributes.store_attributes
- end
- end
- end
- end
-end
diff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rb
deleted file mode 100644
index 1ab4ae7ff9..0000000000
--- a/spree/core/lib/spree/permitted_attributes.rb
+++ /dev/null
@@ -1,309 +0,0 @@
-module Spree
- module PermittedAttributes
- ATTRIBUTES = [
- :address_attributes,
- :allowed_origin_attributes,
- :api_key_attributes,
- :asset_attributes,
- :category_attributes,
- :checkout_attributes,
- :classification_attributes,
- :cms_page_attributes,
- :cms_section_attributes,
- :custom_domain_attributes,
- :customer_group_attributes,
- :digital_attributes,
- :digital_link_attributes,
- :export_attributes,
- :gift_card_attributes,
- :gift_card_batch_attributes,
- :image_attributes,
- :import_attributes,
- :import_mapping_attributes,
- :integration_attributes,
- :inventory_unit_attributes,
- :invitation_attributes,
- :line_item_attributes,
- :market_attributes,
- :menu_attributes,
- :menu_item_attributes,
- :custom_field_attributes,
- :custom_field_definition_attributes,
- :option_type_attributes,
- :option_value_attributes,
- :page_attributes,
- :page_block_attributes,
- :page_link_attributes,
- :page_section_attributes,
- :payment_attributes,
- :payment_method_attributes,
- :payment_session_attributes,
- :payment_setup_session_attributes,
- :policy_attributes,
- :price_list_attributes,
- :product_attributes,
- :promotion_attributes,
- :promotion_rule_attributes,
- :promotion_action_attributes,
- :refund_attributes,
- :refund_reason_attributes,
- :report_attributes,
- :return_reason_attributes,
- :claim_reason_attributes,
- :role_attributes,
- :shipment_attributes,
- :shipping_method_attributes,
- :channel_attributes,
- :source_attributes,
- :stock_level_attributes,
- :stock_location_attributes,
- :stock_movement_attributes,
- :stock_transfer_attributes,
- :store_attributes,
- :store_credit_attributes,
- :tax_rate_attributes,
- :tax_category_attributes,
- :theme_attributes,
- :user_attributes,
- :variant_attributes,
- :webhook_endpoint_attributes,
- :wishlist_attributes,
- :wished_item_attributes,
- :zone_attributes
- ]
-
- mattr_reader(*ATTRIBUTES)
-
- @@address_attributes = [
- :id, :firstname, :lastname, :first_name, :last_name,
- # state_abbr is the deprecated write name (see Spree::Address); 6.1 drops it.
- :address1, :address2, :city, :country_code, :state_code, :state_abbr,
- :zipcode, :phone, :state_name, :alternative_phone, :company,
- :user_id, :deleted_at, :label, :quick_checkout
- ]
-
- @@allowed_origin_attributes = [:origin]
-
- @@api_key_attributes = [:name, :key_type, :channel_id, { scopes: [] }]
-
- @@asset_attributes = [:type, :viewable_id, :viewable_type, :attachment, :alt, :position, :url, :signed_id]
-
- @@checkout_attributes = [
- :coupon_code, :email, :shipping_method_id, :special_instructions, :use_billing, :use_shipping,
- :user_id, :bill_address_id, :ship_address_id, :accept_marketing, :signup_for_an_account, :currency, :locale,
- :internal_note
- ]
-
- @@classification_attributes = [
- :position, :category_id, :product_id
- ]
-
- @@cms_page_attributes = [:title, :meta_title, :content, :meta_description, :visible, :slug, :locale]
-
- @@cms_section_attributes = [:name, :cms_page_id, :fit, :destination, { content: {}, settings: {} }]
-
- @@custom_domain_attributes = [:url, :default]
-
- @@customer_group_attributes = [:name, :description]
-
- @@digital_attributes = [:attachment, :variant_id]
-
- @@digital_link_attributes = [:access_counter]
-
- @@export_attributes = [:type, :format, :record_selection, :search_params]
-
- @@gift_card_attributes = [:code, :amount, :expires_at, :user_id, :currency]
-
- @@gift_card_batch_attributes = [:prefix, :codes_count, :amount, :expires_at, :currency]
-
- @@image_attributes = [:alt, :attachment, :position, :viewable_type, :viewable_id]
-
- @@import_attributes = [:type, :attachment, :delimiter]
-
- @@import_mapping_attributes = [:file_column]
-
- @@integration_attributes = [:type, :active]
-
- @@inventory_unit_attributes = [:shipment, :shipment_id, :variant_id]
-
- @@invitation_attributes = [:email, :expires_at, :role_id]
-
- @@line_item_attributes = [:id, :variant_id, :quantity, { metadata: {} }]
-
- @@market_attributes = [:name, :currency, :default_locale, :supported_locales,
- :tax_inclusive, :default, :position, country_ids: []]
-
- @@menu_attributes = [:name, :locale, :location]
-
- @@menu_item_attributes = [:name, :subtitle, :destination, :new_window, :item_type,
- :linked_resource_type, :linked_resource_id, :code, :menu_id]
-
- @@custom_field_attributes = [:id, :value, :type, :custom_field_definition_id, :_destroy]
-
- @@custom_field_definition_attributes = [
- :key, :label, :namespace, :field_type, :resource_type, :storefront_visible,
- :searchable, :sortable
- ]
-
-
- @@option_type_attributes = [:name, :presentation, :position, :filterable, :kind,
- option_values_attributes: [:id, :name, :presentation, :position, :color_code, :image, :_destroy]]
-
- @@option_value_attributes = [:name, :presentation, :position, :color_code, :image]
-
- @@page_attributes = [:name, :slug, :meta_title, :meta_description, :meta_keywords]
-
- @@page_block_attributes = [:type, :name, :text, :position, :asset]
-
- @@page_link_attributes = [:linkable_id, :linkable_type, :position, :label, :url, :open_in_new_tab]
-
- @@page_section_attributes = [:type, :name, :position, :asset, :text, :description]
-
- @@payment_attributes = [:amount, :payment_method_id, :payment_method]
-
- @@payment_method_attributes = [:name, :type, :description, :active, :display_on, :auto_capture, :capture_method, :position, { metadata: {}, preferences: {} }]
-
- @@payment_session_attributes = [:amount, :payment_method_id, { external_data: {} }]
-
- @@payment_setup_session_attributes = [:payment_method_id, { external_data: {} }]
-
- @@policy_attributes = [:name, :slug, :body]
-
- @@price_list_attributes = [:name, :description, :match_policy, :starts_at, :ends_at, :status, :position]
-
- @@product_attributes = [
- :name, :description, :available_on, :make_active_at, :discontinue_on, :permalink, :meta_description,
- :meta_keywords, :meta_title, :sku, :deleted_at,
- :weight, :height, :width, :depth,
- :product_type_id, :tax_category_id,
- :cost_currency, :cost_price,
- :slug, :track_inventory, :backorderable, :barcode, :status,
- :weight_unit, :dimensions_unit,
- {
- tag_list: [],
- label_list: [],
- option_type_ids: [],
- taxon_ids: [],
- product_option_types_attributes: [:id, :option_type_id, :position, :_destroy],
- legacy_product_publications_attributes: [:id, :channel_id, :published_at, :unpublished_at, :_destroy]
- }
- ]
-
- @@promotion_attributes = [:name, :description, :starts_at, :expires_at, :code, :usage_limit, :path, :match_policy,
- :advertise, :promotion_category_id, :code_prefix, :kind, :number_of_codes, :multi_codes]
-
- @@promotion_rule_attributes = [:type, :preferred_match_policy, preferred_eligible_values: [], user_ids_to_add: [], product_ids_to_add: [], taxon_ids_to_add: []]
-
- @@promotion_action_attributes = [:type, :calculator_type, calculator_attributes: {}, promotion_action_line_items_attributes: [:id, :promotion_action_id, :variant_id, :quantity, :_destroy]]
-
- @@refund_attributes = [:amount, :refund_reason_id]
-
- @@refund_reason_attributes = [:name, :active]
-
- @@report_attributes = [:type, :date_from, :date_to, :currency]
-
- @@return_reason_attributes = [:name, :active]
-
- @@claim_reason_attributes = [:name, :active]
-
- @@role_attributes = [:name]
-
- @@shipment_attributes = [
- :order, :special_instructions, :stock_location_id, :id,
- :tracking, :address, :inventory_units, :selected_shipping_rate_id
- ]
-
- @@channel_attributes = [:name, :code, :active, :default, :preferred_order_routing_strategy,
- :preferred_storefront_access, :preferred_guest_checkout]
-
- @@shipping_method_attributes = [:name, :admin_name, :code, :tracking_url, :tax_category_id, :storefront_visible,
- :fulfillment_provider, :delivery_profile_id, :delivery_zone_id,
- :estimated_transit_business_days_min, :estimated_transit_business_days_max,
- :calculator_type, :preferences, calculator_attributes: {}]
-
- # month / year may be provided by some sources, or others may elect to use one field
- @@source_attributes = [
- :id, :number, :month, :year, :expiry, :verification_value,
- :first_name, :last_name, :cc_type, :gateway_customer_profile_id,
- :gateway_payment_profile_id, :last_digits, :name, :encrypted_data
- ]
-
- @@stock_level_attributes = [:variant_id, :stock_location_id, :backorderable, :count_on_hand, { metadata: {} }]
-
- @@stock_location_attributes = [
- :name, :admin_name, :active, :address1, :address2, :city, :zipcode, :company,
- :backorderable_default, :state_name, :state_id, :country_id, :phone,
- :propagate_all_variants
- ]
-
- @@stock_movement_attributes = [
- :quantity, :kind, :reason, :stock_level, :stock_level_id,
- :order_id, :fulfillment_id, :return_id, :exchange_id, :stock_transfer_id
- ]
-
- @@stock_transfer_attributes = [:source_location_id, :destination_location_id, :reference,
- stock_movements_attributes: [:variant_id, :quantity, :kind, :stock_level_id]]
-
- @@store_attributes = [:name, :url, :seo_title, :code, :meta_keywords,
- :meta_description, :default_currency, :default_country_code, :mail_from_address,
- :customer_support_email, :description, :address, :contact_phone,
- :supported_locales, :default_locale, :supported_currencies,
- :new_order_notifications_email,
- :preferred_admin_locale, :preferred_timezone, :preferred_weight_unit, :preferred_unit_system,
- :preferred_digital_asset_authorized_clicks, :preferred_digital_asset_authorized_days,
- :preferred_limit_digital_download_count, :preferred_limit_digital_download_days,
- :preferred_digital_asset_link_expire_time,
- :logo, :mailer_logo,
- :preferred_guest_checkout, :preferred_storefront_access]
-
- @@store_credit_attributes = %i[amount currency memo]
-
- @@tax_category_attributes = [:name, :tax_code,:description, :is_default]
-
- @@tax_rate_attributes = [:name, :amount, :amount_percentage, :zone_id, :tax_category_id, :included_in_price, :show_rate_in_label, :calculator_type, calculator_attributes: {}]
-
- @@category_attributes = [
- :name, :parent_id, :position, :icon, :description, :permalink,
- :meta_description, :meta_keywords, :meta_title, :child_index,
- :image, :square_image
- ]
-
- @@theme_attributes = [:name, :type, :default]
-
- @@user_attributes = [:email, :bill_address_id, :ship_address_id, :password, :first_name, :last_name,
- :password_confirmation, :selected_locale, :avatar, :accepts_email_marketing, :phone,
- :internal_note,
- { metadata: {}, tag_list: [], customer_group_ids: [] }]
-
- @@variant_attributes = [
- :name, :presentation, :cost_price, :discontinue_on, :lock_version,
- :position, :track_inventory, :preorderable, :preorder_ships_at, :backorder_limit, :tax_category_id,
- :product_id, :product, :option_values_attributes,
- :seller_id, :delivery_profile_id,
- :weight, :height, :width, :depth, :sku, :barcode, :cost_currency,
- :weight_unit, :dimensions_unit,
- :hs_code, :country_of_origin, :customs_description,
- {
- options: [:id, :name, :option_value_presentation, :option_value_name, :position, :_destroy],
- stock_levels_attributes: [:id, :count_on_hand, :stock_location_id, :backorderable, :_destroy],
- prices_attributes: [:id, :amount, :compare_at_amount, :currency, :_destroy],
- option_value_variants_attributes: [:id, :option_value_id, :_destroy],
- option_value_ids: []
- }
- ]
-
- @@webhook_endpoint_attributes = [:name, :url, :secret, :active, subscriptions: []]
-
- @@wishlist_attributes = [:name, :is_default, :is_private]
-
- @@wished_item_attributes = [:variant_id, :quantity]
-
- @@zone_attributes = [:name, :description, :default_tax, :kind, :states_country_id, country_ids: [], state_ids: []]
-
- # @deprecated Renamed to .category_attributes in 6.0; removed in 6.1.
- def self.taxon_attributes
- Spree::Deprecation.warn('Spree::PermittedAttributes.taxon_attributes is deprecated and will be removed in Spree 6.1. Use .category_attributes instead.')
- category_attributes
- end
- end
-end
diff --git a/spree/core/spec/lib/spree/core/controller_helpers/strong_parameters_spec.rb b/spree/core/spec/lib/spree/core/controller_helpers/strong_parameters_spec.rb
deleted file mode 100644
index 627a6bdf06..0000000000
--- a/spree/core/spec/lib/spree/core/controller_helpers/strong_parameters_spec.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-require 'spec_helper'
-
-class FakesController < ApplicationController
- include Spree::Core::ControllerHelpers::StrongParameters
-end
-
-describe Spree::Core::ControllerHelpers::StrongParameters, type: :controller do
- controller(FakesController) {}
-
- describe '#permitted_attributes' do
- it 'returns Spree::PermittedAttributes module' do
- expect(controller.permitted_attributes).to eq Spree::PermittedAttributes
- end
- end
-
- describe '#permitted_payment_attributes' do
- it 'returns Array class' do
- expect(controller.permitted_payment_attributes.class).to eq Array
- end
- end
-
- describe '#permitted_checkout_attributes' do
- it 'returns Array class' do
- expect(controller.permitted_checkout_attributes.class).to eq Array
- end
- end
-
- describe '#permitted_order_attributes' do
- it 'returns Array class' do
- expect(controller.permitted_order_attributes.class).to eq Array
- end
- end
-
- describe '#permitted_product_attributes' do
- it 'returns Array class' do
- expect(controller.permitted_product_attributes.class).to eq Array
- end
- end
-
- describe '#permitted_store_attributes' do
- it 'returns Array class' do
- expect(controller.permitted_store_attributes.class).to eq Array
- end
- end
-
-end
diff --git a/spree/core/spec/models/spree/base_spec.rb b/spree/core/spec/models/spree/base_spec.rb
index 769e11d848..0b46e9a142 100644
--- a/spree/core/spec/models/spree/base_spec.rb
+++ b/spree/core/spec/models/spree/base_spec.rb
@@ -107,6 +107,48 @@ describe Spree::Base do
it { expect(Spree::Address.json_api_permitted_attributes).to contain_exactly('firstname', 'lastname', 'address1', 'address2', 'city', 'zipcode', 'phone', 'country_code', 'state_code', 'state_name', 'alternative_phone', 'company', 'country_id', 'state_id', 'created_at', 'updated_at', 'customer_id', 'deleted_at', 'label', 'metadata', 'quick_checkout', 'latitude', 'longitude') }
end
+ describe '.additional_permitted_attributes' do
+ it 'defaults to an empty list' do
+ expect(Spree::Product.additional_permitted_attributes).to eq([])
+ end
+
+ it 'is inherited by the STI rule base classes that used to define their own' do
+ expect(Spree::PromotionRule.additional_permitted_attributes).to eq([])
+ expect(Spree::PromotionAction.additional_permitted_attributes).to eq([])
+ expect(Spree::DeliveryMethodRule.additional_permitted_attributes).to eq([])
+ expect(Spree::CommissionRule.additional_permitted_attributes).to eq([])
+ end
+
+ it 'lets a subclass declare its own without affecting siblings' do
+ expect(Spree::Promotion::Rules::Product.additional_permitted_attributes).to eq([product_ids: []])
+ expect(Spree::PromotionRule.additional_permitted_attributes).to eq([])
+ end
+
+ # The documented extension contract: append from an initializer.
+ context 'when an extension appends to it' do
+ around do |example|
+ original = Spree::Product.additional_permitted_attributes
+ example.run
+ Spree::Product.additional_permitted_attributes = original
+ end
+
+ it 'adds the attribute without touching other models' do
+ Spree::Product.additional_permitted_attributes += [:brand_id]
+
+ expect(Spree::Product.additional_permitted_attributes).to eq([:brand_id])
+ expect(Spree::Variant.additional_permitted_attributes).to eq([])
+ expect(Spree::Base.additional_permitted_attributes).to eq([])
+ end
+
+ it 'accumulates across extensions rather than replacing' do
+ Spree::Product.additional_permitted_attributes += [:brand_id]
+ Spree::Product.additional_permitted_attributes += [{ region_ids: [] }]
+
+ expect(Spree::Product.additional_permitted_attributes).to eq([:brand_id, { region_ids: [] }])
+ end
+ end
+ end
+
describe 'preference defaults on load' do
let(:store) { Spree::Store.default }