ActiveRecord 모델의 우발적 직렬화 방지

ActiveRecord 모델을 직렬화할 때 직렬화할 필드를 명시하지 않는 경우의 우발적 직렬화를 방지하기 위한 패치를 도입했습니다. 이 변경 사항은 포함할 필드를 우리가 제어할 수 있도록 하여, 불완전하거나 과도한 데이터가 노출될 수 있는 잠재적 문제를 방지합니다.

기본적으로 ActiveRecord 모델을 JSON으로 렌더링하면 모든 속성이 포함되지만, 많은 경우 이는 바람직하지 않을 수 있습니다. 더 나은 관행을 강제하기 위해 직렬화해야 할 필드를 명시해야 합니다.

사용 예시

잘못된 사용법:

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

개발 및 테스트 환경에서 이 경우 다음과 같은 결과가 발생합니다:

ActiveRecordSerializationSafety::BlockedSerializationError:
필드를 지정하지 않고 ActiveRecord 모델(User)을 직렬화하는 것은 허용되지 않습니다.
Serializer를 사용하거나 #serializable_hash에 :only 옵션을 전달하세요. 자세한 정보: https://meta.discourse.org/t/-/314495
./lib/freedom_patches/active_record_disable_serialization.rb:15:in `serializable_hash'

올바른 사용법:

  1. Serializer 사용
class UserSerializer < ApplicationSerializer
  attributes :id, :email
end

def show
  @user = User.first
  render json: @user, serializer: UserSerializer
end
  1. :only 옵션 사용
def show
  @user = User.first
  render json: @user.as_json(only: [:id, :email])
end

이 문서는 버전 관리됩니다 - 변경 사항을 github에서 제안하세요.

6개의 좋아요

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

For an example see:

https://github.com/paviliondev/discourse-custom-wizard/commit/247a3d551cdfcacacded7ca5640e4df1d084d07d

5개의 좋아요

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개의 좋아요