jwt 2.8.2 → 3.1.1

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.
Files changed (58) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +149 -31
  3. data/CODE_OF_CONDUCT.md +14 -14
  4. data/CONTRIBUTING.md +9 -10
  5. data/README.md +299 -234
  6. data/UPGRADING.md +47 -0
  7. data/lib/jwt/base64.rb +4 -10
  8. data/lib/jwt/claims/audience.rb +30 -0
  9. data/lib/jwt/claims/crit.rb +35 -0
  10. data/lib/jwt/claims/decode_verifier.rb +40 -0
  11. data/lib/jwt/claims/expiration.rb +32 -0
  12. data/lib/jwt/claims/issued_at.rb +22 -0
  13. data/lib/jwt/claims/issuer.rb +34 -0
  14. data/lib/jwt/claims/jwt_id.rb +35 -0
  15. data/lib/jwt/claims/not_before.rb +32 -0
  16. data/lib/jwt/claims/numeric.rb +45 -0
  17. data/lib/jwt/claims/required.rb +33 -0
  18. data/lib/jwt/claims/subject.rb +30 -0
  19. data/lib/jwt/claims/verifier.rb +61 -0
  20. data/lib/jwt/claims.rb +67 -0
  21. data/lib/jwt/configuration/container.rb +20 -1
  22. data/lib/jwt/configuration/decode_configuration.rb +24 -0
  23. data/lib/jwt/configuration/jwk_configuration.rb +1 -0
  24. data/lib/jwt/configuration.rb +8 -0
  25. data/lib/jwt/decode.rb +42 -81
  26. data/lib/jwt/encode.rb +17 -60
  27. data/lib/jwt/encoded_token.rb +236 -0
  28. data/lib/jwt/error.rb +32 -1
  29. data/lib/jwt/json.rb +1 -1
  30. data/lib/jwt/jwa/ecdsa.rb +59 -24
  31. data/lib/jwt/jwa/hmac.rb +22 -19
  32. data/lib/jwt/jwa/none.rb +8 -3
  33. data/lib/jwt/jwa/ps.rb +21 -15
  34. data/lib/jwt/jwa/rsa.rb +21 -10
  35. data/lib/jwt/jwa/signing_algorithm.rb +62 -0
  36. data/lib/jwt/jwa/unsupported.rb +9 -8
  37. data/lib/jwt/jwa.rb +76 -35
  38. data/lib/jwt/jwk/ec.rb +54 -65
  39. data/lib/jwt/jwk/hmac.rb +5 -6
  40. data/lib/jwt/jwk/key_base.rb +16 -1
  41. data/lib/jwt/jwk/key_finder.rb +35 -8
  42. data/lib/jwt/jwk/kid_as_key_digest.rb +1 -0
  43. data/lib/jwt/jwk/rsa.rb +7 -4
  44. data/lib/jwt/jwk/set.rb +2 -0
  45. data/lib/jwt/jwk.rb +1 -1
  46. data/lib/jwt/token.rb +131 -0
  47. data/lib/jwt/version.rb +24 -19
  48. data/lib/jwt.rb +18 -4
  49. data/ruby-jwt.gemspec +2 -0
  50. metadata +49 -15
  51. data/lib/jwt/claims_validator.rb +0 -37
  52. data/lib/jwt/deprecations.rb +0 -48
  53. data/lib/jwt/jwa/eddsa.rb +0 -42
  54. data/lib/jwt/jwa/hmac_rbnacl.rb +0 -50
  55. data/lib/jwt/jwa/hmac_rbnacl_fixed.rb +0 -46
  56. data/lib/jwt/jwa/wrapper.rb +0 -26
  57. data/lib/jwt/jwk/okp_rbnacl.rb +0 -110
  58. data/lib/jwt/verify.rb +0 -117
