From 5767e797fb96298fc78afa92546bf4bbc9003e23 Mon Sep 17 00:00:00 2001 From: Vasiliy Yakliushin Date: Mon, 30 Sep 2024 11:23:03 +0200 Subject: [PATCH] Verify JWT header format **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. --- CHANGELOG.md | 1 + lib/jwt/decode.rb | 1 + spec/jwt/jwt_spec.rb | 9 +++++++++ 3 files changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7238cb54..cf05db0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/lib/jwt/decode.rb b/lib/jwt/decode.rb index a8de603d..e51a9582 100644 --- a/lib/jwt/decode.rb +++ b/lib/jwt/decode.rb @@ -49,6 +49,7 @@ def verify_signature def verify_algo raise JWT::IncorrectAlgorithm, 'An algorithm must be specified' if allowed_algorithms.empty? + raise JWT::DecodeError, 'Token header not a JSON object' unless header.is_a?(Hash) raise JWT::IncorrectAlgorithm, 'Token is missing alg header' unless alg_in_header raise JWT::IncorrectAlgorithm, 'Expected a different algorithm' if allowed_and_valid_algorithms.empty? end diff --git a/spec/jwt/jwt_spec.rb b/spec/jwt/jwt_spec.rb index c11d233e..6c280871 100644 --- a/spec/jwt/jwt_spec.rb +++ b/spec/jwt/jwt_spec.rb @@ -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'), @@ -520,6 +521,14 @@ end.to raise_error JWT::IncorrectAlgorithm end + context 'invalid header format' do + it 'should raise JWT::DecodeError' do + expect do + JWT.decode data[:invalid_header_token] + end.to raise_error JWT::DecodeError + end + end + context '2-segment token' do it 'should raise JWT::IncorrectAlgorithm' do expect do