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.

15.4 KB
Raw Blame

Drop Spree::PermittedAttributes, add a model-level extension hook

Status: Implemented 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:

# 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:

# 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.

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:

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