Skip to content

JWK: raise JWT::JWKError for EC coordinates that don't match the curve #788

Closed

Description

@anakinj

Problem

When an EC JWK's x/y coordinates aren't a valid point on the curve named in crv, JWT::JWK::EC lets the raw OpenSSL error escape. That error isn't a JWT::Error, so code that rescues JWT::Error or JWT::JWKError around decoding doesn't catch it.

The error comes from create_point in lib/jwt/jwk/ec.rb, which builds an OpenSSL::PKey::EC::Point from the JWK parameters. It's raised when the key is first used, through verify_key, private?, export or JWKS-based decoding, not on import.

Reproduction (main, 3.3.1 dev)

p256 = JWT::JWK.new(OpenSSL::PKey::EC.generate("prime256v1")).export

JWT::JWK.import(p256.merge(crv: "P-384")).verify_key
# => OpenSSL::PKey::EC::Point::Error: EC_POINT_bn2point: invalid encoding

JWT::JWK.import(p256.merge(y: p256[:x])).verify_key
# => OpenSSL::PKey::EC::Point::Error: EC_POINT_bn2point: point is not on curve

token = JWT.encode({ a: 1 }, OpenSSL::PKey::EC.generate("prime256v1"), "ES256", kid: "k")
JWT.decode(token, nil, true, algorithms: ["ES256"], jwks: { keys: [p256.merge(crv: "P-384", kid: "k")] })
# => OpenSSL::PKey::EC::Point::Error, not a JWT::Error

Other invalid JWK input is already wrapped. An invalid base64 coordinate raises JWT::Base64DecodeError, and an unknown crv raises JWT::JWKError.

A JWKS is usually fetched from a remote endpoint, so a malformed or mislabelled key there currently surfaces as an OpenSSL exception in application code.

Suggested fix

Rescue OpenSSL::PKey::EC::Point::Error in create_point and re-raise it as JWT::JWKError (for example "Invalid EC point for curve P-384"), keeping the original as the cause. Add specs for a mislabelled curve and an off-curve point, covering both the import-and-use path and JWT.decode with jwks:.

Found while reviewing #787.

Posted by Claude on behalf of @anakinj.

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