Skip to content

Plain Ruby error from JWT.decode for a non-numeric exp/nbf or a payload that is not a JSON object #793

Open

Description

@orien

I've run into a problem where JWT.decode raises NoMethodError and TypeError instead of JWT::Error for specific tokens. Specifically, when a correctly signed token carries an exp or nbf that is a Boolean, Array or Hash, or a payload that is not a JSON object. The error escapes rescue JWT::DecodeError, so a caller that rescues the gem's errors to reject the token gets an unhandled error instead.

Seen on jwt 3.3.0 with Ruby 4.0.10.

Reproduction

JWT.encode refuses a non-numeric exp, so the tokens are signed by hand.

require 'jwt'
require 'base64'
require 'openssl'

secret = 'secret'
b64 = ->(h) { Base64.urlsafe_encode64(JSON.generate(h), padding: false) }
sign =  ->(payload) {
  "#{b64.call('alg' => 'HS256')}.#{b64.call(payload)}" \
    ".#{Base64.urlsafe_encode64(OpenSSL::HMAC.digest('SHA256', secret, input), padding: false)}"
}

options = { algorithm: 'HS256', verify_iss: true, iss: 'me', required_claims: ['exp'] }

{
  'exp Array'       => { 'iss' => 'me', 'exp' => ['x'] },
  'exp true'        => { 'iss' => 'me', 'exp' => true },
  'nbf Hash'        => { 'iss' => 'me', 'exp' => Time.now.to_i + 60, 'nbf' => {} },
  'payload Array'   => ['x'],
  'payload Integer' => 42,
  'payload null'    => nil
}.each do |name, payload|
  JWT.decode(sign.call(payload), secret, true, options)
rescue JWT::Error => e
  puts "#{name}: #{e.class} (JWT::Error)"
rescue StandardError => e
  puts "#{name}: #{e.class}: #{e.message}"
end

Output:

exp Array: NoMethodError: undefined method 'to_i' for an instance of Array
exp true: NoMethodError: undefined method 'to_i' for true
nbf Hash: NoMethodError: undefined method 'to_i' for an instance of Hash
payload Array: TypeError: no implicit conversion of String into Integer
payload Integer: TypeError: no implicit conversion of String into Integer
payload null: NoMethodError: undefined method '[]' for nil

Expected

Each case raises a JWT::DecodeError subclass, for example JWT::InvalidPayload for a non-numeric exp or nbf and JWT::MalformedTokenError for a payload that is not a JSON object.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions