Skip to content

Commit

Permalink
Remove Ruby <2.3 base64 decoding workaround
Browse files Browse the repository at this point in the history
In older Ruby versions, WebPush.decode64 was introduced to wrap
Base64.urlsafe_decode64 to prevent errors decoding "unpadded"
urlsafe-encoded input. Since Ruby 2.3, Base64.urlsafe_decode64 can now
gracefully decode padded and unpadded input. Given WebPush now supports
Ruby 3+, we should be able to remove this workaround gracefully. I've
added basic specs to demonstrate and perhaps catch any potential (though
unlikely) future regressions in Ruby.

For historical discussion of the issue:
https://bugs.ruby-lang.org/issues/10740
  • Loading branch information
rossta committed Jan 21, 2024
1 parent 736de6d commit 36574af
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
4 changes: 0 additions & 4 deletions lib/web_push.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,6 @@ def encode64(bytes)
end

def decode64(str)
# For Ruby < 2.3, Base64.urlsafe_decode64 strict decodes and will raise errors if encoded value is not properly padded
# Implementation: http://ruby-doc.org/stdlib-2.3.0/libdoc/base64/rdoc/Base64.html#method-i-urlsafe_decode64
str = str.ljust((str.length + 3) & ~3, '=') if !str.end_with?('=') && str.length % 4 != 0

Base64.urlsafe_decode64(str)
end

Expand Down
12 changes: 12 additions & 0 deletions spec/web_push_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@
expect(WebPush::VERSION).not_to be nil
end

describe '.decode64' do
let(:a_padded_key) { "YWJjZGU=" }

it 'urlsafe decodes padded base64 string' do
expect(WebPush.decode64(a_padded_key)).to eq("abcde")
end

it 'urlsafe decodes unpadded base64 string' do
expect(WebPush.decode64(a_padded_key.delete("="))).to eq("abcde")
end
end

shared_examples 'web push protocol standard error handling' do
it 'raises InvalidSubscription if the API returns a 404 Error' do
stub_request(:post, expected_endpoint)
Expand Down

0 comments on commit 36574af

Please sign in to comment.