data/UPGRADING.md ADDED
@@ -0,0 +1,47 @@
1
+ # Upgrading ruby-jwt to >= 3.0.0
2
+
3
+ ## Removal of the indirect [RbNaCl](https://github.com/RubyCrypto/rbnacl) dependency
4
+
5
+ Historically, the set of supported algorithms was extended by including the `rbnacl` gem in the application's Gemfile. On load, ruby-jwt tried to load the gem and, if available, extend the algorithms to those provided by the `rbnacl/libsodium` libraries. This indirect dependency has caused some maintenance pain and confusion about which versions of the gem are supported.
6
+
7
+ Some work to ease the way alternative algorithms can be implemented has been done. This enables the extraction of the algorithm provided by `rbnacl`.
8
+
9
+ The extracted algorithms now live in the [jwt-eddsa](https://rubygems.org/gems/jwt-eddsa) gem.
10
+
11
+ ### Dropped support for HS512256
12
+
13
+ The algorithm HS512256 (HMAC-SHA-512 truncated to 256-bits) is not part of any JWA/JWT RFC and therefore will not be supported anymore. It was part of the HMAC algorithms provided by the indirect [RbNaCl](https://github.com/RubyCrypto/rbnacl) dependency. Currently, there are no direct substitutes for the algorithm.
14
+
15
+ ### `JWT::EncodedToken#payload` will raise before token is verified
16
+
17
+ To avoid accidental use of unverified tokens, the `JWT::EncodedToken#payload` method will raise an error if accessed before the token signature has been verified.
18
+
19
+ To access the payload before verification, use the method `JWT::EncodedToken#unverified_payload`.
20
+
21
+ ## Stricter requirements on Base64 encoded data
22
+
23
+ Base64 decoding will no longer fallback on the looser RFC 2045. The biggest difference is that the looser version was ignoring whitespaces and newlines, whereas the stricter version raises errors in such cases.
24
+
25
+ If you, for example, read tokens from files, there could be problems with trailing newlines. Make sure you trim your input before passing it to the decoding mechanisms.
26
+
27
+ ## Claim verification revamp
28
+
29
+ Claim verification has been [split into separate classes](https://github.com/jwt/ruby-jwt/pull/605) and has [a new API](https://github.com/jwt/ruby-jwt/pull/626), leading to the following deprecations:
30
+
31
+ - The `::JWT::ClaimsValidator` class will be removed in favor of the functionality provided by `::JWT::Claims`.
32
+ - The `::JWT::Claims::verify!` method will be removed in favor of `::JWT::Claims::verify_payload!`.
33
+ - The `::JWT::JWA.create` method will be removed.
34
+ - The `::JWT::Verify` class will be removed in favor of the functionality provided by `::JWT::Claims`.
35
+ - Calling `::JWT::Claims::Numeric.new` with a payload will be removed in favor of `::JWT::Claims::verify_payload!(payload, :numeric)`.
36
+ - Calling `::JWT::Claims::Numeric.verify!` with a payload will be removed in favor of `::JWT::Claims::verify_payload!(payload, :numeric)`.
37
+
38
+ ## Algorithm restructuring
39
+
40
+ The internal algorithms were [restructured](https://github.com/jwt/ruby-jwt/pull/607) to support extensions from separate libraries. The changes led to a few deprecations and new requirements:
41
+
42
+ - The `sign` and `verify` static methods on all the algorithms (`::JWT::JWA`) will be removed.
43
+ - Custom algorithms are expected to include the `JWT::JWA::SigningAlgorithm` module.
44
+
45
+ ## Base64 the `k´ value for HMAC JWKs
46
+
47
+ The gem was missing the Base64 encoding and decoding when representing and parsing a HMAC key as a JWK. This issue is now addressed. The added encoding will break compatibility with JWKs produced by older versions of the gem.
data/lib/jwt/base64.rb CHANGED
@@ -4,29 +4,23 @@ require 'base64'
4
4
 
5
5
  module JWT
6
6
  # Base64 encoding and decoding
7
+ # @api private
7
8
  class Base64
8
9
  class << self
9
10
  # Encode a string with URL-safe Base64 complying with RFC 4648 (not padded).
11
+ # @api private
10
12
  def url_encode(str)
11
13
  ::Base64.urlsafe_encode64(str, padding: false)
12
14
  end
13
15
 
14
16
  # Decode a string with URL-safe Base64 complying with RFC 4648.
15
- # Deprecated support for RFC 2045 remains for now. ("All line breaks or other characters not found in Table 1 must be ignored by decoding software")
17
+ # @api private
16
18
  def url_decode(str)
17
19
  ::Base64.urlsafe_decode64(str)
18
20
  rescue ArgumentError => e
19
21
  raise unless e.message == 'invalid base64'
20
- raise Base64DecodeError, 'Invalid base64 encoding' if JWT.configuration.strict_base64_decoding
21
22
 
22
- loose_urlsafe_decode64(str).tap do
23
- Deprecations.warning('Invalid base64 input detected, could be because of invalid padding, trailing whitespaces or newline chars. Graceful handling of invalid input will be dropped in the next major version of ruby-jwt', only_if_valid: true)
24
- end
25
- end
26
-
27
- def loose_urlsafe_decode64(str)
28
- str += '=' * (4 - str.length.modulo(4))
29
- ::Base64.decode64(str.tr('-_', '+/'))
23
+ raise Base64DecodeError, 'Invalid base64 encoding'
30
24
  end
31
25
  end
32
26
  end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The Audience class is responsible for validating the audience claim ('aud') in a JWT token.
6
+ class Audience
7
+ # Initializes a new Audience instance.
8
+ #
9
+ # @param expected_audience [String, Array<String>] the expected audience(s) for the JWT token.
10
+ def initialize(expected_audience:)
11
+ @expected_audience = expected_audience
12
+ end
13
+
14
+ # Verifies the audience claim ('aud') in the JWT token.
15
+ #
16
+ # @param context [Object] the context containing the JWT payload.
17
+ # @param _args [Hash] additional arguments (not used).
18
+ # @raise [JWT::InvalidAudError] if the audience claim is invalid.
19
+ # @return [nil]
20
+ 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?
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :expected_audience
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # Responsible of validation the crit header
6
+ class Crit
7
+ # Initializes a new Crit instance.
8
+ #
9
+ # @param expected_crits [String] the expected crit header values for the JWT token.
10
+ def initialize(expected_crits:)
11
+ @expected_crits = Array(expected_crits)
12
+ end
13
+
14
+ # Verifies the critical claim ('crit') in the JWT token header.
15
+ #
16
+ # @param context [Object] the context containing the JWT payload and header.
17
+ # @param _args [Hash] additional arguments (not used).
18
+ # @raise [JWT::InvalidCritError] if the crit claim is invalid.
19
+ # @return [nil]
20
+ def verify!(context:, **_args)
21
+ raise(JWT::InvalidCritError, 'Crit header missing') unless context.header['crit']
22
+ raise(JWT::InvalidCritError, 'Crit header should be an array') unless context.header['crit'].is_a?(Array)
23
+
24
+ missing = (expected_crits - context.header['crit'])
25
+ raise(JWT::InvalidCritError, "Crit header missing expected values: #{missing.join(', ')}") if missing.any?
26
+
27
+ nil
28
+ end
29
+
30
+ private
31
+
32
+ attr_reader :expected_crits
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # Context class to contain the data passed to individual claim validators
6
+ #
7
+ # @api private
8
+ VerificationContext = Struct.new(:payload, keyword_init: true)
9
+
10
+ # Verifiers to support the ::JWT.decode method
11
+ #
12
+ # @api private
13
+ module DecodeVerifier
14
+ VERIFIERS = {
15
+ verify_expiration: ->(options) { Claims::Expiration.new(leeway: options[:exp_leeway] || options[:leeway]) },
16
+ verify_not_before: ->(options) { Claims::NotBefore.new(leeway: options[:nbf_leeway] || options[:leeway]) },
17
+ verify_iss: ->(options) { options[:iss] && Claims::Issuer.new(issuers: options[:iss]) },
18
+ verify_iat: ->(*) { Claims::IssuedAt.new },
19
+ verify_jti: ->(options) { Claims::JwtId.new(validator: options[:verify_jti]) },
20
+ verify_aud: ->(options) { options[:aud] && Claims::Audience.new(expected_audience: options[:aud]) },
21
+ verify_sub: ->(options) { options[:sub] && Claims::Subject.new(expected_subject: options[:sub]) },
22
+ required_claims: ->(options) { Claims::Required.new(required_claims: options[:required_claims]) }
23
+ }.freeze
24
+
25
+ private_constant(:VERIFIERS)
26
+
27
+ class << self
28
+ # @api private
29
+ def verify!(payload, options)
30
+ VERIFIERS.each do |key, verifier_builder|
31
+ next unless options[key] || options[key.to_s]
32
+
33
+ verifier_builder&.call(options)&.verify!(context: VerificationContext.new(payload: payload))
34
+ end
35
+ nil
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The Expiration class is responsible for validating the expiration claim ('exp') in a JWT token.
6
+ class Expiration
7
+ # Initializes a new Expiration instance.
8
+ #
9
+ # @param leeway [Integer] the amount of leeway (in seconds) to allow when validating the expiration time. Default: 0.
10
+ def initialize(leeway:)
11
+ @leeway = leeway || 0
12
+ end
13
+
14
+ # Verifies the expiration claim ('exp') in the JWT token.
15
+ #
16
+ # @param context [Object] the context containing the JWT payload.
17
+ # @param _args [Hash] additional arguments (not used).
18
+ # @raise [JWT::ExpiredSignature] if the token has expired.
19
+ # @return [nil]
20
+ def verify!(context:, **_args)
21
+ return unless context.payload.is_a?(Hash)
22
+ return unless context.payload.key?('exp')
23
+
24
+ raise JWT::ExpiredSignature, 'Signature has expired' if context.payload['exp'].to_i <= (Time.now.to_i - leeway)
25
+ end
26
+
27
+ private
28
+
29
+ attr_reader :leeway
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The IssuedAt class is responsible for validating the issued at claim ('iat') in a JWT token.
6
+ class IssuedAt
7
+ # Verifies the issued at claim ('iat') in the JWT token.
8
+ #
9
+ # @param context [Object] the context containing the JWT payload.
10
+ # @param _args [Hash] additional arguments (not used).
11
+ # @raise [JWT::InvalidIatError] if the issued at claim is invalid.
12
+ # @return [nil]
13
+ def verify!(context:, **_args)
14
+ return unless context.payload.is_a?(Hash)
15
+ return unless context.payload.key?('iat')
16
+
17
+ iat = context.payload['iat']
18
+ raise(JWT::InvalidIatError, 'Invalid iat') if !iat.is_a?(::Numeric) || iat.to_f > Time.now.to_f
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The Issuer class is responsible for validating the issuer claim ('iss') in a JWT token.
6
+ class Issuer
7
+ # Initializes a new Issuer instance.
8
+ #
9
+ # @param issuers [String, Symbol, Array<String, Symbol>] the expected issuer(s) for the JWT token.
10
+ def initialize(issuers:)
11
+ @issuers = Array(issuers).map { |item| item.is_a?(Symbol) ? item.to_s : item }
12
+ end
13
+
14
+ # Verifies the issuer claim ('iss') in the JWT token.
15
+ #
16
+ # @param context [Object] the context containing the JWT payload.
17
+ # @param _args [Hash] additional arguments (not used).
18
+ # @raise [JWT::InvalidIssuerError] if the issuer claim is invalid.
19
+ # @return [nil]
20
+ 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
27
+ end
28
+
29
+ private
30
+
31
+ attr_reader :issuers
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The JwtId class is responsible for validating the JWT ID claim ('jti') in a JWT token.
6
+ class JwtId
7
+ # Initializes a new JwtId instance.
8
+ #
9
+ # @param validator [#call] an object responding to `call` to validate the JWT ID.
10
+ def initialize(validator:)
11
+ @validator = validator
12
+ end
13
+
14
+ # Verifies the JWT ID claim ('jti') in the JWT token.
15
+ #
16
+ # @param context [Object] the context containing the JWT payload.
17
+ # @param _args [Hash] additional arguments (not used).
18
+ # @raise [JWT::InvalidJtiError] if the JWT ID claim is invalid or missing.
19
+ # @return [nil]
20
+ def verify!(context:, **_args)
21
+ jti = context.payload['jti']
22
+ if validator.respond_to?(:call)
23
+ verified = validator.arity == 2 ? validator.call(jti, context.payload) : validator.call(jti)
24
+ raise(JWT::InvalidJtiError, 'Invalid jti') unless verified
25
+ elsif jti.to_s.strip.empty?
26
+ raise(JWT::InvalidJtiError, 'Missing jti')
27
+ end
28
+ end
29
+
30
+ private
31
+
32
+ attr_reader :validator
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The NotBefore class is responsible for validating the 'nbf' (Not Before) claim in a JWT token.
6
+ class NotBefore
7
+ # Initializes a new NotBefore instance.
8
+ #
9
+ # @param leeway [Integer] the amount of leeway (in seconds) to allow when validating the 'nbf' claim. Defaults to 0.
10
+ def initialize(leeway:)
11
+ @leeway = leeway || 0
12
+ end
13
+
14
+ # Verifies the 'nbf' (Not Before) claim in the JWT token.
15
+ #
16
+ # @param context [Object] the context containing the JWT payload.
17
+ # @param _args [Hash] additional arguments (not used).
18
+ # @raise [JWT::ImmatureSignature] if the 'nbf' claim has not been reached.
19
+ # @return [nil]
20
+ def verify!(context:, **_args)
21
+ return unless context.payload.is_a?(Hash)
22
+ return unless context.payload.key?('nbf')
23
+
24
+ raise JWT::ImmatureSignature, 'Signature nbf has not been reached' if context.payload['nbf'].to_i > (Time.now.to_i + leeway)
25
+ end
26
+
27
+ private
28
+
29
+ attr_reader :leeway
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The Numeric class is responsible for validating numeric claims in a JWT token.
6
+ # The numeric claims are: exp, iat and nbf
7
+ class Numeric
8
+ # List of numeric claims that can be validated.
9
+ NUMERIC_CLAIMS = %i[
10
+ exp
11
+ iat
12
+ nbf
13
+ ].freeze
14
+
15
+ private_constant(:NUMERIC_CLAIMS)
16
+
17
+ # Verifies the numeric claims in the JWT context.
18
+ #
19
+ # @param context [Object] the context containing the JWT payload.
20
+ # @raise [JWT::InvalidClaimError] if any numeric claim is invalid.
21
+ # @return [nil]
22
+ def verify!(context:)
23
+ validate_numeric_claims(context.payload)
24
+ end
25
+
26
+ private
27
+
28
+ def validate_numeric_claims(payload)
29
+ NUMERIC_CLAIMS.each do |claim|
30
+ validate_is_numeric(payload, claim)
31
+ end
32
+ end
33
+
34
+ def validate_is_numeric(payload, claim)
35
+ return unless payload.is_a?(Hash)
36
+ return unless payload.key?(claim) ||
37
+ payload.key?(claim.to_s)
38
+
39
+ return if payload[claim].is_a?(::Numeric) || payload[claim.to_s].is_a?(::Numeric)
40
+
41
+ raise InvalidPayload, "#{claim} claim must be a Numeric value but it is a #{(payload[claim] || payload[claim.to_s]).class}"
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The Required class is responsible for validating that all required claims are present in a JWT token.
6
+ class Required
7
+ # Initializes a new Required instance.
8
+ #
9
+ # @param required_claims [Array<String>] the list of required claims.
10
+ def initialize(required_claims:)
11
+ @required_claims = required_claims
12
+ end
13
+
14
+ # Verifies that all required claims are present in the JWT payload.
15
+ #
16
+ # @param context [Object] the context containing the JWT payload.
17
+ # @param _args [Hash] additional arguments (not used).
18
+ # @raise [JWT::MissingRequiredClaim] if any required claim is missing.
19
+ # @return [nil]
20
+ def verify!(context:, **_args)
21
+ required_claims.each do |required_claim|
22
+ next if context.payload.is_a?(Hash) && context.payload.key?(required_claim)
23
+
24
+ raise JWT::MissingRequiredClaim, "Missing required claim #{required_claim}"
25
+ end
26
+ end
27
+
28
+ private
29
+
30
+ attr_reader :required_claims
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # The Subject class is responsible for validating the subject claim ('sub') in a JWT token.
6
+ class Subject
7
+ # Initializes a new Subject instance.
8
+ #
9
+ # @param expected_subject [String] the expected subject for the JWT token.
10
+ def initialize(expected_subject:)
11
+ @expected_subject = expected_subject.to_s
12
+ end
13
+
14
+ # Verifies the subject claim ('sub') in the JWT token.
15
+ #
16
+ # @param context [Object] the context containing the JWT payload.
17
+ # @param _args [Hash] additional arguments (not used).
18
+ # @raise [JWT::InvalidSubError] if the subject claim is invalid.
19
+ # @return [nil]
20
+ 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
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :expected_subject
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JWT
4
+ module Claims
5
+ # @api private
6
+ module Verifier
7
+ VERIFIERS = {
8
+ exp: ->(options) { Claims::Expiration.new(leeway: options.dig(:exp, :leeway)) },
9
+ nbf: ->(options) { Claims::NotBefore.new(leeway: options.dig(:nbf, :leeway)) },
10
+ iss: ->(options) { Claims::Issuer.new(issuers: options[:iss]) },
11
+ iat: ->(*) { Claims::IssuedAt.new },
12
+ jti: ->(options) { Claims::JwtId.new(validator: options[:jti]) },
13
+ aud: ->(options) { Claims::Audience.new(expected_audience: options[:aud]) },
14
+ sub: ->(options) { Claims::Subject.new(expected_subject: options[:sub]) },
15
+ crit: ->(options) { Claims::Crit.new(expected_crits: options[:crit]) },
16
+ required: ->(options) { Claims::Required.new(required_claims: options[:required]) },
17
+ numeric: ->(*) { Claims::Numeric.new }
18
+ }.freeze
19
+
20
+ private_constant(:VERIFIERS)
21
+
22
+ class << self
23
+ # @api private
24
+ def verify!(context, *options)
25
+ iterate_verifiers(*options) do |verifier, verifier_options|
26
+ verify_one!(context, verifier, verifier_options)
27
+ end
28
+ nil
29
+ end
30
+
31
+ # @api private
32
+ def errors(context, *options)
33
+ errors = []
34
+ iterate_verifiers(*options) do |verifier, verifier_options|
35
+ verify_one!(context, verifier, verifier_options)
36
+ rescue ::JWT::DecodeError => e
37
+ errors << Error.new(message: e.message)
38
+ end
39
+ errors
40
+ end
41
+
42
+ private
43
+
44
+ def iterate_verifiers(*options)
45
+ options.each do |element|
46
+ if element.is_a?(Hash)
47
+ element.each_key { |key| yield(key, element) }
48
+ else
49
+ yield(element, {})
50
+ end
51
+ end
52
+ end
53
+
54
+ def verify_one!(context, verifier, options)
55
+ verifier_builder = VERIFIERS.fetch(verifier) { raise ArgumentError, "#{verifier} not a valid claim verifier" }
56
+ verifier_builder.call(options || {}).verify!(context: context)
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
data/lib/jwt/claims.rb ADDED
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'claims/audience'
4
+ require_relative 'claims/crit'
5
+ require_relative 'claims/decode_verifier'
6
+ require_relative 'claims/expiration'
7
+ require_relative 'claims/issued_at'
8
+ require_relative 'claims/issuer'
9
+ require_relative 'claims/jwt_id'
10
+ require_relative 'claims/not_before'
11
+ require_relative 'claims/numeric'
12
+ require_relative 'claims/required'
13
+ require_relative 'claims/subject'
14
+ require_relative 'claims/verifier'
15
+
16
+ module JWT
17
+ # JWT Claim verifications
18
+ # https://datatracker.ietf.org/doc/html/rfc7519#section-4
19
+ #
20
+ # Verification is supported for the following claims:
21
+ # exp
22
+ # nbf
23
+ # iss
24
+ # iat
25
+ # jti
26
+ # aud
27
+ # sub
28
+ # required
29
+ # numeric
30
+ module Claims
31
+ # Represents a claim verification error
32
+ Error = Struct.new(:message, keyword_init: true)
33
+
34
+ class << self
35
+ # Checks if the claims in the JWT payload are valid.
36
+ # @example
37
+ #
38
+ # ::JWT::Claims.verify_payload!({"exp" => Time.now.to_i + 10}, :exp)
39
+ # ::JWT::Claims.verify_payload!({"exp" => Time.now.to_i - 10}, exp: { leeway: 11})
40
+ #
41
+ # @param payload [Hash] the JWT payload.
42
+ # @param options [Array] the options for verifying the claims.
43
+ # @return [void]
44
+ # @raise [JWT::DecodeError] if any claim is invalid.
45
+ def verify_payload!(payload, *options)
46
+ Verifier.verify!(VerificationContext.new(payload: payload), *options)
47
+ end
48
+
49
+ # Checks if the claims in the JWT payload are valid.
50
+ #
51
+ # @param payload [Hash] the JWT payload.
52
+ # @param options [Array] the options for verifying the claims.
53
+ # @return [Boolean] true if the claims are valid, false otherwise
54
+ def valid_payload?(payload, *options)
55
+ payload_errors(payload, *options).empty?
56
+ end
57
+
58
+ # Returns the errors in the claims of the JWT token.
59
+ #
60
+ # @param options [Array] the options for verifying the claims.
61
+ # @return [Array<JWT::Claims::Error>] the errors in the claims of the JWT
62
+ def payload_errors(payload, *options)
63
+ Verifier.errors(VerificationContext.new(payload: payload), *options)
64
+ end
65
+ end
66
+ end
67
+ end
@@ -5,23 +5,42 @@ require_relative 'jwk_configuration'
5
5
 
6
6
  module JWT
7
7
  module Configuration
8
+ # The Container class holds the configuration settings for JWT.
8
9
  class Container
10
+ # @!attribute [rw] decode
11
+ # @return [DecodeConfiguration] the decode configuration.
12
+ # @!attribute [rw] jwk
13
+ # @return [JwkConfiguration] the JWK configuration.
14
+ # @!attribute [rw] strict_base64_decoding
15
+ # @return [Boolean] whether strict Base64 decoding is enabled.
9
16
  attr_accessor :decode, :jwk, :strict_base64_decoding
17
+
18
+ # @!attribute [r] deprecation_warnings
19
+ # @return [Symbol] the deprecation warnings setting.
10
20
  attr_reader :deprecation_warnings
11
21
 
22
+ # Initializes a new Container instance and resets the configuration.
12
23
  def initialize
13
24
  reset!
14
25
  end
15
26
 
27
+ # Resets the configuration to default values.
28
+ #
29
+ # @return [void]
16
30
  def reset!
17
31
  @decode = DecodeConfiguration.new
18
32
  @jwk = JwkConfiguration.new
19
- @strict_base64_decoding = false
20
33
 
21
34
  self.deprecation_warnings = :once
22
35
  end
23
36
 
24
37
  DEPRECATION_WARNINGS_VALUES = %i[once warn silent].freeze
38
+ private_constant(:DEPRECATION_WARNINGS_VALUES)
39
+ # Sets the deprecation warnings setting.
40
+ #
41
+ # @param value [Symbol] the deprecation warnings setting. Must be one of `:once`, `:warn`, or `:silent`.
42
+ # @raise [ArgumentError] if the value is not one of the supported values.
43
+ # @return [void]
25
44
  def deprecation_warnings=(value)
26
45
  raise ArgumentError, "Invalid deprecation_warnings value #{value}. Supported values: #{DEPRECATION_WARNINGS_VALUES}" unless DEPRECATION_WARNINGS_VALUES.include?(value)
27
46