From 4ce091920c91adf4da99d606471aff28df29ce9e Mon Sep 17 00:00:00 2001 From: Joakim Antman Date: Fri, 4 Jun 2021 22:26:49 +0300 Subject: [PATCH] Tests for iat verification behaviour --- lib/jwt/verify.rb | 1 + spec/jwt_spec.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/jwt/verify.rb b/lib/jwt/verify.rb index 7c699352..ed9359f4 100644 --- a/lib/jwt/verify.rb +++ b/lib/jwt/verify.rb @@ -45,6 +45,7 @@ def verify_iat return unless @payload.include?('iat') iat = @payload['iat'] + raise(JWT::InvalidIatError, 'Invalid iat') if !iat.is_a?(Numeric) || iat.to_f > Time.now.to_f end diff --git a/spec/jwt_spec.rb b/spec/jwt_spec.rb index 508c8e71..7c0ca537 100644 --- a/spec/jwt_spec.rb +++ b/spec/jwt_spec.rb @@ -537,4 +537,34 @@ end.to raise_error(NotImplementedError) end end + + describe '::JWT.decode with verify_iat parameter' do + let!(:time_now) { Time.now } + let(:token) { ::JWT.encode({ pay: 'load', iat: iat}, 'secret', 'HS256') } + + subject(:decoded_token) { ::JWT.decode(token, 'secret', true, verify_iat: true) } + + before { allow(Time).to receive(:now) { time_now } } + + context 'when iat is exactly the same as Time.now and iat is given as a float' do + let(:iat) { time_now.to_f } + it 'considers iat valid' do + expect(decoded_token).to be_an(Array) + end + end + + context 'when iat is exactly the same as Time.now and iat is given as floored integer' do + let(:iat) { time_now.to_f.floor } + it 'considers iat valid' do + expect(decoded_token).to be_an(Array) + end + end + + context 'when iat is 1 second before Time.now' do + let(:iat) { time_now.to_i + 1 } + it 'raises an error' do + expect { decoded_token }.to raise_error(::JWT::InvalidIatError, 'Invalid iat') + end + end + end end