Skip to content

Commit

Permalink
Merge pull request #292 from anakinj/segment-handling-bug
Browse files Browse the repository at this point in the history
Fix bug and simplify segment validation
  • Loading branch information
excpt authored Jan 21, 2019
2 parents 0ad5436 + de41517 commit 73ba6a0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lib/jwt/decode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def initialize(jwt, key, verify, options, &keyfinder)
end

def decode_segments
validate_segment_count
validate_segment_count!
if @verify
decode_crypto
verify_signature
Expand Down Expand Up @@ -64,10 +64,11 @@ def verify_claims
Verify.verify_claims(payload, @options)
end

def validate_segment_count
raise(JWT::DecodeError, 'Not enough or too many segments') unless
(@verify && segment_length != 3) ||
(segment_length != 3 || segment_length != 2)
def validate_segment_count!
return if segment_length == 3
return if !@verify && segment_length == 2 # If no verifying required, the signature is not needed

raise(JWT::DecodeError, 'Not enough or too many segments')
end

def segment_length
Expand Down
25 changes: 25 additions & 0 deletions spec/jwt_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@
end
end
end

%w[ES256 ES384 ES512].each do |alg|
context "alg: #{alg}" do
before(:each) do
Expand Down Expand Up @@ -348,6 +349,30 @@
end
end

context 'a token with no segments' do
it 'raises JWT::DecodeError' do
expect { JWT.decode('ThisIsNotAValidJWTToken', nil, true) }.to raise_error(JWT::DecodeError, 'Not enough or too many segments')
end
end

context 'a token with not enough segments' do
it 'raises JWT::DecodeError' do
expect { JWT.decode('ThisIsNotAValidJWTToken.second', nil, true) }.to raise_error(JWT::DecodeError, 'Not enough or too many segments')
end
end

context 'a token with not too many segments' do
it 'raises JWT::DecodeError' do
expect { JWT.decode('ThisIsNotAValidJWTToken.second.third.signature', nil, true) }.to raise_error(JWT::DecodeError, 'Not enough or too many segments')
end
end

context 'a token with two segments but does not require verifying' do
it 'raises something else than "Not enough or too many segments"' do
expect { JWT.decode('ThisIsNotAValidJWTToken.second', nil, false) }.to raise_error(JWT::DecodeError, 'Invalid segment encoding')
end
end

context 'Base64' do
it 'urlsafe replace + / with - _' do
allow(Base64).to receive(:encode64) { 'string+with/non+url-safe/characters_' }
Expand Down

0 comments on commit 73ba6a0

Please sign in to comment.