From b006395d85f6f9a86b9df21a4dbcbda023e47431 Mon Sep 17 00:00:00 2001 From: Mike Ragalie Date: Thu, 12 Dec 2024 09:06:21 -0500 Subject: [PATCH] Handle empty string as token value If the token is the empty string we try to pass `nil` to `Base64.url_decode`, which always expects a string. This ensures we always pass a string to avoid an unexpected error. --- CHANGELOG.md | 1 + lib/jwt/encoded_token.rb | 2 +- spec/jwt/encoded_token_spec.rb | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 74ac03cb..a3f652e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ - Deprecation warnings for deprecated methods and classes [#629](https://github.com/jwt/ruby-jwt/pull/629) ([@anakinj](https://github.com/anakinj)) - Improved documentation for public apis [#629](https://github.com/jwt/ruby-jwt/pull/629) ([@anakinj](https://github.com/anakinj)) - Use correct methods when raising error during signing/verification with EdDSA [#633](https://github.com/jwt/ruby-jwt/pull/633) +- Fix JWT::EncodedToken behavior with empty string as token [#640](https://github.com/jwt/ruby-jwt/pull/640) ([@ragalie](https://github.com/ragalie)) - Your contribution here ## [v2.9.3](https://github.com/jwt/ruby-jwt/tree/v2.9.3) (2024-10-03) diff --git a/lib/jwt/encoded_token.rb b/lib/jwt/encoded_token.rb index c0ed8b2e..a7afdc62 100644 --- a/lib/jwt/encoded_token.rb +++ b/lib/jwt/encoded_token.rb @@ -124,7 +124,7 @@ def unencoded_payload? end def parse_and_decode(segment) - parse(::JWT::Base64.url_decode(segment)) + parse(::JWT::Base64.url_decode(segment || '')) end def parse_unencoded(segment) diff --git a/spec/jwt/encoded_token_spec.rb b/spec/jwt/encoded_token_spec.rb index 597c74f1..522fe270 100644 --- a/spec/jwt/encoded_token_spec.rb +++ b/spec/jwt/encoded_token_spec.rb @@ -40,10 +40,26 @@ expect(token.payload).to eq({ 'foo' => 'bar' }) end end + + context 'when token is the empty string' do + let(:encoded_token) { '' } + + it 'raises decode error' do + expect { token.payload }.to raise_error(JWT::DecodeError, 'Invalid segment encoding') + end + end end describe '#header' do it { expect(token.header).to eq({ 'alg' => 'HS256' }) } + + context 'when token is the empty string' do + let(:encoded_token) { '' } + + it 'raises decode error' do + expect { token.header }.to raise_error(JWT::DecodeError, 'Invalid segment encoding') + end + end end describe '#signature' do