File: encoded_token_spec.rb

package info (click to toggle)
ruby-jwt 3.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 876 kB
  • sloc: ruby: 5,550; makefile: 4
file content (478 lines) | stat: -rw-r--r-- 17,022 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# frozen_string_literal: true

RSpec.describe JWT::EncodedToken do
  let(:payload) { { 'pay' => 'load' } }
  let(:header) { {} }
  let(:encoded_token) { JWT::Token.new(payload: payload, header: header).tap { |t| t.sign!(algorithm: 'HS256', key: 'secret') }.jwt }
  let(:detached_payload_token) do
    JWT::Token.new(payload: payload).tap do |t|
      t.detach_payload!
      t.sign!(algorithm: 'HS256', key: 'secret')
    end
  end

  subject(:token) { described_class.new(encoded_token) }

  describe '#unverified_payload' do
    it { expect(token.unverified_payload).to eq(payload) }

    context 'when payload is detached' do
      let(:encoded_token) { detached_payload_token.jwt }

      context 'when payload provided in separate' do
        before { token.encoded_payload = detached_payload_token.encoded_payload }
        it { expect(token.unverified_payload).to eq(payload) }
      end

      context 'when payload is not provided' do
        it 'raises decode error' do
          expect { token.unverified_payload }.to raise_error(JWT::DecodeError, 'Encoded payload is empty')
        end
      end
    end

    context 'when payload is not encoded and the b64 crit is enabled' do
      subject(:token) { described_class.new(encoded_token) }
      let(:encoded_token) { 'eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19..signature' }
      before { token.encoded_payload = '{"foo": "bar"}' }

      it 'handles the payload encoding' do
        expect(token.unverified_payload).to eq({ 'foo' => 'bar' })
      end
    end

    context 'when token is the empty string' do
      let(:encoded_token) { '' }

      it 'raises decode error' do
        expect { token.unverified_payload }.to raise_error(JWT::DecodeError, 'Invalid segment encoding')
      end
    end
  end

  describe '#payload' do
    context 'when token is verified using #valid?' do
      before do
        token.valid?(signature: { algorithm: 'HS256', key: 'secret' })
      end

      it { expect(token.payload).to eq(payload) }
    end

    context 'when token is verified using #verify_signature! and #verify_claims!' do
      before do
        token.verify_signature!(algorithm: 'HS256', key: 'secret')
        token.verify_claims!
      end

      it { expect(token.payload).to eq(payload) }
    end

    context 'when token is checked using #valid_signature? and #valid_claims?' do
      before do
        token.valid_signature?(algorithm: 'HS256', key: 'secret')
        token.valid_claims?
      end

      it { expect(token.payload).to eq(payload) }
    end

    context 'when token is verified using #verify_signature!' do
      before { token.verify_signature!(algorithm: 'HS256', key: 'secret') }

      it 'raises an error' do
        expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token claims before accessing the payload')
      end
    end

    context 'when token is verified using #valid_signature? but is not valid' do
      before { token.valid_signature?(algorithm: 'HS256', key: 'wrong') }

      it 'raises an error' do
        expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload')
      end
    end

    context 'when token is not verified' do
      it 'raises an error' do
        expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload')
      end
    end
  end

  describe '#header' do
    it { expect(token.header).to eq({ 'alg' => 'HS256' }) }

    context 'when token is the empty string' do
      let(:encoded_token) { '' }

      it 'raises decode error' do
        expect { token.header }.to raise_error(JWT::DecodeError, 'Invalid segment encoding')
      end
    end
  end

  describe '#signature' do
    it { expect(token.signature).to be_a(String) }
  end

  describe '#signing_input' do
    it { expect(token.signing_input).to eq('eyJhbGciOiJIUzI1NiJ9.eyJwYXkiOiJsb2FkIn0') }
  end

  describe '#verify_signature!' do
    context 'when key is valid' do
      it 'does not raise' do
        expect(token.verify_signature!(algorithm: 'HS256', key: 'secret')).to eq(nil)
      end
    end

    context 'when key is invalid' do
      it 'raises an error' do
        expect { token.verify_signature!(algorithm: 'HS256', key: 'wrong') }.to raise_error(JWT::VerificationError, 'Signature verification failed')
      end
    end

    context 'when key is an array with one valid entry' do
      it 'does not raise' do
        expect(token.verify_signature!(algorithm: 'HS256', key: %w[wrong secret])).to eq(nil)
      end
    end

    context 'when algorithm is an empty array' do
      it 'raises an error' do
        expect { token.verify_signature!(key: 'secret', algorithm: []) }.to raise_error(JWT::VerificationError, 'No algorithm provided')
      end
    end

    context 'when algorithm is not given' do
      it 'raises an error' do
        expect { token.verify_signature!(key: 'secret') }.to raise_error(ArgumentError, /missing keyword/)
      end
    end

    context 'when header has invalid alg value' do
      let(:header) { { 'alg' => 'HS123' } }

      it 'does not raise' do
        expect(token.header).to eq(header)
        expect(token.verify_signature!(algorithm: 'HS256', key: 'secret')).to eq(nil)
      end
    end

    context 'when payload is detached' do
      let(:encoded_token) { detached_payload_token.jwt }

      context 'when payload provided in separate' do
        before { token.encoded_payload = detached_payload_token.encoded_payload }
        it 'does not raise' do
          expect(token.verify_signature!(algorithm: 'HS256', key: 'secret')).to eq(nil)
        end
      end

      context 'when payload is not provided' do
        it 'raises VerificationError' do
          expect { token.verify_signature!(algorithm: 'HS256', key: 'secret') }.to raise_error(JWT::VerificationError, 'Signature verification failed')
        end
      end
    end

    context 'when key_finder is given' do
      it 'uses key provided by keyfinder' do
        expect(token.verify_signature!(algorithm: 'HS256', key_finder: ->(_token) { 'secret' })).to eq(nil)
      end

      it 'can utilize an array provided by keyfinder' do
        expect(token.verify_signature!(algorithm: 'HS256', key_finder: ->(_token) { %w[wrong secret] })).to eq(nil)
      end
    end

    context 'when neither key or key_finder is given' do
      it 'raises an ArgumentError' do
        expect { token.verify_signature!(algorithm: 'HS256') }.to raise_error(ArgumentError, 'Provide either key or key_finder, not both or neither')
      end
    end

    context 'when both key or key_finder is given' do
      it 'raises an ArgumentError' do
        expect { token.verify_signature!(algorithm: 'HS256', key: 'key', key_finder: 'finder') }.to raise_error(ArgumentError, 'Provide either key or key_finder, not both or neither')
      end
    end

    context 'when payload is not encoded' do
      let(:encoded_token) { 'eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19..A5dxf2s96_n5FLueVuW1Z_vh161FwXZC4YLPff6dmDY' }
      before { token.encoded_payload = '$.02' }

      let(:key) { Base64.urlsafe_decode64('AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow') }

      it 'does not raise' do
        expect(token.verify_signature!(algorithm: 'HS256', key: key)).to eq(nil)
      end
    end

    context 'when JWT::KeyFinder is used as a key_finder' do
      let(:jwk) { JWT::JWK.new(test_pkey('rsa-2048-private.pem')) }
      let(:encoded_token) do
        JWT::Token.new(payload: payload, header: { kid: jwk.kid })
                  .tap { |t| t.sign!(algorithm: 'RS256', key: jwk.signing_key) }
                  .jwt
      end

      it 'uses the keys provided by the JWK key finder' do
        key_finder = JWT::JWK::KeyFinder.new(jwks: JWT::JWK::Set.new(jwk))
        expect(token.verify_signature!(algorithm: 'RS256', key_finder: key_finder)).to eq(nil)
      end
    end

    context 'when RSA JWK is given as a key' do
      let(:jwk) { JWT::JWK.new(test_pkey('rsa-2048-private.pem'), alg: 'RS256') }
      let(:encoded_token) do
        JWT::Token.new(payload: payload)
                  .tap { |t| t.sign!(algorithm: 'RS256', key: jwk.signing_key) }
                  .jwt
      end

      context 'with empty algorithm array provided' do
        it 'uses the JWK for verification' do
          expect(token.verify_signature!(key: jwk, algorithm: [])).to eq(nil)
        end
      end

      context 'with algorithms supported by key provided' do
        it 'uses the JWK for verification' do
          expect(token.verify_signature!(algorithm: %w[RS256 RS512], key: jwk)).to eq(nil)
        end
      end

      context 'with algorithms not supported by key provided' do
        it 'raises JWT::VerificationError' do
          expect { token.verify_signature!(algorithm: %w[RS384 RS512], key: jwk) }.to raise_error(JWT::VerificationError, 'Provided JWKs do not support one of the specified algorithms: RS384, RS512')
        end
      end
    end
  end

  describe '#verify_claims!' do
    context 'when required_claims is passed' do
      it 'raises error' do
        expect { token.verify_claims!(required: ['exp']) }.to raise_error(JWT::MissingRequiredClaim, 'Missing required claim exp')
      end
    end

    context 'exp claim' do
      let(:payload) { { 'exp' => Time.now.to_i - 10, 'pay' => 'load' } }

      it 'verifies the exp' do
        token.verify_claims!(required: ['exp'])
        expect { token.verify_claims!(exp: {}) }.to raise_error(JWT::ExpiredSignature, 'Signature has expired')
        token.verify_claims!(exp: { leeway: 1000 })
      end

      context 'when no claims are provided' do
        it 'raises ExpiredSignature error' do
          expect { token.verify_claims! }.to raise_error(JWT::ExpiredSignature, 'Signature has expired')
        end
      end

      context 'when claim validation skips verifying the exp claim' do
        it 'does not raise' do
          expect { token.verify_claims!({}) }.not_to raise_error
        end
      end

      context 'when claims given as symbol' do
        it 'validates the claim' do
          expect { token.verify_claims!(:exp) }.to raise_error(JWT::ExpiredSignature, 'Signature has expired')
        end
      end

      context 'when claims given as a list of symbols' do
        it 'validates the claim' do
          expect { token.verify_claims!(:exp, :nbf) }.to raise_error(JWT::ExpiredSignature, 'Signature has expired')
        end
      end

      context 'when claims given as a list of symbols and hashes' do
        it 'validates the claim' do
          expect { token.verify_claims!({ exp: { leeway: 1000 }, nbf: {} }, :exp, :nbf) }.to raise_error(JWT::ExpiredSignature, 'Signature has expired')
        end
      end

      context 'when payload is detached' do
        let(:encoded_token) { detached_payload_token.jwt }
        context 'when payload provided in separate' do
          before { token.encoded_payload = detached_payload_token.encoded_payload }
          it 'raises claim verification error' do
            expect { token.verify_claims!(:exp, :nbf) }.to raise_error(JWT::ExpiredSignature, 'Signature has expired')
          end
        end
        context 'when payload is not provided' do
          it 'raises decode error' do
            expect { token.verify_claims!(:exp, :nbf) }.to raise_error(JWT::DecodeError, 'Encoded payload is empty')
          end
        end
      end
    end

    context 'when header contains crits header' do
      let(:header) { { crit: ['b64'] } }

      context 'when expected crits are missing' do
        it 'raises an error' do
          expect { token.verify_claims!(crit: ['other']) }.to raise_error(JWT::InvalidCritError, 'Crit header missing expected values: other')
        end
      end

      context 'when expected crits are present' do
        it 'passes verification' do
          expect { token.verify_claims!(crit: ['b64']) }.not_to raise_error
        end
      end
    end
  end

  context '#verify!' do
    context 'when key is valid' do
      it 'does not raise' do
        expect(token.verify!(signature: { algorithm: 'HS256', key: 'secret' })).to eq(nil)
      end
    end

    context 'when key is invalid' do
      it 'raises an error' do
        expect { token.verify!(signature: { algorithm: 'HS256', key: 'wrong' }) }.to raise_error(JWT::VerificationError, 'Signature verification failed')
      end
    end

    context 'when claims are invalid' do
      let(:payload) { { 'pay' => 'load', exp: Time.now.to_i - 1000 } }

      it 'raises an error' do
        expect do
          token.verify!(signature: { algorithm: 'HS256', key: 'secret' },
                        claims: { exp: { leeway: 900 } })
        end.to raise_error(JWT::ExpiredSignature, 'Signature has expired')
      end
    end
  end

  context '#valid?' do
    context 'when key is valid' do
      it 'returns true' do
        expect(token.valid?(signature: { algorithm: 'HS256', key: 'secret' })).to be(true)
      end
    end

    context 'when key is invalid' do
      it 'returns false' do
        expect(token.valid?(signature: { algorithm: 'HS256', key: 'wrong' })).to be(false)
      end
    end

    context 'when claims are provided as an array' do
      it 'returns true' do
        expect(
          token.valid?(signature: { algorithm: 'HS256', key: 'secret' }, claims: [:exp])
        ).to be(true)
      end
    end

    context 'when claims are invalid' do
      let(:payload) { { 'pay' => 'load', exp: Time.now.to_i - 1000 } }

      it 'returns false' do
        expect(
          token.valid?(signature: { algorithm: 'HS256', key: 'secret' },
                       claims: { exp: { leeway: 900 } })
        ).to be(false)
      end
    end
  end

  describe '#valid_claims?' do
    context 'exp claim' do
      let(:payload) { { 'exp' => Time.now.to_i - 10, 'pay' => 'load' } }

      context 'when claim is valid' do
        it 'returns true' do
          expect(token.valid_claims?(exp: { leeway: 1000 })).to be(true)
        end
      end

      context 'when claim is invalid' do
        it 'returns true' do
          expect(token.valid_claims?(:exp)).to be(false)
        end
      end

      context 'when no claims are provided' do
        it 'validates the exp claim and returns false' do
          expect(token.valid_claims?).to be(false)
        end
      end

      context 'when claim validation skips verifying the exp claim' do
        it 'returns true' do
          expect(token.valid_claims?({})).to be(true)
        end
      end
    end
  end

  describe '#claim_errors' do
    context 'exp claim' do
      let(:payload) { { 'exp' => Time.now.to_i - 10, 'pay' => 'load' } }

      context 'when claim is valid' do
        it 'returns empty array' do
          expect(token.claim_errors(exp: { leeway: 1000 })).to be_empty
        end
      end

      context 'when claim is invalid' do
        it 'returns array with error objects' do
          expect(token.claim_errors(:exp).map(&:message)).to eq(['Signature has expired'])
        end
      end
    end
  end

  describe 'integration use-cases' do
    context 'simple verify HS256 with defaults' do
      let(:encoded_token) do
        JWT::Token.new(payload: { 'pay' => 'load' })
                  .tap { |t| t.sign!(algorithm: 'HS256', key: 'secret_signing_key') }
                  .jwt
      end

      it 'protects the user from unverified payload access' do
        token = described_class.new(encoded_token)

        expect(token.unverified_payload).to eq({ 'pay' => 'load' })
        expect(token.header).to eq({ 'alg' => 'HS256' })

        expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload')

        expect(token.valid_signature?(algorithm: 'HS256', key: 'invalid_signing_key')).to be(false)
        expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload')

        expect(token.valid_signature?(algorithm: 'HS256', key: 'secret_signing_key')).to be(true)
        expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token claims before accessing the payload')

        expect(token.valid_claims?(iss: 'issuer')).to be(false)
        expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token claims before accessing the payload')

        expect(token.valid_claims?).to be(true)
        expect(token.payload).to eq({ 'pay' => 'load' })

        token = described_class.new(encoded_token)

        expect(token.valid?(signature: { algorithm: 'HS256', key: 'invalid_signing_key' })).to be(false)
        expect { token.payload }.to raise_error(JWT::DecodeError, 'Verify the token signature before accessing the payload')

        expect(token.valid?(signature: { algorithm: 'HS256', key: 'secret_signing_key' })).to be(true)
        expect(token.payload).to eq({ 'pay' => 'load' })
      end
    end
  end
end