jwt 3.3.1 → 3.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ac94f7fd1bb89ec71d44706775828e684817f608314d89021ff542c16783b2bd
4
- data.tar.gz: 67a7a4b461307cc2605af71d5dfb5dad3eac48ffe9090bb76452774395ea4a24
3
+ metadata.gz: de14e160c727913a224d9c021188bb7c031845056f469d21dad987bcd21146fb
4
+ data.tar.gz: 7acb3c8c8383ca27edd8a2f2744a686037692870b3ffdbd10aeb34e3613128b7
5
5
  SHA512:
6
- metadata.gz: ef43ab8d9418b3eb5f36de01e18a461890f1c2d652a49544e167bf65c8fba51a39f306c9e702046ed7e39c73024111ecce7b737c0df63c2ce2164268eecf488c
7
- data.tar.gz: c77ce20c2e1c03ac70ac59aae2a0e8d43c4ed5fcde37839c1c76ca872e83233e0a1a3fbe1ceff6e79212d9e77e47bd8feec73461c05682249655729cb9d41acc
6
+ metadata.gz: 46a3d4fdcc603425c6489e61cda3689d08ee1ee556d629a188accf2ba30e49ecb87522a42f8ef61e09dc50156bb660b51e78e35ef658578b3230c5052d1c36f8
7
+ data.tar.gz: 73e32a48a195e795aea2bbe524f69d0eb082ae56fe509ae76db202bf4b833d9d5279f25eae880d4dc7e7e7600284d4c042665c575679069c6229d2b09aed3be6
data/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.3.2](https://github.com/jwt/ruby-jwt/compare/v3.3.1...v3.3.2) (2026-11-28)
4
+
5
+
6
+ ### Fixes and enhancements
7
+
8
+ * Do not mark the claims as verified when reading an unencoded payload ([#809](https://github.com/jwt/ruby-jwt/issues/809)) ([953e444](https://github.com/jwt/ruby-jwt/commit/953e444258c92d651c2d61a59a25def1b5bf93e4)), closes [#723](https://github.com/jwt/ruby-jwt/issues/723)
9
+ * raise `JWT::ClaimValidationError` for a payload that is not a JSON object ([#794](https://github.com/jwt/ruby-jwt/issues/794)) ([04e5ecd](https://github.com/jwt/ruby-jwt/commit/04e5ecdd6d38348eca87e3ad4ddda0235538dc36)), closes [#793](https://github.com/jwt/ruby-jwt/issues/793)
10
+ * Reject a missing iss or sub, and raise claim errors instead of crashing in the iss and jti checks ([#808](https://github.com/jwt/ruby-jwt/issues/808)) ([d487fca](https://github.com/jwt/ruby-jwt/commit/d487fcab7defe2dd5782e334eb1124d9683c0bae))
11
+ * Reject public keys and certificates as HMAC secrets ([d78ddc2](https://github.com/jwt/ruby-jwt/commit/d78ddc2f652d2894ef1085828ea2a75fecc43a88))
12
+ * Try the remaining keys when a verification key is of the wrong type or on another EC curve ([d78ddc2](https://github.com/jwt/ruby-jwt/commit/d78ddc2f652d2894ef1085828ea2a75fecc43a88))
13
+
3
14
  ## [v3.3.1](https://github.com/jwt/ruby-jwt/tree/v3.3.1) (2026-11-24)
4
15
 
5
16
  [Full Changelog](https://github.com/jwt/ruby-jwt/compare/v3.3.0...v3.3.1)
data/CONTRIBUTING.md CHANGED
@@ -41,13 +41,8 @@ bundle exec rubocop
41
41
  ## Implement your feature
42
42
 
43
43
  Implement tests and your change. Don't be shy adding a little something in the [README](README.md).
44
- Add a short description of the change in either the `Features` or `Fixes` section in the [CHANGELOG](CHANGELOG.md) file.
45
44
 
46
- The form of the row (You need to return to the row when you know the pull request id)
47
-
48
- ```markdown
49
- - Fix a little problem [#123](https://github.com/jwt/ruby-jwt/pull/123) - [@you](https://github.com/you).
50
- ```
45
+ Don't edit the [CHANGELOG](CHANGELOG.md). It's generated from the pull request titles when a release is made.
51
46
 
52
47
  ## Push your branch and create a pull request
53
48
 
@@ -61,17 +56,13 @@ git push origin fix-a-little-problem
61
56
 
62
57
  Make a new pull request on the [ruby-jwt project](https://github.com/jwt/ruby-jwt/pulls) with a description what the change is about.
63
58
 
64
- ## Update the CHANGELOG, again
59
+ Title the pull request in the [Conventional Commits](https://www.conventionalcommits.org/) format, for example `fix: Reject tokens with too many segments`. Pull requests are squash merged, so the title becomes the commit message, and the changelog is generated from it. Write the description as it should read in the changelog. Use one of these types:
65
60
 
66
- Update the [CHANGELOG](CHANGELOG.md) with the pull request id from the previous step.
61
+ - `feat` for a new feature, which leads to a minor release
62
+ - `fix` for a bug fix, which leads to a patch release
63
+ - `perf`, `refactor`, `docs`, `test`, `ci`, `build`, `chore` or `revert` for everything else
67
64
 
68
- You can amend the previous commit with the updated changelog change and force push your branch. The PR will get automatically updated.
69
-
70
- ```bash
71
- git add CHANGELOG.md
72
- git commit --amend --no-edit
73
- git push origin fix-a-little-problem -f
74
- ```
65
+ Add `!` after the type, as in `feat!:`, for a breaking change, which leads to a major release. A check on the pull request verifies the format, and maintainers may adjust the title before merging.
75
66
 
76
67
  ## Keep an eye on your pull request
77
68
 
@@ -90,21 +81,23 @@ git push origin fix-a-little-problem -f
90
81
 
91
82
  ## Releasing a new version
92
83
 
93
- The version follows [Semantic Versioning](http://semver.org/) and lives in the [version.rb](lib/jwt/version.rb) file. It is bumped right after every release, so main normally already carries the next version number. Check that it is the number you mean to release and adjust it if, say, a feature landed on what had been set up as a patch release.
84
+ Releases are made with [release-please](https://github.com/googleapis/release-please). The version follows [Semantic Versioning](http://semver.org/) and is picked from the pull request titles merged since the last release: `fix` and `perf` lead to a patch release, `feat` to a minor release, and a `!` after the type to a major release.
94
85
 
95
- Prepare the release on a branch: give the upcoming [CHANGELOG](CHANGELOG.md) section its release date and remove the `Your contribution here` placeholders. Merge it as usual.
86
+ After each merge to main, the [release-please.yml](.github/workflows/release-please.yml) workflow opens or updates a release pull request. It bumps the version in [version.rb](lib/jwt/version.rb) and adds a section to the [CHANGELOG](CHANGELOG.md) with an entry for each `feat`, `fix`, `perf` and `revert` pull request. Other types are left out. Edit a pull request's title before merging it if the changelog entry should read differently.
96
87
 
97
- Then tag the merged commit and push the tag to this repository:
88
+ To release, merge the release pull request. The workflow then tags the merge commit, creates the GitHub release, and calls [push_gem.yml](.github/workflows/push_gem.yml), which verifies that the tag matches `JWT.gem_version`, builds the gem, pushes it to RubyGems using trusted publishing and waits for it to propagate. No RubyGems credentials are needed on your machine.
98
89
 
99
- ```bash
100
- git checkout main
101
- git pull upstream main
102
- git tag -a v3.3.0 -m "Version 3.3.0"
103
- git push upstream v3.3.0
104
- ```
90
+ If publishing fails, fix the cause and run the **Push Gem** workflow manually with the tag as input to publish it again.
91
+
92
+ Do not use `rake release`. It builds and pushes the gem from your machine, which bypasses trusted publishing.
105
93
 
106
- Pushing the tag is what publishes the gem. The [push_gem.yml](.github/workflows/push_gem.yml) workflow verifies that the tag matches `JWT.gem_version`, builds the gem, pushes it to RubyGems using trusted publishing and waits for it to propagate. No RubyGems credentials are needed on your machine.
94
+ ### Releasing 2.x
107
95
 
108
- Do not use `rake release`. It builds and pushes the gem from your machine, which bypasses trusted publishing, and it pushes the tag too, so the workflow then fails trying to publish a version that already exists.
96
+ The `2-10-stable` branch is released by hand. Bump the version in [version.rb](lib/jwt/version.rb), add a section to the [CHANGELOG](CHANGELOG.md) and merge it, then tag the merged commit and push the tag:
97
+
98
+ ```bash
99
+ git tag -a v2.10.4 -m "Version 2.10.4"
100
+ git push upstream v2.10.4
101
+ ```
109
102
 
110
- Once the workflow is green, [create a GitHub release](https://github.com/jwt/ruby-jwt/releases/new) for the tag, named `jwt-<version>` and with the changelog section for that version as its body. Finally, open the next iteration by bumping the version and adding a fresh `NEXT` changelog section.
103
+ Pushing the tag runs [push_gem.yml](.github/workflows/push_gem.yml) on the branch. Then [create a GitHub release](https://github.com/jwt/ruby-jwt/releases/new) for the tag.
data/README.md CHANGED
@@ -7,8 +7,6 @@
7
7
 
8
8
  A ruby implementation of the [RFC 7519 OAuth JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519) standard.
9
9
 
10
- If you have further questions related to development or usage, join us: [ruby-jwt google group](https://groups.google.com/forum/#!forum/ruby-jwt).
11
-
12
10
  See [CHANGELOG.md](CHANGELOG.md) for a complete set of changes and [upgrade guide](UPGRADING.md) for upgrading between major versions.
13
11
 
14
12
  ## Sponsors
@@ -29,7 +27,7 @@ gem install jwt
29
27
 
30
28
  Add the following to your Gemfile
31
29
 
32
- ```bash
30
+ ```ruby
33
31
  gem 'jwt'
34
32
  ```
35
33
 
@@ -45,7 +43,7 @@ require 'jwt'
45
43
 
46
44
  The jwt gem natively supports the NONE, HMAC, RSASSA, ECDSA and RSASSA-PSS algorithms via the openssl library. The gem can be extended with additional or alternative implementations of the algorithms via extensions.
47
45
 
48
- Additionally the EdDSA algorithm is supported via a the [jwt-eddsa gem](https://rubygems.org/gems/jwt-eddsa).
46
+ Additionally the EdDSA algorithm is supported via the [jwt-eddsa gem](https://rubygems.org/gems/jwt-eddsa).
49
47
 
50
48
  For safe cryptographic signing, you need to specify the algorithm in the options hash whenever you call `JWT.decode` to ensure that an attacker [cannot bypass the algorithm verification step](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). **It is strongly recommended that you hard code the algorithm, as you may leave yourself vulnerable by dynamically picking the algorithm**
51
49
 
@@ -61,10 +59,10 @@ token = JWT.encode(payload, nil, 'none')
61
59
  # => "eyJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9."
62
60
 
63
61
  decoded_token = JWT.decode(token, nil, true, { algorithm: 'none' })
64
- # => [
65
- # {"data"=>"test"}, # payload
66
- # {"alg"=>"none"} # header
67
- # ]
62
+ # => [
63
+ # {"data"=>"test"}, # payload
64
+ # {"alg"=>"none"} # header
65
+ # ]
68
66
  ```
69
67
 
70
68
  ### **HMAC**
@@ -116,15 +114,16 @@ decoded_token = JWT.decode(token, rsa_public, true, { algorithm: 'RS256' })
116
114
  - ES256K - ECDSA using P-256K and SHA-256
117
115
 
118
116
  ```ruby
119
- payload = { data: 'test' }
120
- ecdsa_key = OpenSSL::PKey::EC.generate('prime256v1')
117
+ payload = { data: 'test' }
118
+ ecdsa_private = OpenSSL::PKey::EC.generate('prime256v1')
119
+ ecdsa_public = OpenSSL::PKey::EC.new(ecdsa_private.public_to_der)
121
120
 
122
- token = JWT.encode(payload, ecdsa_key, 'ES256')
121
+ token = JWT.encode(payload, ecdsa_private, 'ES256')
123
122
  # => "eyJhbGciOiJFUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.AlLW--kaF7EX1NMX9WJRuIW8NeRJbn2BLXHns7Q5TZr7Hy3lF6MOpMlp7GoxBFRLISQ6KrD0CJOrR8aogEsPeg"
124
123
 
125
- decoded_token = JWT.decode(token, ecdsa_key, true, { algorithm: 'ES256' })
124
+ decoded_token = JWT.decode(token, ecdsa_public, true, { algorithm: 'ES256' })
126
125
  # => [
127
- # {"test"=>"data"}, # payload
126
+ # {"data"=>"test"}, # payload
128
127
  # {"alg"=>"ES256"} # header
129
128
  # ]
130
129
  ```
@@ -176,15 +175,17 @@ module CustomHS512Algorithm
176
175
  end
177
176
 
178
177
  def self.verify(data:, signature:, verification_key:)
179
- ::OpenSSL.secure_compare(sign(data: data, signing_key: verification_key), signature)
178
+ OpenSSL.secure_compare(sign(data: data, signing_key: verification_key), signature)
180
179
  end
181
180
  end
182
181
 
183
- payload = { data: 'test' }
184
- token = JWT.encode(payload, 'secret', CustomHS512Algorithm)
185
- # => "eyJhbGciOiJIUzUxMiJ9.eyJkYXRhIjoidGVzdCJ9.aBNoejLEM2WMF3TxzRDKlehYdG2ATvFpGNauTI4GSD2VJseS_sC8covrVMlgslf0aJM4SKb3EIeORJBFPtZ33w"
182
+ payload = { data: 'test' }
183
+ hmac_secret = 'my$ecretK3y'
184
+
185
+ token = JWT.encode(payload, hmac_secret, CustomHS512Algorithm)
186
+ # => "eyJhbGciOiJIUzUxMiJ9.eyJkYXRhIjoidGVzdCJ9.A1E4QkK-YRAJCS8jhhClibuZNdKxUopEOVrQNTZAN9y4PhGMNVyfKrIMycTNtOEwdei70ZTDOXobeiLa4mwDkw"
186
187
 
187
- decoded_token = JWT.decode(token, 'secret', true, algorithm: CustomHS512Algorithm)
188
+ decoded_token = JWT.decode(token, hmac_secret, true, { algorithm: CustomHS512Algorithm })
188
189
  # => [
189
190
  # {"data"=>"test"}, # payload
190
191
  # {"alg"=>"HS512"} # header
@@ -193,8 +194,8 @@ decoded_token = JWT.decode(token, 'secret', true, algorithm: CustomHS512Algorith
193
194
 
194
195
  ### Add custom header fields
195
196
 
196
- The ruby-jwt gem supports custom [header fields](https://tools.ietf.org/html/rfc7519#section-5)
197
- To add custom header fields you need to pass `header_fields` parameter
197
+ The ruby-jwt gem supports custom [header fields](https://tools.ietf.org/html/rfc7519#section-5).
198
+ To add custom header fields, pass them in the `header_fields` parameter.
198
199
 
199
200
  ```ruby
200
201
  payload = { data: 'test' }
@@ -203,10 +204,10 @@ token = JWT.encode(payload, nil, 'none', { typ: 'JWT' })
203
204
  # => "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9."
204
205
 
205
206
  decoded_token = JWT.decode(token, nil, true, { algorithm: 'none' })
206
- # => [
207
- # {"data"=>"test"}, # payload
208
- # {"typ"=>"JWT", "alg"=>"none"} # header
209
- # ]
207
+ # => [
208
+ # {"data"=>"test"}, # payload
209
+ # {"typ"=>"JWT", "alg"=>"none"} # header
210
+ # ]
210
211
  ```
211
212
 
212
213
  ## `JWT::Token` and `JWT::EncodedToken`
@@ -216,59 +217,60 @@ The `JWT::Token` and `JWT::EncodedToken` classes can be used to manage your JWTs
216
217
  ### Signing and encoding a token
217
218
 
218
219
  ```ruby
219
- payload = { exp: Time.now.to_i + 60, jti: '1234', sub: "my-subject" }
220
- header = { kid: 'hmac' }
220
+ payload = { exp: Time.now.to_i + 60, jti: '1234', sub: 'my-subject' }
221
+ header = { kid: 'hmac' }
222
+ hmac_secret = 'my$ecretK3y'
221
223
 
222
224
  token = JWT::Token.new(payload: payload, header: header)
223
- token.sign!(algorithm: 'HS256', key: "secret")
225
+ token.sign!(algorithm: 'HS256', key: hmac_secret)
224
226
 
225
227
  token.jwt
226
- # => "eyJraWQiOiJobWFjIiwiYWxnIjoiSFMyNTYifQ.eyJleHAiOjE3NTAwMDU0NzksImp0aSI6IjEyMzQiLCJzdWIiOiJteS1zdWJqZWN0In0.NRLcK6fYr3IdNfmncJePMWLQ34M4n14EgqSYrQIjL9w"
228
+ # => "eyJraWQiOiJobWFjIiwiYWxnIjoiSFMyNTYifQ.eyJleHAiOjE3OTU4MDQzMDAsImp0aSI6IjEyMzQiLCJzdWIiOiJteS1zdWJqZWN0In0.8viuwmMsA2UUe4ksmgg9F8rMzud9M3LOHsIKoavN5e8"
227
229
  ```
228
230
 
229
231
  ### Verifying and decoding a token
230
232
 
231
- The `JWT::EncodedToken` can be used as a token object that allows verification of signatures and claims.
233
+ The `JWT::EncodedToken` can be used as a token object that allows verification of signatures and claims. The payload can only be read after both the signature and the claims have been verified.
232
234
 
233
235
  ```ruby
234
236
  encoded_token = JWT::EncodedToken.new(token.jwt)
235
237
 
236
- encoded_token.verify_signature!(algorithm: 'HS256', key: "secret")
237
- encoded_token.verify_signature!(algorithm: 'HS256', key: "wrong_secret") # raises JWT::VerificationError
238
+ encoded_token.verify_signature!(algorithm: 'HS256', key: 'wrong_secret') # raises JWT::VerificationError
239
+ encoded_token.verify_claims!(sub: ['not-my-subject']) # raises JWT::InvalidSubError
240
+ encoded_token.claim_errors(sub: ['not-my-subject']).map(&:message) # => ["Invalid subject. Expected [\"not-my-subject\"], received my-subject"]
241
+
242
+ encoded_token.verify_signature!(algorithm: 'HS256', key: hmac_secret)
238
243
  encoded_token.verify_claims!(:exp, :jti)
239
- encoded_token.verify_claims!(sub: ["not-my-subject"]) # raises JWT::InvalidSubError
240
- encoded_token.claim_errors(sub: ["not-my-subject"]).map(&:message) # => ["Invalid subject. Expected [\"not-my-subject\"], received my-subject"]
241
- encoded_token.payload # => { 'exp'=>1234, 'jti'=>'1234", 'sub'=>'my-subject' }
242
- encoded_token.header # {'kid'=>'hmac', 'alg'=>'HS256'}
244
+ encoded_token.payload # => {"exp"=>1795804300, "jti"=>"1234", "sub"=>"my-subject"}
245
+ encoded_token.header # => {"kid"=>"hmac", "alg"=>"HS256"}
243
246
  ```
244
247
 
245
248
  The `JWT::EncodedToken#verify!` method can be used to verify signature and claim verification in one go. The `exp` claim is verified by default.
246
249
 
247
250
  ```ruby
248
251
  encoded_token = JWT::EncodedToken.new(token.jwt)
249
- encoded_token.verify!(signature: {algorithm: 'HS256', key: "secret"})
250
- encoded_token.payload # => { 'exp'=>1234, 'jti'=>'1234", 'sub'=>'my-subject' }
251
- encoded_token.header # {'kid'=>'hmac', 'alg'=>'HS256'}
252
+ encoded_token.verify!(signature: { algorithm: 'HS256', key: hmac_secret })
253
+ encoded_token.payload # => {"exp"=>1795804300, "jti"=>"1234", "sub"=>"my-subject"}
254
+ encoded_token.header # => {"kid"=>"hmac", "alg"=>"HS256"}
252
255
  ```
253
256
 
254
257
  A JWK can be used to sign and verify the token if it's possible to derive the signing algorithm from the key.
255
258
 
256
259
  ```ruby
257
260
  jwk_json = '{
258
- "kty": "oct",
259
- "k": "c2VjcmV0",
260
- "alg": "HS256",
261
- "kid": "hmac"
261
+ "kty": "oct",
262
+ "k": "bXkkZWNyZXRLM3k",
263
+ "alg": "HS256",
264
+ "kid": "hmac"
262
265
  }'
263
266
 
264
267
  jwk = JWT::JWK.import(JSON.parse(jwk_json))
265
268
 
266
269
  token = JWT::Token.new(payload: payload, header: header)
267
-
268
- token.sign!(key: jwk, algorithm: 'HS256')
270
+ token.sign!(algorithm: 'HS256', key: jwk)
269
271
 
270
272
  encoded_token = JWT::EncodedToken.new(token.jwt)
271
- encoded_token.verify!(signature: { algorithm: ["HS256", "HS512"], key: jwk})
273
+ encoded_token.verify!(signature: { algorithm: ['HS256', 'HS512'], key: jwk })
272
274
  ```
273
275
 
274
276
  #### Using a keyfinder
@@ -280,49 +282,50 @@ An example on using the built-in JWK keyfinder.
280
282
  ```ruby
281
283
  # Create and sign a token
282
284
  jwk = JWT::JWK.new(OpenSSL::PKey::RSA.generate(2048))
283
- token = JWT::Token.new(payload: { pay: 'load' }, header: { kid: jwk.kid })
285
+ token = JWT::Token.new(payload: { data: 'test' }, header: { kid: jwk.kid })
284
286
  token.sign!(algorithm: 'RS256', key: jwk.signing_key)
285
287
 
286
288
  # Create keyfinder object, verify and decode token
287
289
  key_finder = JWT::JWK::KeyFinder.new(jwks: JWT::JWK::Set.new(jwk))
288
290
  encoded_token = JWT::EncodedToken.new(token.jwt)
289
- encoded_token.verify!(signature: { algorithm: 'RS256', key_finder: key_finder})
290
- encoded_token.payload # => { 'pay' => 'load' }
291
+ encoded_token.verify!(signature: { algorithm: 'RS256', key_finder: key_finder })
292
+ encoded_token.payload # => {"data"=>"test"}
291
293
  ```
292
294
 
293
295
  Using a custom keyfinder proc.
294
296
 
295
297
  ```ruby
296
298
  # Create and sign a token
297
- key = OpenSSL::PKey::RSA.generate(2048)
298
- token = JWT::Token.new(payload: { pay: 'load' })
299
- token.sign!(algorithm: 'RS256', key: key)
299
+ rsa_private = OpenSSL::PKey::RSA.generate(2048)
300
+ rsa_public = rsa_private.public_key
301
+ token = JWT::Token.new(payload: { data: 'test' })
302
+ token.sign!(algorithm: 'RS256', key: rsa_private)
300
303
 
301
304
  # Verify and decode token
302
305
  encoded_token = JWT::EncodedToken.new(token.jwt)
303
- encoded_token.verify!(signature: { algorithm: 'RS256', key_finder: ->(_token){ key.public_key }})
304
- encoded_token.payload # => { 'pay' => 'load' }
306
+ encoded_token.verify!(signature: { algorithm: 'RS256', key_finder: ->(_token) { rsa_public } })
307
+ encoded_token.payload # => {"data"=>"test"}
305
308
  ```
306
309
 
307
310
  ### Detached payload
308
311
 
309
- The `::JWT::Token#detach_payload!` method can be use to detach the payload from the JWT.
312
+ The `JWT::Token#detach_payload!` method can be used to detach the payload from the JWT.
310
313
 
311
314
  ```ruby
312
- token = JWT::Token.new(payload: { pay: 'load' })
313
- token.sign!(algorithm: 'HS256', key: "secret")
315
+ token = JWT::Token.new(payload: { data: 'test' })
316
+ token.sign!(algorithm: 'HS256', key: hmac_secret)
314
317
  token.detach_payload!
315
- token.jwt # => "eyJhbGciOiJIUzI1NiJ9..UEhDY1Qlj29ammxuVRA_-gBah4qTy5FngIWg0yEAlC0"
316
- token.encoded_payload # => "eyJwYXkiOiJsb2FkIn0"
318
+ token.jwt # => "eyJhbGciOiJIUzI1NiJ9..pNIWIL34Jo13LViZAJACzK6Yf0qnvT_BuwOxiMCPE-Y"
319
+ token.encoded_payload # => "eyJkYXRhIjoidGVzdCJ9"
317
320
  ```
318
321
 
319
- The `JWT::EncodedToken` class can be used to decode a token with a detached payload by providing the payload to the token instance in separate.
322
+ The `JWT::EncodedToken` class can be used to decode a token with a detached payload by giving the payload to the token instance separately.
320
323
 
321
324
  ```ruby
322
325
  encoded_token = JWT::EncodedToken.new(token.jwt)
323
- encoded_token.encoded_payload = "eyJwYXkiOiJsb2FkIn0"
324
- encoded_token.verify_signature!(algorithm: 'HS256', key: "secret")
325
- encoded_token.payload # => {"pay"=>"load"}
326
+ encoded_token.encoded_payload = 'eyJkYXRhIjoidGVzdCJ9'
327
+ encoded_token.verify!(signature: { algorithm: 'HS256', key: hmac_secret })
328
+ encoded_token.payload # => {"data"=>"test"}
326
329
  ```
327
330
 
328
331
  ## Claims
@@ -346,7 +349,7 @@ From [Oauth JSON Web Token 4.1.4. "exp" (Expiration Time) Claim](https://tools.i
346
349
 
347
350
  ```ruby
348
351
  exp = Time.now.to_i + 4 * 3600
349
- exp_payload = { data: 'data', exp: exp }
352
+ exp_payload = { data: 'test', exp: exp }
350
353
 
351
354
  token = JWT.encode(exp_payload, hmac_secret, 'HS256')
352
355
 
@@ -370,9 +373,9 @@ Leeway and the exp claim.
370
373
  exp = Time.now.to_i - 10
371
374
  leeway = 30 # seconds
372
375
 
373
- exp_payload = { data: 'data', exp: exp }
376
+ exp_payload = { data: 'test', exp: exp }
374
377
 
375
- # build expired token
378
+ # build an expired token
376
379
  token = JWT.encode(exp_payload, hmac_secret, 'HS256')
377
380
 
378
381
  begin
@@ -391,7 +394,7 @@ From [Oauth JSON Web Token 4.1.5. "nbf" (Not Before) Claim](https://tools.ietf.o
391
394
 
392
395
  ```ruby
393
396
  nbf = Time.now.to_i - 3600
394
- nbf_payload = { data: 'data', nbf: nbf }
397
+ nbf_payload = { data: 'test', nbf: nbf }
395
398
 
396
399
  token = JWT.encode(nbf_payload, hmac_secret, 'HS256')
397
400
 
@@ -413,11 +416,11 @@ Leeway and the nbf claim.
413
416
 
414
417
  ```ruby
415
418
  nbf = Time.now.to_i + 10
416
- leeway = 30
419
+ leeway = 30 # seconds
417
420
 
418
- nbf_payload = { data: 'data', nbf: nbf }
421
+ nbf_payload = { data: 'test', nbf: nbf }
419
422
 
420
- # build expired token
423
+ # build a token that is not valid yet
421
424
  token = JWT.encode(nbf_payload, hmac_secret, 'HS256')
422
425
 
423
426
  begin
@@ -434,11 +437,11 @@ From [Oauth JSON Web Token 4.1.1. "iss" (Issuer) Claim](https://tools.ietf.org/h
434
437
 
435
438
  > The `iss` (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The `iss` value is a case-sensitive string containing a **_StringOrURI_** value. Use of this claim is OPTIONAL.
436
439
 
437
- You can pass multiple allowed issuers as an Array, verification will pass if one of them matches the `iss` value in the payload.
440
+ You can pass multiple allowed issuers as an Array, verification will pass if one of them matches the `iss` value in the payload. A token without an `iss` claim does not pass, and `nil` never matches. The Regexp, Proc and Method matchers shown below are only used when `iss` is a String; any other `iss` value has to equal one of the expected issuers.
438
441
 
439
442
  ```ruby
440
443
  iss = 'My Awesome Company Inc. or https://my.awesome.website/'
441
- iss_payload = { data: 'data', iss: iss }
444
+ iss_payload = { data: 'test', iss: iss }
442
445
 
443
446
  token = JWT.encode(iss_payload, hmac_secret, 'HS256')
444
447
 
@@ -450,29 +453,18 @@ rescue JWT::InvalidIssuerError
450
453
  end
451
454
  ```
452
455
 
453
- You can also pass a Regexp or Proc (with arity 1), verification will pass if the regexp matches or the proc returns truthy.
454
- On supported ruby versions (>= 2.5) you can also delegate to methods, on older versions you will have
455
- to convert them to proc (using `to_proc`)
456
+ You can also pass a Regexp, a Proc or a Method (with arity 1), verification will pass if the regexp matches or the proc or method returns truthy.
456
457
 
457
458
  ```ruby
458
- JWT.decode(token, hmac_secret, true,
459
- iss: %r'https://my.awesome.website/',
460
- verify_iss: true,
461
- algorithm: 'HS256')
459
+ JWT.decode(token, hmac_secret, true, { iss: %r{https://my.awesome.website/}, verify_iss: true, algorithm: 'HS256' })
462
460
  ```
463
461
 
464
462
  ```ruby
465
- JWT.decode(token, hmac_secret, true,
466
- iss: ->(issuer) { issuer.start_with?('My Awesome Company Inc') },
467
- verify_iss: true,
468
- algorithm: 'HS256')
463
+ JWT.decode(token, hmac_secret, true, { iss: ->(issuer) { issuer.start_with?('My Awesome Company Inc') }, verify_iss: true, algorithm: 'HS256' })
469
464
  ```
470
465
 
471
466
  ```ruby
472
- JWT.decode(token, hmac_secret, true,
473
- iss: method(:valid_issuer?),
474
- verify_iss: true,
475
- algorithm: 'HS256')
467
+ JWT.decode(token, hmac_secret, true, { iss: method(:valid_issuer?), verify_iss: true, algorithm: 'HS256' })
476
468
 
477
469
  # somewhere in the same class:
478
470
  def valid_issuer?(issuer)
@@ -488,7 +480,7 @@ From [Oauth JSON Web Token 4.1.3. "aud" (Audience) Claim](https://tools.ietf.org
488
480
 
489
481
  ```ruby
490
482
  aud = ['Young', 'Old']
491
- aud_payload = { data: 'data', aud: aud }
483
+ aud_payload = { data: 'test', aud: aud }
492
484
 
493
485
  token = JWT.encode(aud_payload, hmac_secret, 'HS256')
494
486
 
@@ -497,7 +489,6 @@ begin
497
489
  decoded_token = JWT.decode(token, hmac_secret, true, { aud: aud, verify_aud: true, algorithm: 'HS256' })
498
490
  rescue JWT::InvalidAudError
499
491
  # Handle invalid token, e.g. logout user or deny access
500
- puts 'Audience Error'
501
492
  end
502
493
  ```
503
494
 
@@ -508,23 +499,21 @@ From [Oauth JSON Web Token 4.1.7. "jti" (JWT ID) Claim](https://tools.ietf.org/h
508
499
  > The `jti` (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The `jti` claim can be used to prevent the JWT from being replayed. The `jti` value is a case-sensitive string. Use of this claim is OPTIONAL.
509
500
 
510
501
  ```ruby
511
- # Use the secret and iat to create a unique key per request to prevent replay attacks
512
- jti_raw = [hmac_secret, iat].join(':').to_s
513
- jti = Digest::MD5.hexdigest(jti_raw)
514
- jti_payload = { data: 'data', iat: iat, jti: jti }
502
+ # Use a random, unique identifier for each token
503
+ jti = SecureRandom.uuid
504
+ jti_payload = { data: 'test', jti: jti }
515
505
 
516
506
  token = JWT.encode(jti_payload, hmac_secret, 'HS256')
517
507
 
518
508
  begin
519
509
  # If :verify_jti is true, validation will pass if a JTI is present
520
- #decoded_token = JWT.decode(token, hmac_secret, true, { verify_jti: true, algorithm: 'HS256' })
510
+ decoded_token = JWT.decode(token, hmac_secret, true, { verify_jti: true, algorithm: 'HS256' })
521
511
  # Alternatively, pass a proc with your own code to check if the JTI has already been used
522
- decoded_token = JWT.decode(token, hmac_secret, true, { verify_jti: proc { |jti| my_validation_method(jti) }, algorithm: 'HS256' })
512
+ decoded_token = JWT.decode(token, hmac_secret, true, { verify_jti: ->(jti) { my_validation_method(jti) }, algorithm: 'HS256' })
523
513
  # or
524
- decoded_token = JWT.decode(token, hmac_secret, true, { verify_jti: proc { |jti, payload| my_validation_method(jti, payload) }, algorithm: 'HS256' })
514
+ decoded_token = JWT.decode(token, hmac_secret, true, { verify_jti: ->(jti, payload) { my_validation_method(jti, payload) }, algorithm: 'HS256' })
525
515
  rescue JWT::InvalidJtiError
526
516
  # Handle invalid token, e.g. logout user or deny access
527
- puts 'Error'
528
517
  end
529
518
  ```
530
519
 
@@ -538,7 +527,7 @@ The global `leeway` option does not apply to `iat`. To allow for clock drift, pa
538
527
 
539
528
  ```ruby
540
529
  iat = Time.now.to_i
541
- iat_payload = { data: 'data', iat: iat }
530
+ iat_payload = { data: 'test', iat: iat }
542
531
 
543
532
  token = JWT.encode(iat_payload, hmac_secret, 'HS256')
544
533
 
@@ -562,9 +551,11 @@ From [Oauth JSON Web Token 4.1.2. "sub" (Subject) Claim](https://tools.ietf.org/
562
551
 
563
552
  > The `sub` (subject) claim identifies the principal that is the subject of the JWT. The Claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The sub value is a case-sensitive string containing a **_StringOrURI_** value. Use of this claim is OPTIONAL.
564
553
 
554
+ When `sub` is verified, a token without a `sub` claim does not pass, and the expected subject must not be blank.
555
+
565
556
  ```ruby
566
557
  sub = 'Subject'
567
- sub_payload = { data: 'data', sub: sub }
558
+ sub_payload = { data: 'test', sub: sub }
568
559
 
569
560
  token = JWT.encode(sub_payload, hmac_secret, 'HS256')
570
561
 
@@ -580,26 +571,26 @@ end
580
571
 
581
572
  The JWT claim verifications can be used to verify any Hash to include expected keys and values.
582
573
 
583
- A few example on verifying the claims for a payload:
574
+ A few examples of verifying the claims for a payload:
584
575
 
585
576
  ```ruby
586
- JWT::Claims.verify_payload!({"exp" => Time.now.to_i + 10}, :numeric, :exp)
587
- JWT::Claims.valid_payload?({"exp" => Time.now.to_i + 10}, :exp)
577
+ JWT::Claims.verify_payload!({ 'exp' => Time.now.to_i + 10 }, :numeric, :exp)
578
+ JWT::Claims.valid_payload?({ 'exp' => Time.now.to_i + 10 }, :exp)
588
579
  # => true
589
- JWT::Claims.payload_errors({"exp" => Time.now.to_i - 10}, :exp)
580
+ JWT::Claims.payload_errors({ 'exp' => Time.now.to_i - 10 }, :exp)
590
581
  # => [#<struct JWT::Claims::Error message="Signature has expired">]
591
- JWT::Claims.verify_payload!({"exp" => Time.now.to_i - 10}, exp: { leeway: 11})
582
+ JWT::Claims.verify_payload!({ 'exp' => Time.now.to_i - 10 }, exp: { leeway: 11 })
592
583
 
593
- JWT::Claims.verify_payload!({"exp" => Time.now.to_i + 10, "sub" => "subject"}, :exp, sub: "subject")
584
+ JWT::Claims.verify_payload!({ 'exp' => Time.now.to_i + 10, 'sub' => 'subject' }, :exp, sub: 'subject')
594
585
  ```
595
586
 
596
587
  ### Finding a Key
597
588
 
598
- To dynamically find the key for verifying the JWT signature, pass a block to the decode block. The block receives headers and the original payload as parameters. It should return with the key to verify the signature that was used to sign the JWT.
589
+ To dynamically find the key for verifying the JWT signature, pass a block to `JWT.decode`. The block receives the header and the original payload as parameters. It should return the key to verify the signature that was used to sign the JWT.
599
590
 
600
591
  ```ruby
601
592
  issuers = %w[My_Awesome_Company1 My_Awesome_Company2]
602
- iss_payload = { data: 'data', iss: issuers.first }
593
+ iss_payload = { data: 'test', iss: issuers.first }
603
594
 
604
595
  secrets = { issuers.first => hmac_secret, issuers.last => 'hmac_secret2' }
605
596
 
@@ -607,7 +598,7 @@ token = JWT.encode(iss_payload, hmac_secret, 'HS256')
607
598
 
608
599
  begin
609
600
  # Add iss to the validation to check if the token has been manipulated
610
- decoded_token = JWT.decode(token, nil, true, { iss: issuers, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload|
601
+ decoded_token = JWT.decode(token, nil, true, { iss: issuers, verify_iss: true, algorithm: 'HS256' }) do |_header, payload|
611
602
  secrets[payload['iss']]
612
603
  end
613
604
  rescue JWT::InvalidIssuerError
@@ -617,7 +608,7 @@ end
617
608
 
618
609
  ### Required Claims
619
610
 
620
- You can specify claims that must be present for decoding to be successful. JWT::MissingRequiredClaim will be raised if any are missing
611
+ You can specify claims that must be present for decoding to be successful. `JWT::MissingRequiredClaim` will be raised if any are missing.
621
612
 
622
613
  ```ruby
623
614
  # Will raise a JWT::MissingRequiredClaim error if the 'exp' claim is absent
@@ -630,16 +621,16 @@ A JWT signature can be verified using certificate(s) given in the `x5c` header.
630
621
 
631
622
  ```ruby
632
623
  root_certificates = [] # trusted `OpenSSL::X509::Certificate` objects
633
- crl_uris = root_certificates.map(&:crl_uris)
624
+ crl_uris = root_certificates.flat_map(&:crl_uris).compact
634
625
  crls = crl_uris.map do |uri|
635
626
  # look up cached CRL by `uri` and return it if found, otherwise continue
636
- crl = Net::HTTP.get(uri)
637
- crl = OpenSSL::X509::CRL.new(crl)
627
+ crl = OpenSSL::X509::CRL.new(Net::HTTP.get(URI(uri)))
638
628
  # cache `crl` using `uri` as the key, expiry set to `crl.next_update` timestamp
629
+ crl
639
630
  end
640
631
 
641
632
  begin
642
- JWT.decode(token, nil, true, { x5c: { root_certificates: root_certificates, crls: crls } })
633
+ JWT.decode(token, nil, true, { algorithm: 'RS256', x5c: { root_certificates: root_certificates, crls: crls } })
643
634
  rescue JWT::TokenError
644
635
  # Handle error, e.g. x5c header certificate revoked or expired
645
636
  end
@@ -647,17 +638,17 @@ end
647
638
 
648
639
  ## JSON Web Key (JWK)
649
640
 
650
- JWK is a JSON structure representing a cryptographic key. This gem currently supports RSA, EC, OKP and HMAC keys. OKP support requires [RbNaCl](https://github.com/RubyCrypto/rbnacl) and currently only supports the Ed25519 curve.
641
+ JWK is a JSON structure representing a cryptographic key. This gem supports RSA, EC and HMAC keys. OKP keys (Ed25519) are supported by the [jwt-eddsa gem](https://rubygems.org/gems/jwt-eddsa).
651
642
 
652
643
  To encode a JWT using your JWK:
653
644
 
654
645
  ```ruby
655
646
  optional_parameters = { kid: 'my-kid', use: 'sig', alg: 'RS512' }
656
- jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), optional_parameters)
647
+ jwk = JWT::JWK.new(OpenSSL::PKey::RSA.generate(2048), optional_parameters)
657
648
 
658
649
  # Encoding
659
- payload = { data: 'data' }
660
- token = JWT.encode(payload, jwk.signing_key, jwk[:alg], kid: jwk[:kid])
650
+ payload = { data: 'test' }
651
+ token = JWT.encode(payload, jwk.signing_key, jwk[:alg], { kid: jwk[:kid] })
661
652
 
662
653
  # JSON Web Key Set for advertising your signing keys
663
654
  jwks_hash = JWT::JWK::Set.new(jwk).export
@@ -667,9 +658,9 @@ To decode a JWT using a trusted entity's JSON Web Key Set (JWKS):
667
658
 
668
659
  ```ruby
669
660
  jwks = JWT::JWK::Set.new(jwks_hash)
670
- jwks.filter! {|key| key[:use] == 'sig' } # Signing keys only!
661
+ jwks.select! { |key| key[:use] == 'sig' } # Signing keys only
671
662
  algorithms = jwks.map { |key| key[:alg] }.compact.uniq
672
- JWT.decode(token, nil, true, algorithms: algorithms, jwks: jwks)
663
+ JWT.decode(token, nil, true, { algorithms: algorithms, jwks: jwks })
673
664
  ```
674
665
 
675
666
  The `jwks` option can also be given as a lambda that evaluates every time a key identifier is resolved.
@@ -683,7 +674,7 @@ Tokens without a specified key identifier (`kid` or `x5t`) are rejected by defau
683
674
  This behaviour may be overwritten by setting the `allow_nil_kid` option for `decode` to `true`.
684
675
 
685
676
  ```ruby
686
- jwks_loader = ->(options) do
677
+ jwks_loader = lambda do |options|
687
678
  # The jwk loader would fetch the set of JWKs from a trusted source.
688
679
  # To avoid malicious requests triggering cache invalidations there needs to be
689
680
  # some kind of grace time or other logic for determining the validity of the invalidation.
@@ -696,7 +687,7 @@ jwks_loader = ->(options) do
696
687
  @cache_last_update = Time.now.to_i
697
688
  # Replace with your own JWKS fetching routine
698
689
  jwks = JWT::JWK::Set.new(jwks_hash)
699
- jwks.select! { |key| key[:use] == 'sig' } # Signing Keys only
690
+ jwks.select! { |key| key[:use] == 'sig' } # Signing keys only
700
691
  jwks
701
692
  end
702
693
  end
@@ -712,19 +703,19 @@ end
712
703
 
713
704
  ### Importing and exporting JSON Web Keys
714
705
 
715
- The ::JWT::JWK class can be used to import both JSON Web Keys and OpenSSL keys
706
+ The `JWT::JWK` class can be used to import both JSON Web Keys and OpenSSL keys
716
707
  and export to either format with and without the private key included.
717
708
 
718
709
  To include the private key in the export pass the `include_private` parameter to the export method.
719
710
 
720
711
  ```ruby
721
- # Import a JWK Hash (showing an HMAC example)
722
- jwk = JWT::JWK.new({ kty: 'oct', k: 'my-secret', kid: 'my-kid' })
712
+ # Import a JWK Hash (showing an HMAC example, `k` is the base64url-encoded secret)
713
+ jwk = JWT::JWK.new({ kty: 'oct', k: 'bXkkZWNyZXRLM3k', kid: 'my-kid' })
723
714
 
724
715
  # Import an OpenSSL key
725
716
  # You can optionally add descriptive parameters to the JWK
726
717
  desc_params = { kid: 'my-kid', use: 'sig' }
727
- jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), desc_params)
718
+ jwk = JWT::JWK.new(OpenSSL::PKey::RSA.generate(2048), desc_params)
728
719
 
729
720
  # Export as JWK Hash (public key only by default)
730
721
  jwk_hash = jwk.export
@@ -735,7 +726,7 @@ public_key = jwk.verify_key
735
726
  private_key = jwk.signing_key if jwk.private?
736
727
 
737
728
  # You can also import and export entire JSON Web Key Sets
738
- jwks_hash = { keys: [{ kty: 'oct', k: 'my-secret', kid: 'my-kid' }] }
729
+ jwks_hash = { keys: [{ kty: 'oct', k: 'bXkkZWNyZXRLM3k', kid: 'my-kid' }] }
739
730
  jwks = JWT::JWK::Set.new(jwks_hash)
740
731
  jwks_hash = jwks.export
741
732
  ```
@@ -749,9 +740,9 @@ or can be given to the JWK instance on initialization.
749
740
  ```ruby
750
741
  JWT.configuration.jwk.kid_generator_type = :rfc7638_thumbprint
751
742
  # OR
752
- JWT.configuration.jwk.kid_generator = ::JWT::JWK::Thumbprint
743
+ JWT.configuration.jwk.kid_generator = JWT::JWK::Thumbprint
753
744
  # OR
754
- jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048), nil, kid_generator: ::JWT::JWK::Thumbprint)
745
+ jwk = JWT::JWK.new(OpenSSL::PKey::RSA.generate(2048), nil, kid_generator: JWT::JWK::Thumbprint)
755
746
 
756
747
  jwk_hash = jwk.export
757
748
 
@@ -769,13 +760,7 @@ bundle exec appraisal rake test
769
760
 
770
761
  ## Releasing
771
762
 
772
- To cut a new release adjust the [version.rb](lib/jwt/version.rb) and [CHANGELOG](CHANGELOG.md) with desired version numbers and dates and commit the changes. Tag the release with the version number using the following command:
773
-
774
- ```bash
775
- rake release:source_control_push
776
- ```
777
-
778
- This will tag a new version an trigger a [GitHub action](.github/workflows/push_gem.yml) that eventually will push the gem to rubygems.org.
763
+ See [Releasing a new version](CONTRIBUTING.md#releasing-a-new-version) in CONTRIBUTING.
779
764
 
780
765
  ## How to contribute
781
766
 
data/UPGRADING.md CHANGED
@@ -1,3 +1,31 @@
1
+ # Upgrading ruby-jwt to >= 3.3.2
2
+
3
+ ## Claim checks fail when the claim is missing
4
+
5
+ The `iss` and `sub` checks no longer pass for a token that lacks the claim, and the `iss`, `aud`, `sub` and `jti` checks treat a payload that is not a Hash as having no claims. Each check raises its own error, such as `JWT::InvalidIssuerError`, instead of passing or raising a plain Ruby error.
6
+
7
+ - **`iss`:** a token without `iss` fails, whatever the expected issuers are. Issuer Procs and Methods are no longer called with `nil`, so a Proc written to accept a missing issuer now rejects the token. `nil` among the expected issuers, as in `iss: [ENV['JWT_ISSUER']]` with the variable unset, no longer matches a token without `iss`. Regexp, Proc and Method matchers are only used for a String `iss`; any other value has to equal one of the expected issuers.
8
+ - **`aud`:** `nil` among the expected audiences no longer matches a token whose `aud` is `[null]`.
9
+ - **`sub`:** a token without `sub` fails, and so does every token when the expected subject is blank. This includes `:sub` given to `JWT::EncodedToken#verify_claims!` or `JWT::Claims.verify_payload!` without a value, which used to pass for tokens without `sub`.
10
+ - **Payloads that are not a Hash:** Hash-like objects, such as `ActionController::Parameters`, given to `JWT::Claims.verify_payload!` or used as a `JWT::Token` payload now fail these checks. Convert them with `to_h` first. `JWT.decode` is not affected, because it parses the payload from JSON.
11
+
12
+ ## Public keys and certificates are rejected as HMAC secrets
13
+
14
+ `HS256`, `HS384` and `HS512` reject the PEM and SSH encodings listed below when used as the shared secret. Public keys in other encodings, including DER, bare base64 and JWK JSON strings, are not detected and can still act as HMAC secrets; do not include them in mixed asymmetric/HMAC key lists. Signing with a rejected encoding raises `JWT::EncodeError`, and verifying with one raises `JWT::VerificationKeyError`, both with the message `HMAC key cannot be a public key or certificate`. This covers:
15
+
16
+ - a public key in PEM, such as `-----BEGIN PUBLIC KEY-----` or `-----BEGIN RSA PUBLIC KEY-----`;
17
+ - a certificate in PEM, such as `-----BEGIN CERTIFICATE-----`;
18
+ - an OpenSSH public key or certificate, such as `ssh-ed25519 AAAA…`, including a line from `authorized_keys`;
19
+ - an RFC 4716 SSH public key (`---- BEGIN SSH2 PUBLIC KEY ----`).
20
+
21
+ A public key is known to others by design, so anyone holding it could sign tokens that verify with such a secret. If you use one, replace it with a randomly generated secret. Tokens signed with the old secret will no longer verify. A private key used as the secret is not affected, unless the same string also holds a public key or certificate, as a combined key and certificate file does.
22
+
23
+ ## Every key is tried when several are given
24
+
25
+ When several keys are given for verification, a key that cannot be used for the algorithm, such as an EC key for `HS256` or an EC key on another curve, no longer stops the remaining keys from being tried. A token now verifies if any key matches. When none does, the error for the first unusable key is raised, as before.
26
+
27
+ If you allow an HMAC algorithm alongside an asymmetric one, every String in the key list can now act as an HMAC secret, wherever it is in the list. RSA, ECDSA and EdDSA only accept key objects, so a public key given as a String, in any format, does nothing for them and should not be in the list. Keep the keys for each algorithm apart instead, for example with a key finder block that returns keys based on the token's `alg` header.
28
+
1
29
  # Upgrading ruby-jwt to >= 3.3.0
2
30
 
3
31
  ## Error hierarchy revamp
@@ -15,11 +15,12 @@ module JWT
15
15
  #
16
16
  # @param context [Object] the context containing the JWT payload.
17
17
  # @param _args [Hash] additional arguments (not used).
18
- # @raise [JWT::InvalidAudError] if the audience claim is invalid.
18
+ # @raise [JWT::InvalidAudError] if no audience in the claim is one of the expected audiences.
19
+ # A payload that is not a Hash has no audience claim, and nil never matches.
19
20
  # @return [nil]
20
21
  def verify!(context:, **_args)
21
- aud = context.payload['aud']
22
- raise JWT::InvalidAudError, "Invalid audience. Expected #{expected_audience}, received #{aud || '<none>'}" if ([*aud] & [*expected_audience]).empty?
22
+ aud = context.payload['aud'] if context.payload.is_a?(Hash)
23
+ raise JWT::InvalidAudError, "Invalid audience. Expected #{expected_audience}, received #{aud || '<none>'}" if ([*aud].compact & [*expected_audience].compact).empty?
23
24
  end
24
25
 
25
26
  private
@@ -15,20 +15,30 @@ module JWT
15
15
  #
16
16
  # @param context [Object] the context containing the JWT payload.
17
17
  # @param _args [Hash] additional arguments (not used).
18
- # @raise [JWT::InvalidIssuerError] if the issuer claim is invalid.
18
+ # @raise [JWT::InvalidIssuerError] if the issuer claim is missing or matches none of the expected issuers.
19
+ # A payload that is not a Hash has no issuer claim. Regexp, Proc and Method matchers are only used for
20
+ # a String issuer; any other issuer has to equal one of the expected issuers.
19
21
  # @return [nil]
20
22
  def verify!(context:, **_args)
21
- case (iss = context.payload['iss'])
22
- when *issuers
23
- nil
24
- else
25
- raise JWT::InvalidIssuerError, "Invalid issuer. Expected #{issuers}, received #{iss || '<none>'}"
26
- end
23
+ iss = context.payload['iss'] if context.payload.is_a?(Hash)
24
+ return if expected_issuer?(iss)
25
+
26
+ raise JWT::InvalidIssuerError, "Invalid issuer. Expected #{issuers}, received #{iss.nil? ? '<none>' : iss}"
27
27
  end
28
28
 
29
29
  private
30
30
 
31
31
  attr_reader :issuers
32
+
33
+ def expected_issuer?(iss)
34
+ return false if iss.nil?
35
+ return issuers.include?(iss) unless iss.is_a?(String)
36
+
37
+ case iss
38
+ when *issuers then true
39
+ else false
40
+ end
41
+ end
32
42
  end
33
43
  end
34
44
  end
@@ -15,12 +15,15 @@ module JWT
15
15
  #
16
16
  # @param context [Object] the context containing the JWT payload.
17
17
  # @param _args [Hash] additional arguments (not used).
18
- # @raise [JWT::InvalidJtiError] if the JWT ID claim is invalid or missing.
18
+ # @raise [JWT::InvalidJtiError] if the JWT ID claim is invalid or missing. A payload that is not a Hash
19
+ # raises without calling the validator.
19
20
  # @return [nil]
20
21
  def verify!(context:, **_args)
22
+ raise(JWT::InvalidJtiError, 'Missing jti') unless context.payload.is_a?(Hash)
23
+
21
24
  jti = context.payload['jti']
22
25
  if validator.respond_to?(:call)
23
- verified = validator.arity == 2 ? validator.call(jti, context.payload) : validator.call(jti)
26
+ verified = validator_arity == 2 ? validator.call(jti, context.payload) : validator.call(jti)
24
27
  raise(JWT::InvalidJtiError, 'Invalid jti') unless verified
25
28
  elsif jti.to_s.strip.empty?
26
29
  raise(JWT::InvalidJtiError, 'Missing jti')
@@ -30,6 +33,10 @@ module JWT
30
33
  private
31
34
 
32
35
  attr_reader :validator
36
+
37
+ def validator_arity
38
+ validator.respond_to?(:arity) ? validator.arity : validator.method(:call).arity
39
+ end
33
40
  end
34
41
  end
35
42
  end
@@ -15,11 +15,14 @@ module JWT
15
15
  #
16
16
  # @param context [Object] the context containing the JWT payload.
17
17
  # @param _args [Hash] additional arguments (not used).
18
- # @raise [JWT::InvalidSubError] if the subject claim is invalid.
18
+ # @raise [JWT::InvalidSubError] if the subject claim is missing or does not match the expected subject,
19
+ # or if the expected subject is blank. A payload that is not a Hash has no subject claim.
19
20
  # @return [nil]
20
21
  def verify!(context:, **_args)
21
- sub = context.payload['sub']
22
- raise(JWT::InvalidSubError, "Invalid subject. Expected #{expected_subject}, received #{sub || '<none>'}") unless sub.to_s == expected_subject
22
+ sub = context.payload['sub'] if context.payload.is_a?(Hash)
23
+ return if !sub.nil? && !expected_subject.strip.empty? && sub.to_s == expected_subject
24
+
25
+ raise JWT::InvalidSubError, "Invalid subject. Expected #{expected_subject}, received #{sub.nil? ? '<none>' : sub}"
23
26
  end
24
27
 
25
28
  private
@@ -226,7 +226,7 @@ module JWT
226
226
  raise JWT::MalformedTokenError, 'Encoded payload is empty' if encoded_payload == ''
227
227
 
228
228
  if unencoded_payload?
229
- verify_claims!(crit: ['b64'])
229
+ Claims::Verifier.verify!(ClaimsContext.new(self), crit: ['b64'])
230
230
  return parse(encoded_payload)
231
231
  end
232
232
 
data/lib/jwt/jwa/hmac.rb CHANGED
@@ -15,6 +15,10 @@ module JWT
15
15
  'HS512' => 64
16
16
  }.freeze
17
17
 
18
+ PUBLIC_KEY_BANNER = /-----BEGIN (?:RSA |EC |DSA )?PUBLIC KEY-----|-----BEGIN (?:X509 |TRUSTED )?CERTIFICATE-----|---- BEGIN SSH2 PUBLIC KEY ----/.freeze
19
+ OPENSSH_PUBLIC_KEY = /(?:\A|\s)(?:ssh-(?:rsa|dss|ed25519|ed448)|ecdsa-sha2-nistp(?:256|384|521)|sk-(?:ssh-ed25519|ecdsa-sha2-nistp256))(?:-cert-v01)?(?:@openssh\.com)?\s+AAAA/.freeze
20
+ private_constant :PUBLIC_KEY_BANNER, :OPENSSH_PUBLIC_KEY
21
+
18
22
  def initialize(alg, digest)
19
23
  @alg = alg
20
24
  @digest = digest
@@ -45,6 +49,7 @@ module JWT
45
49
  def validate_key!(key)
46
50
  yield 'HMAC key expected to be a String' unless key.is_a?(String)
47
51
  yield 'HMAC key cannot be empty' if key.empty?
52
+ yield 'HMAC key cannot be a public key or certificate' if public_key_material?(key)
48
53
 
49
54
  return unless JWT.configuration.decode.enforce_hmac_key_length
50
55
 
@@ -52,6 +57,11 @@ module JWT
52
57
  yield "HMAC key must be at least #{min_length} bytes for #{alg} algorithm" if key.bytesize < min_length
53
58
  end
54
59
 
60
+ def public_key_material?(key)
61
+ binary = key.b
62
+ binary.match?(PUBLIC_KEY_BANNER) || binary.match?(OPENSSH_PUBLIC_KEY)
63
+ end
64
+
55
65
  # Copy of https://github.com/rails/rails/blob/v7.0.3.1/activesupport/lib/active_support/security_utils.rb
56
66
  # rubocop:disable-next Naming/MethodParameterName, Style/StringLiterals, Style/NumericPredicate
57
67
  module SecurityUtils
@@ -12,9 +12,16 @@ module JWT
12
12
  end
13
13
 
14
14
  def verify(*args, **kwargs)
15
- @keys.any? do |key|
15
+ errors = []
16
+ verified = @keys.any? do |key|
16
17
  @jwa.verify(*args, **kwargs, verification_key: key)
18
+ rescue VerificationError, IncorrectAlgorithm => e
19
+ errors << e
20
+ false
17
21
  end
22
+ raise errors.first if !verified && !errors.empty?
23
+
24
+ verified
18
25
  end
19
26
  end
20
27
  end
data/lib/jwt/version.rb CHANGED
@@ -14,9 +14,9 @@ module JWT
14
14
 
15
15
  # Version constants
16
16
  module VERSION
17
- MAJOR = 3
18
- MINOR = 3
19
- TINY = 1
17
+ MAJOR = 3 # x-release-please-major
18
+ MINOR = 3 # x-release-please-minor
19
+ TINY = 2 # x-release-please-patch
20
20
  PRE = nil
21
21
 
22
22
  STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
@@ -0,0 +1,17 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
3
+ "release-type": "ruby",
4
+ "packages": {
5
+ ".": {
6
+ "version-file": "lib/jwt/version.rb",
7
+ "extra-files": ["lib/jwt/version.rb"],
8
+ "include-commit-authors": true,
9
+ "changelog-sections": [
10
+ { "type": "feat", "section": "Features" },
11
+ { "type": "fix", "section": "Fixes and enhancements" },
12
+ { "type": "perf", "section": "Fixes and enhancements" },
13
+ { "type": "revert", "section": "Reverts" }
14
+ ]
15
+ }
16
+ }
17
+ }
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jwt
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.3.1
4
+ version: 3.3.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tim Rudat
@@ -196,13 +196,14 @@ files:
196
196
  - lib/jwt/token.rb
197
197
  - lib/jwt/version.rb
198
198
  - lib/jwt/x5c_key_finder.rb
199
+ - release-please-config.json
199
200
  - ruby-jwt.gemspec
200
201
  homepage: https://github.com/jwt/ruby-jwt
201
202
  licenses:
202
203
  - MIT
203
204
  metadata:
204
205
  bug_tracker_uri: https://github.com/jwt/ruby-jwt/issues
205
- changelog_uri: https://github.com/jwt/ruby-jwt/blob/v3.3.1/CHANGELOG.md
206
+ changelog_uri: https://github.com/jwt/ruby-jwt/blob/v3.3.2/CHANGELOG.md
206
207
  rubygems_mfa_required: 'true'
207
208
  rdoc_options: []
208
209
  require_paths: