Preventing accidental serialization of ActiveRecord models

We’ve introduced a patch to prevent the accidental serialization of ActiveRecord models without specifying the fields to be serialized. This change ensures that we control which fields are included, avoiding potential issues with incomplete or excessive data being exposed.

By default, rendering an ActiveRecord model as JSON includes all attributes, which may not be desirable in many cases. To enforce better practices, we need to specify which fields should be serialized.

Usage Examples

Incorrect Usage:

def show
  @user = User.first
  render json: @user
end

In development and tests, this will result in:

ActiveRecordSerializationSafety::BlockedSerializationError:
Serializing ActiveRecord models (User) without specifying fields is not allowed.
Use a Serializer, or pass the :only option to #serializable_hash. More info: https://meta.discourse.org/t/-/314495    
./lib/freedom_patches/active_record_disable_serialization.rb:15:in `serializable_hash'

Correct Usage:

  1. Using a Serializer
class UserSerializer < ApplicationSerializer
  attributes :id, :email
end

def show
  @user = User.first
  render json: @user, serializer: UserSerializer
end
  1. Using the :only option
def show
  @user = User.first
  render json: @user.as_json(only: [:id, :email])
end

This document is version controlled - suggest changes on github.

Last edited by @JammyDodger 2024-07-17T18:16:40Z

Check documentPerform check on document:
6 Likes

Just to clarify for those that may encounter this in the wild, this means that all uses of the serialization methods in ActiveModel::Serialization, e.g. as_json, regardless of context (including in specs), will result in an error unless you pass the only option. See further

https://apidock.com/rails/ActiveModel/Serializers/JSON/as_json

For an example see:

5 Likes

A post was split to a new topic: Help with new serialization protectionsd

Well, it took 21 days, but I finally made sense of what you said here in your linked code, in at least one context, and hopefully the other one mentioned in the split topic mentioned above. That one seems harder (by my memory, anyway) since I don’t quite know just where the problem is.

Thanks for saving the day (or at least this day). :beers:

The other issue was that my server model included the user model and I needed to be calling the user serializer (or limiting fields) of the user model in my server serializer.

It turned out that I didn’t need any of the user model in my server model (user_id_was already there,and there’s a reasonable chance I don’t really even need that)

1 Like