From de41517f95e6790163b9bb6093233d4e7c90ce5b Mon Sep 17 00:00:00 2001 From: Joakim Antman Date: Fri, 18 Jan 2019 10:11:20 +0200 Subject: [PATCH] Fix bug and simplify segment validation --- lib/jwt/decode.rb | 11 ++++++----- spec/jwt_spec.rb | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/lib/jwt/decode.rb b/lib/jwt/decode.rb index c6a6f543..6d1bd991 100644 --- a/lib/jwt/decode.rb +++ b/lib/jwt/decode.rb @@ -25,7 +25,7 @@ def initialize(jwt, key, verify, options, &keyfinder) end def decode_segments - validate_segment_count + validate_segment_count! if @verify decode_crypto verify_signature @@ -69,10 +69,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 diff --git a/spec/jwt_spec.rb b/spec/jwt_spec.rb index 65085aff..f70dbb82 100644 --- a/spec/jwt_spec.rb +++ b/spec/jwt_spec.rb @@ -172,6 +172,7 @@ end end end + %w[ES256 ES384 ES512].each do |alg| context "alg: #{alg}" do before(:each) do @@ -336,6 +337,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_' }