Skip to content

Commit

Permalink
Make sure the message format doesn't change
Browse files Browse the repository at this point in the history
When `use_message_serializer_for_metadata` is false, the message
format should be enveloped in the same way it was in Rails 7.0
to make sure we don't have inconsistent formats.
  • Loading branch information
rafaelfranca committed Sep 1, 2023
1 parent ed873f1 commit fea9ad3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
9 changes: 8 additions & 1 deletion activesupport/lib/active_support/messages/metadata.rb
Expand Up @@ -32,7 +32,7 @@ def serialize_with_metadata(data, **metadata)

if has_metadata && !use_message_serializer_for_metadata?
data_string = serialize_to_json_safe_string(data)
envelope = wrap_in_metadata_envelope({ "message" => data_string }, **metadata)
envelope = wrap_in_metadata_legacy_envelope({ "message" => data_string }, **metadata)
serialize_to_json(envelope)
else
data = wrap_in_metadata_envelope({ "data" => data }, **metadata) if has_metadata
Expand Down Expand Up @@ -68,6 +68,13 @@ def wrap_in_metadata_envelope(hash, expires_at: nil, expires_in: nil, purpose: n
{ "_rails" => hash }
end

def wrap_in_metadata_legacy_envelope(hash, expires_at: nil, expires_in: nil, purpose: nil)
expiry = pick_expiry(expires_at, expires_in)
hash["exp"] = expiry
hash["pur"] = purpose
{ "_rails" => hash }
end

def extract_from_metadata_envelope(envelope, purpose: nil)
hash = envelope["_rails"]

Expand Down
14 changes: 14 additions & 0 deletions activesupport/test/messages/message_verifier_metadata_test.rb
Expand Up @@ -86,6 +86,20 @@ class MessageVerifierMetadataTest < ActiveSupport::TestCase
end
end

test "messages keep the old format when use_message_serializer_for_metadata is false" do
# Message generated by Rails 7.0 using:
#
# verifier = ActiveSupport::MessageVerifier.new("secret", serializer: JSON)
# legacy_message = verifier.generate("legacy", purpose: "test")
legacy_message = "eyJfcmFpbHMiOnsibWVzc2FnZSI6IklteGxaMkZqZVNJPSIsImV4cCI6bnVsbCwicHVyIjoidGVzdCJ9fQ==--53b1fc02f5b89b2da8c6ce94efa95f5cb656d975"

verifier = ActiveSupport::MessageVerifier.new("secret", serializer: JSON)

using_message_serializer_for_metadata(false) do
assert_equal legacy_message, verifier.generate("legacy", purpose: "test")
end
end

private
def make_codec(**options)
ActiveSupport::MessageVerifier.new("secret", **options)
Expand Down

0 comments on commit fea9ad3

Please sign in to comment.