Skip to content

Commit

Permalink
Verify JWT header format
Browse files Browse the repository at this point in the history
**Problem**

JWT header is expected to be a hash. However, it's possible to generate
a token that defines header as an Array `[]`. This case is not handled
by the application and leads to `TypeError: no implicit conversion of
String into Integer`.

**Solution**

Add a verification for an header type before accessing hash elements.
  • Loading branch information
304 committed Sep 30, 2024
1 parent a40f8d7 commit abd8816
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
**Fixes and enhancements:**

- Updated README to correctly document `OpenSSL::HMAC` documentation [#617](https://github.com/jwt/ruby-jwt/pull/617) ([@aedryan](https://github.com/aedryan))
- Verify JWT header format [#622](https://github.com/jwt/ruby-jwt/pull/622) ([@304](https://github.com/304))
- Your contribution here

## [v2.9.1](https://github.com/jwt/ruby-jwt/tree/v2.9.1) (2024-09-23)
Expand Down
2 changes: 1 addition & 1 deletion lib/jwt/decode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def decode_signature
end

def alg_in_header
header['alg']
header.is_a?(Hash) && header['alg']
end

def header
Expand Down
9 changes: 9 additions & 0 deletions spec/jwt/jwt_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
data = {
:empty_token => 'e30K.e30K.e30K',
:empty_token_2_segment => 'e30K.e30K.',
:invalid_header_token => 'W10.e30K.e30K',
:secret => 'My$ecretK3y',
:rsa_private => test_pkey('rsa-2048-private.pem'),
:rsa_public => test_pkey('rsa-2048-public.pem'),
Expand Down Expand Up @@ -520,6 +521,14 @@
end.to raise_error JWT::IncorrectAlgorithm
end

context 'invalid header format' do
it 'should raise JWT::IncorrectAlgorithm' do
expect do
JWT.decode data[:invalid_header_token]
end.to raise_error JWT::IncorrectAlgorithm
end
end

context '2-segment token' do
it 'should raise JWT::IncorrectAlgorithm' do
expect do
Expand Down

0 comments on commit abd8816

Please sign in to comment.