File: encoded_token.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 (236 lines) | stat: -rw-r--r-- 8,112 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
# frozen_string_literal: true

module JWT
  # Represents an encoded JWT token
  #
  # Processing an encoded and signed token:
  #
  #   token = JWT::Token.new(payload: {pay: 'load'})
  #   token.sign!(algorithm: 'HS256', key: 'secret')
  #
  #   encoded_token = JWT::EncodedToken.new(token.jwt)
  #   encoded_token.verify_signature!(algorithm: 'HS256', key: 'secret')
  #   encoded_token.payload # => {'pay' => 'load'}
  class EncodedToken
    # @private
    # Allow access to the unverified payload for claim verification.
    class ClaimsContext
      extend Forwardable

      def_delegators :@token, :header, :unverified_payload

      def initialize(token)
        @token = token
      end

      def payload
        unverified_payload
      end
    end

    DEFAULT_CLAIMS = [:exp].freeze

    private_constant(:DEFAULT_CLAIMS)

    # Returns the original token provided to the class.
    # @return [String] The JWT token.
    attr_reader :jwt

    # Initializes a new EncodedToken instance.
    #
    # @param jwt [String] the encoded JWT token.
    # @raise [ArgumentError] if the provided JWT is not a String.
    def initialize(jwt)
      raise ArgumentError, 'Provided JWT must be a String' unless jwt.is_a?(String)

      @jwt = jwt
      @signature_verified = false
      @claims_verified    = false

      @encoded_header, @encoded_payload, @encoded_signature = jwt.split('.')
    end

    # Returns the decoded signature of the JWT token.
    #
    # @return [String] the decoded signature.
    def signature
      @signature ||= ::JWT::Base64.url_decode(encoded_signature || '')
    end

    # Returns the encoded signature of the JWT token.
    #
    # @return [String] the encoded signature.
    attr_reader :encoded_signature

    # Returns the decoded header of the JWT token.
    #
    # @return [Hash] the header.
    def header
      @header ||= parse_and_decode(@encoded_header)
    end

    # Returns the encoded header of the JWT token.
    #
    # @return [String] the encoded header.
    attr_reader :encoded_header

    # Returns the payload of the JWT token. Access requires the signature and claims to have been verified.
    #
    # @return [Hash] the payload.
    # @raise [JWT::DecodeError] if the signature has not been verified.
    def payload
      raise JWT::DecodeError, 'Verify the token signature before accessing the payload' unless @signature_verified
      raise JWT::DecodeError, 'Verify the token claims before accessing the payload' unless @claims_verified

      decoded_payload
    end

    # Returns the payload of the JWT token without requiring the signature to have been verified.
    # @return [Hash] the payload.
    def unverified_payload
      decoded_payload
    end

    # Sets or returns the encoded payload of the JWT token.
    #
    # @return [String] the encoded payload.
    attr_accessor :encoded_payload

    # Returns the signing input of the JWT token.
    #
    # @return [String] the signing input.
    def signing_input
      [encoded_header, encoded_payload].join('.')
    end

    # Verifies the token signature and claims.
    # By default it verifies the 'exp' claim.
    #
    # @example
    #  encoded_token.verify!(signature: { algorithm: 'HS256', key: 'secret' }, claims: [:exp])
    #
    # @param signature [Hash] the parameters for signature verification (see {#verify_signature!}).
    # @param claims [Array<Symbol>, Hash] the claims to verify (see {#verify_claims!}).
    # @return [nil]
    # @raise [JWT::DecodeError] if the signature or claim verification fails.
    def verify!(signature:, claims: nil)
      verify_signature!(**signature)
      claims.is_a?(Array) ? verify_claims!(*claims) : verify_claims!(claims)
      nil
    end

    # Verifies the token signature and claims.
    # By default it verifies the 'exp' claim.

    # @param signature [Hash] the parameters for signature verification (see {#verify_signature!}).
    # @param claims [Array<Symbol>, Hash] the claims to verify (see {#verify_claims!}).
    # @return [Boolean] true if the signature and claims are valid, false otherwise.
    def valid?(signature:, claims: nil)
      valid_signature?(**signature) &&
        (claims.is_a?(Array) ? valid_claims?(*claims) : valid_claims?(claims))
    end

    # Verifies the signature of the JWT token.
    #
    # @param algorithm [String, Array<String>, Object, Array<Object>] the algorithm(s) to use for verification.
    # @param key [String, Array<String>] the key(s) to use for verification.
    # @param key_finder [#call] an object responding to `call` to find the key for verification.
    # @return [nil]
    # @raise [JWT::VerificationError] if the signature verification fails.
    # @raise [ArgumentError] if neither key nor key_finder is provided, or if both are provided.
    def verify_signature!(algorithm:, key: nil, key_finder: nil)
      return if valid_signature?(algorithm: algorithm, key: key, key_finder: key_finder)

      raise JWT::VerificationError, 'Signature verification failed'
    end

    # Checks if the signature of the JWT token is valid.
    #
    # @param algorithm [String, Array<String>, Object, Array<Object>] the algorithm(s) to use for verification.
    # @param key [String, Array<String>, JWT::JWK::KeyBase, Array<JWT::JWK::KeyBase>] the key(s) to use for verification.
    # @param key_finder [#call] an object responding to `call` to find the key for verification.
    # @return [Boolean] true if the signature is valid, false otherwise.
    def valid_signature?(algorithm: nil, key: nil, key_finder: nil)
      raise ArgumentError, 'Provide either key or key_finder, not both or neither' if key.nil? == key_finder.nil?

      keys      = Array(key || key_finder.call(self))
      verifiers = JWA.create_verifiers(algorithms: algorithm, keys: keys, preferred_algorithm: header['alg'])

      raise JWT::VerificationError, 'No algorithm provided' if verifiers.empty?

      valid = verifiers.any? do |jwa|
        jwa.verify(data: signing_input, signature: signature)
      end
      valid.tap { |verified| @signature_verified = verified }
    end

    # Verifies the claims of the token.
    # @param options [Array<Symbol>, Hash] the claims to verify. By default, it checks the 'exp' claim.
    # @raise [JWT::DecodeError] if the claims are invalid.
    def verify_claims!(*options)
      Claims::Verifier.verify!(ClaimsContext.new(self), *claims_options(options)).tap do
        @claims_verified = true
      end
    rescue StandardError
      @claims_verified = false
      raise
    end

    # Returns the errors of the claims of the token.
    # @param options [Array<Symbol>, Hash] the claims to verify. By default, it checks the 'exp' claim.
    # @return [Array<Symbol>] the errors of the claims.
    def claim_errors(*options)
      Claims::Verifier.errors(ClaimsContext.new(self), *claims_options(options))
    end

    # Returns whether the claims of the token are valid.
    # @param options [Array<Symbol>, Hash] the claims to verify. By default, it checks the 'exp' claim.
    # @return [Boolean] whether the claims are valid.
    def valid_claims?(*options)
      claim_errors(*claims_options(options)).empty?.tap { |verified| @claims_verified = verified }
    end

    alias to_s jwt

    private

    def claims_options(options)
      return DEFAULT_CLAIMS if options.first.nil?

      options
    end

    def decode_payload
      raise JWT::DecodeError, 'Encoded payload is empty' if encoded_payload == ''

      if unencoded_payload?
        verify_claims!(crit: ['b64'])
        return parse_unencoded(encoded_payload)
      end

      parse_and_decode(encoded_payload)
    end

    def unencoded_payload?
      header['b64'] == false
    end

    def parse_and_decode(segment)
      parse(::JWT::Base64.url_decode(segment || ''))
    end

    def parse_unencoded(segment)
      parse(segment)
    end

    def parse(segment)
      JWT::JSON.parse(segment)
    rescue ::JSON::ParserError
      raise JWT::DecodeError, 'Invalid segment encoding'
    end

    def decoded_payload
      @decoded_payload ||= decode_payload
    end
  end
end