Skip to content

Commit

Permalink
Support UTF-8 data when using the JSON serializer
Browse files Browse the repository at this point in the history
Closes #38
  • Loading branch information
jcmfernandes committed Feb 13, 2024
1 parent c84d5de commit 218d5e0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/rack/session/encryptor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ module Serializable
def serialize_payload(message)
serialized_data = serializer.dump(message)

return "#{[0].pack('v')}#{serialized_data}" if @options[:pad_size].nil?
return "#{[0].pack('v')}#{serialized_data.force_encoding('BINARY')}" if @options[:pad_size].nil?

padding_bytes = @options[:pad_size] - (2 + serialized_data.size) % @options[:pad_size]
padding_data = SecureRandom.random_bytes(padding_bytes)

"#{[padding_bytes].pack('v')}#{padding_data}#{serialized_data}"
"#{[padding_bytes].pack('v')}#{padding_data}#{serialized_data.force_encoding('BINARY')}"
end

# Return the deserialized message. The first 2 bytes will be read as the
Expand Down
12 changes: 12 additions & 0 deletions test/spec_session_encryptor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ def self.included(_base)
encryptor.decrypt(message).must_equal({ 'foo' => 'bar' })
end

# The V1 encryptor defaults to the Marshal serializer, while the V2
# encryptor always uses the JSON serializer. This means that we are
# indirectly covering both serializers.
it 'decrypts an encrypted message with UTF-8 data' do
encryptor = encryptor_class.new(@secret)

encrypted_message = encryptor.encrypt({ 'foo' => '😀' })
decrypted_message = encryptor.decrypt(encrypted_message)

decrypted_message.must_equal({ 'foo' => '😀' })
end

it 'decrypts raises InvalidSignature without purpose' do
encryptor = encryptor_class.new(@secret, purpose: 'testing')
other_encryptor = encryptor_class.new(@secret)
Expand Down

0 comments on commit 218d5e0

Please sign in to comment.