From 62f5fdb96cca612393ff311b1038e8846a31c0b3 Mon Sep 17 00:00:00 2001 From: Natalia Stanko Date: Mon, 17 Apr 2023 17:15:41 +0100 Subject: [PATCH] Handle invalid algorithm when decoding JWT --- CHANGELOG.md | 1 + lib/jwt/algos/algo_wrapper.rb | 2 +- spec/jwt_spec.rb | 8 ++++++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 464a3530..528d8138 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ **Fixes and enhancements:** +- Handle invalid algorithm when decoding JWT [#559](https://github.com/jwt/ruby-jwt/pull/559) - [@nataliastanko](https://github.com/nataliastanko) - Your contribution here ## [v2.7.0](https://github.com/jwt/ruby-jwt/tree/v2.7.0) (2023-02-01) diff --git a/lib/jwt/algos/algo_wrapper.rb b/lib/jwt/algos/algo_wrapper.rb index 2a800ede..e4fa072d 100644 --- a/lib/jwt/algos/algo_wrapper.rb +++ b/lib/jwt/algos/algo_wrapper.rb @@ -11,7 +11,7 @@ def initialize(alg, cls) end def valid_alg?(alg_to_check) - alg.casecmp(alg_to_check)&.zero? == true + alg&.casecmp(alg_to_check)&.zero? == true end def sign(data:, signing_key:) diff --git a/spec/jwt_spec.rb b/spec/jwt_spec.rb index 9f3eab5d..6ed99682 100644 --- a/spec/jwt_spec.rb +++ b/spec/jwt_spec.rb @@ -838,6 +838,14 @@ end end + context 'when the alg is invalid' do + let(:token) { 'eyJhbGciOiJIUzI1NiJ9.eyJwYXkiOiJsb2FkIn0.ZpAhTTtuo-CmbgT6-95NaM_wFckKeyI157baZ29H41o' } + + it 'raises JWT::IncorrectAlgorithm error' do + expect { JWT.decode(token, 'secret', true, algorithm: 'invalid-HS256') }.to raise_error(JWT::IncorrectAlgorithm, 'Expected a different algorithm') + end + end + context 'when algorithm is a custom class' do let(:custom_algorithm) do Class.new do