From 26995119754f6e448ab97e61d75382007a115125 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 30 Nov 2026 18:19:38 -0500 Subject: [PATCH 1/2] fix(session): accept ES256 access tokens and ignore unknown JWKS keys The session verifier accepted only RS256 access tokens. It read the JWKS through the generated JwksResponse model, which holds only the members of an RSA key. Thus one JWKS key of a different type made each session check fail. The verifier now accepts RS256 and ES256. The allow-list is a fixed constant. The SDK reads the JWKS as raw JSON and uses the `kid` header of the token to select the key. It ignores all other keys, also keys of a type that it does not know. The SDK does these checks before ruby-jwt verifies the signature, because not all permitted ruby-jwt versions do them: - RS256 uses only an RSA key. ES256 uses only an EC P-256 key. - If the key has an `alg` member, it must be the algorithm of the token. - If the key has a `use` member, it must be `sig`. - The comparison of the algorithm name is exact. - An ES256 signature must be 64 bytes long. - A token that has a `crit` header is not valid. A key or a signature that OpenSSL cannot use gives the result for a token that is not valid. A JWKS response that is not JSON, or that has no `keys` array, gives the same result. The SDK does not put such a response in the cache. An unknown `kid` causes a new JWKS request, but not more than one in 30 seconds. If that request fails, the SDK continues to use the cached keys. This commit is the 9.5.x version of the change on the main branch. The dependency ranges do not change on this line. The new tests make their keys at test time. They cover ES256 tokens, a JWKS with RSA and EC keys in the two sequences, keys of unknown types, algorithm confusion, ES256 signatures of an incorrect length, unknown key IDs, JWKS requests that fail, and JWKS responses that are not JSON. The algorithm confusion tests also use keys that have no `alg` member. --- lib/workos/session_manager.rb | 189 ++++++++- test/workos/test_session.rb | 720 ++++++++++++++++++++++++++++++++++ 2 files changed, 897 insertions(+), 12 deletions(-) diff --git a/lib/workos/session_manager.rb b/lib/workos/session_manager.rb index 64bbaa53..afdb1039 100644 --- a/lib/workos/session_manager.rb +++ b/lib/workos/session_manager.rb @@ -14,6 +14,7 @@ require "json" require "jwt" +require "openssl" module WorkOS # Manages sealed-session lifecycle: loading, authenticating, refreshing, @@ -33,7 +34,36 @@ module WorkOS # cookie_password: ENV["COOKIE_PASSWORD"] # ) class SessionManager - JWK_ALGORITHMS = ["RS256"].freeze + # The signature algorithms that the SDK accepts for an access token. + # The list is fixed. The SDK does not take it from the token, from the + # JWKS or from the caller. + JWK_ALGORITHMS = ["RS256", "ES256"].freeze + + # The key type, and for an EC key the curve, that each algorithm uses. + JWK_ALGORITHM_KEYS = { + "RS256" => {"kty" => "RSA"}.freeze, + "ES256" => {"kty" => "EC", "crv" => "P-256"}.freeze + }.freeze + + # The public members that the SDK reads from a key of each type. + JWK_PUBLIC_MEMBERS = { + "RSA" => ["n", "e"].freeze, + "EC" => ["crv", "x", "y"].freeze + }.freeze + + # A JWS ES256 signature is r || s: two integers of 32 bytes each + # (RFC 7518, section 3.4). + ES256_SIGNATURE_BYTES = 64 + + # Seconds that the SDK keeps a JWKS before it gets a new one. + JWKS_CACHE_TTL = 300 + + # Minimum seconds between a JWKS request and the subsequent JWKS request + # that an unknown key ID causes. + JWKS_REFETCH_COOLDOWN = 30 + + private_constant :JWK_ALGORITHM_KEYS, :JWK_PUBLIC_MEMBERS, :ES256_SIGNATURE_BYTES, + :JWKS_CACHE_TTL, :JWKS_REFETCH_COOLDOWN # H04 success / failure shapes — kept minimal & frozen. class AuthSuccess @@ -126,6 +156,7 @@ def initialize(client, encryptor: nil) @encryptor = encryptor || Encryptors::AesGcm.new @jwks_cache = nil @jwks_cache_at = nil + @jwks_requested_at = nil @jwks_mutex = Mutex.new end @@ -174,6 +205,13 @@ def seal_session_from_auth_response(access_token:, refresh_token:, cookie_passwo # Verify an access-token JWT against the WorkOS JWKS for this client. # Used by Session#authenticate; exposed publicly for advanced cases. # + # The token must use RS256 or ES256 ({JWK_ALGORITHMS}). The `kid` header + # of the token selects the JWKS key. That key must be an RSA key for + # RS256 and an EC P-256 key for ES256. The SDK ignores all other keys in + # the JWKS, also keys of a type that it does not know. A token that has a + # `crit` header is not valid, because the SDK implements no header + # extension (RFC 7515, section 4.1.11). + # # NOTE on iss/aud/required_claims: this method intentionally does not # enforce iss, aud, or required_claims. workos-node's `jose` call and # workos-php's `isset($exp) && $exp < time()` accept exp-less tokens, and @@ -182,19 +220,98 @@ def seal_session_from_auth_response(access_token:, refresh_token:, cookie_passwo # required_claims: ['exp'] tightening that was considered here. def decode_jwt(access_token, verify_expiration: true) jwks = fetch_jwks - JWT.decode( - access_token, - nil, - true, + options = { algorithms: JWK_ALGORITHMS, - jwks: jwks, verify_aud: false, verify_expiration: verify_expiration - ).first + } + verify_jwt(access_token, options, jwks) end private + # Verify the signature and the claims of a token. Return the claims. + def verify_jwt(access_token, options, jwks) + # The block gives ruby-jwt the one key that can verify this token. + # ruby-jwt then verifies the signature and the claims. + claims, _header = JWT.decode(access_token, nil, true, options) do |header| + verification_key(header, access_token, jwks) + end + claims + rescue OpenSSL::OpenSSLError => e + # ruby-jwt does not catch all OpenSSL errors. A key or a signature that + # OpenSSL cannot use makes the token not valid. + raise JWT::DecodeError, "Could not verify the token (#{e.class})" + end + + # Give the public key that can verify a token. ruby-jwt calls this method + # with the header of the token before it verifies the signature, so the + # header is not trusted data. Each failure raises a JWT::DecodeError, + # which Session#authenticate reports as a token that is not valid. + def verification_key(header, access_token, jwks) + raise JWT::DecodeError, "Token header not a JSON object" unless header.is_a?(Hash) + # The SDK implements no header extension, so it cannot obey a `crit` + # header (RFC 7515, section 4.1.11). + raise JWT::DecodeError, "Unsupported critical header parameter (crit)" if header.key?("crit") + + algorithm = header["alg"] + # ruby-jwt compares algorithm names without case. This comparison is exact. + raise JWT::IncorrectAlgorithm, "Expected a different algorithm" unless JWK_ALGORITHMS.include?(algorithm) + + kid = header["kid"] + raise JWT::DecodeError, "No key id (kid) found from token headers" unless kid.is_a?(String) && !kid.empty? + + key = import_jwk(find_jwk(jwks, kid, algorithm)) + + # ruby-jwt reads the first 32 bytes of an ES256 signature as r and all + # subsequent bytes as s, so it also accepts some signatures that are + # not 64 bytes long. + if algorithm == "ES256" && JWT::EncodedToken.new(access_token).signature.bytesize != ES256_SIGNATURE_BYTES + raise JWT::VerificationError, "Signature verification failed" + end + + key + end + + # Find the JWKS key that has this key ID and can verify this algorithm. + # + # If no cached key has the key ID, the key can be newer than the cache. + # The SDK then gets the JWKS again (see #refetch_jwks). + def find_jwk(jwks, kid, algorithm) + with_kid = ->(key_set) { key_set["keys"].select { |jwk| jwk["kid"] == kid } } + keys = with_kid.call(jwks) + keys = with_kid.call(refetch_jwks) if keys.empty? + raise JWT::DecodeError, "Could not find public key for kid #{kid}" if keys.empty? + + keys.find { |jwk| jwk_for_algorithm?(jwk, algorithm) } || + raise(JWT::DecodeError, "The public key for kid #{kid} cannot verify #{algorithm}") + end + + # Each algorithm is bound to one key type: RS256 to an RSA key and ES256 + # to an EC P-256 key. If the key has an `alg` member, it must be the + # algorithm of the token. If the key has a `use` member, it must be `sig`. + # ruby-jwt does not do all these checks in all its versions. + def jwk_for_algorithm?(jwk, algorithm) + JWK_ALGORITHM_KEYS.fetch(algorithm).all? { |member, value| jwk[member] == value } && + [nil, algorithm].include?(jwk["alg"]) && + [nil, "sig"].include?(jwk["use"]) + end + + # Make an OpenSSL public key from the public members of a JWK. The SDK + # reads no other member, so a member that it does not use cannot make the + # key fail. A key that is not correct raises a JWT::JWKError, which is a + # JWT::DecodeError. + def import_jwk(jwk) + members = JWK_PUBLIC_MEMBERS.fetch(jwk["kty"]) + raise JWT::JWKError, "Key format is invalid for #{jwk["kty"]}" unless members.all? { |member| jwk[member].is_a?(String) } + + JWT::JWK.import(jwk.slice("kty", "kid", *members)).verify_key + rescue OpenSSL::OpenSSLError + # ruby-jwt before 3.3.1 does not catch the OpenSSL error for some keys + # that are not correct (for example an EC point that is not on the curve). + raise JWT::JWKError, "Key format is invalid for #{jwk["kty"]}" + end + # Validate a cookie_password is non-empty and at least the minimum # byte length required by Session::MIN_COOKIE_PASSWORD_BYTES (32). # Defense-in-depth — Session#initialize enforces the same invariant @@ -208,12 +325,60 @@ def validate_cookie_password!(key) # Cached JWKS fetch (5-minute TTL, thread-safe). def fetch_jwks(now: Time.now) @jwks_mutex.synchronize do - return @jwks_cache if @jwks_cache && @jwks_cache_at && (now - @jwks_cache_at) < 300 - response = @client.user_management.get_jwks(client_id: @client.client_id) - @jwks_cache = {"keys" => response.keys.map(&:to_h)} - @jwks_cache_at = now - @jwks_cache + return @jwks_cache if @jwks_cache && @jwks_cache_at && (now - @jwks_cache_at) < JWKS_CACHE_TTL + + request_jwks(now) + end + end + + # Get the JWKS again because a token names a key ID that the cache does + # not have. The SDK does this only if the last JWKS request is older than + # the cooldown. Thus unknown key IDs cannot cause a JWKS request for each + # token. If the request fails, the SDK continues to use the cached keys. + def refetch_jwks(now: Time.now) + @jwks_mutex.synchronize do + return request_jwks(now) unless @jwks_cache + return @jwks_cache if (now - @jwks_requested_at) < JWKS_REFETCH_COOLDOWN + + begin + request_jwks(now) + rescue + @jwks_cache + end + end + end + + # Get the JWKS from the API and put it in the cache. Call this method + # only while the thread holds the mutex. + # + # The SDK reads the JWKS as raw JSON. The generated JwksResponse model + # has only the members of an RSA key, so it cannot hold other key types. + # The cache keeps each key as the API sent it. A key that the SDK cannot + # use is not an error: only a token that names such a key is not valid. + # + # A response body that is not a JWKS document raises a JWT::JWKError, + # which is a JWT::DecodeError. A request that fails raises the error + # that the client gives for it (for example WorkOS::APIError). + def request_jwks(now) + @jwks_requested_at = now + response = @client.request( + method: :get, + path: "/sso/jwks/#{WorkOS::Util.encode_path(@client.client_id)}", + auth: true + ) + document = begin + JSON.parse(response.body.to_s) + rescue JSON::ParserError + # A body that is not JSON has no keys array. + nil end + keys = document["keys"] if document.is_a?(Hash) + # The SDK does not put this response in the cache, so the subsequent + # token causes a new request. + raise JWT::JWKError, "The JWKS response has no keys array" unless keys.is_a?(Array) + + @jwks_cache_at = now + @jwks_cache = {"keys" => keys.grep(Hash)} end end end diff --git a/test/workos/test_session.rb b/test/workos/test_session.rb index 25bfc134..e239a65a 100644 --- a/test/workos/test_session.rb +++ b/test/workos/test_session.rb @@ -426,6 +426,726 @@ def test_refresh_persists_seal_data_even_when_access_token_decode_fails assert_equal session.seal_data, result.sealed_session end + # --- JWT algorithms and JWKS keys ----------------------------------------- + # + # The SDK accepts RS256 and ES256 tokens. The `kid` header selects the JWKS + # key. The SDK ignores the keys that it cannot use. + + JWKS_URL = "https://api.workos.com/sso/jwks/client_001" + + INVALID_TOKEN_REASONS = [ + WorkOS::SessionManager::INVALID_JWT, + WorkOS::SessionManager::INVALID_JWT_ALGORITHM, + WorkOS::SessionManager::INVALID_JWT_SIGNATURE + ].freeze + + # Throwaway keys for the tests below. The test run makes them one time. + def self.jwks_keys + @jwks_keys ||= { + rsa: OpenSSL::PKey::RSA.generate(2048), + other_rsa: OpenSSL::PKey::RSA.generate(2048), + ec: OpenSSL::PKey::EC.generate("prime256v1"), + other_ec: OpenSSL::PKey::EC.generate("prime256v1"), + p384: OpenSSL::PKey::EC.generate("secp384r1") + }.freeze + end + + def jwks_key(name) + self.class.jwks_keys.fetch(name) + end + + def b64url(bytes) + Base64.urlsafe_encode64(bytes, padding: false) + end + + def user_claims(claims = {}) + {"sid" => "session_42", "auth_time" => Time.now.to_i, "exp" => Time.now.to_i + 60}.merge(claims) + end + + # An RSA key in the shape that the WorkOS JWKS has today. + def rsa_jwk(key = jwks_key(:rsa), kid: "rsa-1") + der = key.public_key.to_der + { + "kty" => "RSA", "alg" => "RS256", "use" => "sig", "kid" => kid, + "n" => b64url(key.n.to_s(2)), "e" => b64url(key.e.to_s(2)), + # The SDK does not read the next two members, so they are not a real certificate. + "x5c" => [Base64.strict_encode64(der)], + "x5t#S256" => b64url(OpenSSL::Digest.digest("SHA256", der)) + } + end + + def ec_jwk(key = jwks_key(:ec), kid: "ec-1", crv: "P-256", alg: "ES256") + point = key.public_key.to_octet_string(:uncompressed) + size = (point.bytesize - 1) / 2 + { + "kty" => "EC", "crv" => crv, "alg" => alg, "use" => "sig", "kid" => kid, + "x" => b64url(point[1, size]), "y" => b64url(point[1 + size, size]) + } + end + + def p384_jwk + ec_jwk(jwks_key(:p384), kid: "p384-1", crv: "P-384", alg: "ES384") + end + + # Keys of types that the SDK cannot use: Ed25519, ML-DSA and a type that does not exist. + def unusable_jwks + [ + {"kty" => "OKP", "crv" => "Ed25519", "alg" => "EdDSA", "use" => "sig", "kid" => "okp-1", "x" => b64url(SecureRandom.random_bytes(32))}, + {"kty" => "AKP", "alg" => "ML-DSA-65", "use" => "sig", "kid" => "akp-1", "pub" => b64url(SecureRandom.random_bytes(1952))}, + {"kty" => "FUTURE", "alg" => "FUTURE512", "kid" => "future-1", "x" => false, "params" => {"a" => [1, 2, 3]}} + ] + end + + def rs256_jwt(key = jwks_key(:rsa), kid: "rsa-1", claims: user_claims, header: {}) + JWT.encode(claims, key, "RS256", {kid: kid}.merge(header)) + end + + def es256_jwt(key = jwks_key(:ec), kid: "ec-1", claims: user_claims, header: {}) + JWT.encode(claims, key, "ES256", {kid: kid}.merge(header)) + end + + # Build a token from a header and the signature that the block gives for the signing input. + def craft_jwt(header, claims = user_claims) + input = [header, claims].map { |part| b64url(JSON.generate(part)) }.join(".") + "#{input}.#{b64url(yield(input))}" + end + + # The signature that OpenSSL makes with SHA-256. For an EC key, it is in the DER form. + def openssl_signature(key, input) + key.sign(OpenSSL::Digest.new("SHA256"), input) + end + + # r and s of an ECDSA signature with SHA-256, each as a string of `size` bytes. + def ecdsa_r_and_s(key, input, size: 32) + der = openssl_signature(key, input) + OpenSSL::ASN1.decode(der).value.map { |integer| integer.value.to_s(2).rjust(size, "\x00".b) } + end + + def stub_jwks(keys) + stub_request(:get, JWKS_URL).to_return(status: 200, body: {"keys" => keys}.to_json) + end + + def authenticate_access_token(access_token, session_manager: @sm) + sealed = session_manager.seal_data({"access_token" => access_token}, PASSWORD) + session_manager.authenticate(seal_data: sealed, cookie_password: PASSWORD) + end + + def assert_authenticated(result) + assert_kind_of WorkOS::SessionManager::AuthSuccess, result + assert result.authenticated + assert_equal "session_42", result.session_id + end + + # The token is not valid: the result is an AuthError, and no exception escapes. + # If `reason` is nil, each reason for a token that is not valid is correct. + def assert_invalid_token(reason, result, message = nil) + assert_kind_of WorkOS::SessionManager::AuthError, result, message + refute result.authenticated, message + if reason + assert_equal reason, result.reason, message + else + assert_includes INVALID_TOKEN_REASONS, result.reason, message + end + end + + def test_jwk_algorithms_is_a_fixed_list_of_rs256_and_es256 + assert_equal ["RS256", "ES256"], WorkOS::SessionManager::JWK_ALGORITHMS + assert_predicate WorkOS::SessionManager::JWK_ALGORITHMS, :frozen? + end + + def test_authenticate_accepts_es256_token + stub = stub_jwks([ec_jwk]) + assert_authenticated authenticate_access_token(es256_jwt) + assert_requested(stub, times: 1) + assert_requested(:get, JWKS_URL, headers: {"User-Agent" => WorkOS::BaseClient::USER_AGENT}) + end + + def test_decode_jwt_returns_claims_of_es256_token + stub_jwks([rsa_jwk, ec_jwk]) + assert_equal "session_42", @sm.decode_jwt(es256_jwt)["sid"] + assert_equal "session_42", @sm.decode_jwt(rs256_jwt)["sid"] + end + + { + "rsa_then_ec" => ->(rsa, ec) { [rsa, ec] }, + "ec_then_rsa" => ->(rsa, ec) { [ec, rsa] } + }.each do |order, keys| + define_method(:"test_authenticate_accepts_rs256_token_with_mixed_jwks_#{order}") do + stub_jwks(keys.call(rsa_jwk, ec_jwk)) + assert_authenticated authenticate_access_token(rs256_jwt) + end + + define_method(:"test_authenticate_accepts_es256_token_with_mixed_jwks_#{order}") do + stub_jwks(keys.call(rsa_jwk, ec_jwk)) + assert_authenticated authenticate_access_token(es256_jwt) + end + + define_method(:"test_authenticate_selects_key_by_algorithm_when_keys_share_a_kid_#{order}") do + stub_jwks(keys.call(rsa_jwk(kid: "shared"), ec_jwk(kid: "shared"))) + assert_authenticated authenticate_access_token(rs256_jwt(kid: "shared")) + assert_authenticated authenticate_access_token(es256_jwt(kid: "shared")) + end + end + + def test_authenticate_ignores_okp_akp_and_unknown_key_types_in_jwks + stub = stub_jwks(unusable_jwks + [rsa_jwk, ec_jwk]) + assert_authenticated authenticate_access_token(rs256_jwt) + assert_authenticated authenticate_access_token(es256_jwt) + + # A token cannot use one of these keys. + token = craft_jwt({"alg" => "ES256", "kid" => "okp-1"}) { |input| ecdsa_r_and_s(jwks_key(:ec), input).join } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + token = craft_jwt({"alg" => "EdDSA", "kid" => "okp-1"}) { SecureRandom.random_bytes(64) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token) + token = craft_jwt({"alg" => "ML-DSA-65", "kid" => "akp-1"}) { SecureRandom.random_bytes(3309) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token) + + assert_requested(stub, times: 1) + end + + def test_authenticate_ignores_keys_that_it_cannot_use_when_a_token_does_not_name_them + stub_jwks([ + nil, "a string", 5, ["an", "array"], + {"kty" => "RSA", "n" => "no kid", "e" => "AQAB"}, + {"kty" => "RSA", "kid" => "rsa-not-base64", "n" => "!!!", "e" => 65537}, + ec_jwk.merge("kid" => "ec-not-on-curve", "y" => b64url(SecureRandom.random_bytes(32))), + ec_jwk.merge("kid" => "ec-x-is-a-number", "x" => 5), + ec_jwk.merge("kid" => "ec-no-coordinates").except("x", "y"), + p384_jwk, + rsa_jwk(jwks_key(:other_rsa), kid: "rsa-enc").merge("use" => "enc", "alg" => "RSA-OAEP"), + rsa_jwk, + ec_jwk + ]) + assert_authenticated authenticate_access_token(rs256_jwt) + assert_authenticated authenticate_access_token(es256_jwt) + end + + def test_authenticate_accepts_rs256_token_when_rsa_key_has_no_x5c_and_x5t + stub_jwks([rsa_jwk.except("x5c", "x5t#S256"), ec_jwk]) + assert_authenticated authenticate_access_token(rs256_jwt) + end + + def test_authenticate_accepts_keys_that_have_only_the_necessary_members + stub_jwks([rsa_jwk.slice("kty", "kid", "n", "e"), ec_jwk.slice("kty", "kid", "crv", "x", "y")]) + assert_authenticated authenticate_access_token(rs256_jwt) + assert_authenticated authenticate_access_token(es256_jwt) + end + + def test_authenticate_rejects_rs256_header_when_kid_names_ec_key + stub_jwks([rsa_jwk, ec_jwk]) + + # Signed with the RSA key, but the key ID is that of the EC key. + result = authenticate_access_token(rs256_jwt(kid: "ec-1")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result + + # Signed with the EC key in the DER form. OpenSSL accepts this signature + # if the caller does not make sure that an RS256 key is an RSA key. + token = craft_jwt({"alg" => "RS256", "kid" => "ec-1"}) { |input| openssl_signature(jwks_key(:ec), input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + + # Signed with the EC key in the raw form. + token = craft_jwt({"alg" => "RS256", "kid" => "ec-1"}) { |input| ecdsa_r_and_s(jwks_key(:ec), input).join } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + end + + def test_authenticate_rejects_es256_header_when_kid_names_rsa_key + stub_jwks([rsa_jwk, ec_jwk]) + + # Signed with the EC key, but the key ID is that of the RSA key. + result = authenticate_access_token(es256_jwt(kid: "rsa-1")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result + + # Signed with the RSA key. + token = craft_jwt({"alg" => "ES256", "kid" => "rsa-1"}) { |input| openssl_signature(jwks_key(:rsa), input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + end + + # The keys of the two tests above have an `alg` member, so that member also + # rejects their tokens. The keys of the two tests below have no `alg` member, + # or an `alg` member that agrees with the token. Thus only the key type and + # the curve can reject the tokens of this method. + def assert_rejects_tokens_for_a_key_of_a_different_type + # An RS256 header with the key ID of an EC key, signed with that EC key in the DER form. + {"ec-1" => :ec, "p384-1" => :p384}.each do |kid, name| + token = craft_jwt({"alg" => "RS256", "kid" => kid}) { |input| openssl_signature(jwks_key(name), input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), kid + end + + # An ES256 header with the key ID of the RSA key, signed with that RSA key. + token = craft_jwt({"alg" => "ES256", "kid" => "rsa-1"}) { |input| openssl_signature(jwks_key(:rsa), input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + + # An ES256 header with the key ID of the P-384 key, signed with that key and with the P-256 key. + token = craft_jwt({"alg" => "ES256", "kid" => "p384-1"}) do |input| + ecdsa_r_and_s(jwks_key(:p384), input, size: 48).join + end + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt(kid: "p384-1")) + end + + def test_authenticate_binds_the_algorithm_to_the_key_type_when_keys_have_no_alg_member + stub_jwks([rsa_jwk.except("alg"), ec_jwk.except("alg"), p384_jwk.except("alg")]) + + assert_authenticated authenticate_access_token(rs256_jwt) + assert_authenticated authenticate_access_token(es256_jwt) + assert_rejects_tokens_for_a_key_of_a_different_type + end + + def test_authenticate_binds_the_algorithm_to_the_key_type_when_alg_member_of_key_agrees_with_the_token + stub_jwks([rsa_jwk.merge("alg" => "ES256"), ec_jwk.merge("alg" => "RS256"), p384_jwk.merge("alg" => "ES256")]) + + assert_rejects_tokens_for_a_key_of_a_different_type + end + + def test_authenticate_rejects_hs256_token_signed_with_public_key_as_secret + stub_jwks([rsa_jwk, ec_jwk]) + rsa_public = jwks_key(:rsa).public_key + ec_point = jwks_key(:ec).public_key.to_octet_string(:uncompressed) + secrets = { + "rsa-1" => [rsa_public.to_pem, rsa_public.to_der, rsa_public.n.to_s(2), rsa_jwk["n"]], + "ec-1" => [jwks_key(:ec).public_to_pem, jwks_key(:ec).public_to_der, ec_point, ec_jwk["x"]] + } + + secrets.each do |kid, public_key_bytes| + public_key_bytes.each do |secret| + ["HS256", "HS384", "HS512"].each do |alg| + token = craft_jwt({"alg" => alg, "kid" => kid}) do |input| + OpenSSL::HMAC.digest(alg.sub("HS", "SHA"), secret, input) + end + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token) + end + end + end + end + + def test_authenticate_rejects_alg_none + stub_jwks([rsa_jwk, ec_jwk]) + signature = rs256_jwt.split(".").last + + ["none", "None", "NONE", "nOnE"].each do |alg| + ["rsa-1", "ec-1"].each do |kid| + token = craft_jwt({"alg" => alg, "kid" => kid}) { "" } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), alg + + # The same token without the last period, and with the signature of a different token. + assert_invalid_token nil, authenticate_access_token(token.delete_suffix(".")), alg + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token + signature), alg + end + end + end + + def test_authenticate_rejects_algorithms_that_are_not_in_the_allow_list + stub_jwks([rsa_jwk, ec_jwk, p384_jwk]) + tokens = { + "RS384" => JWT.encode(user_claims, jwks_key(:rsa), "RS384", {kid: "rsa-1"}), + "RS512" => JWT.encode(user_claims, jwks_key(:rsa), "RS512", {kid: "rsa-1"}), + "PS256" => JWT.encode(user_claims, jwks_key(:rsa), "PS256", {kid: "rsa-1"}), + "ES384" => JWT.encode(user_claims, jwks_key(:p384), "ES384", {kid: "p384-1"}) + } + + tokens.each do |alg, token| + assert_equal alg, JSON.parse(Base64.urlsafe_decode64(token.split(".").first))["alg"] + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), alg + end + end + + def test_authenticate_compares_the_algorithm_name_exactly + stub_jwks([rsa_jwk, ec_jwk]) + + # Each token has a correct signature. Only the algorithm name is not correct. + ["rs256", "Rs256", "RS256 ", " RS256", ["RS256"], {"alg" => "RS256"}, 256, true, nil].each do |alg| + token = craft_jwt({"alg" => alg, "kid" => "rsa-1"}) { |input| openssl_signature(jwks_key(:rsa), input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), alg.inspect + end + + ["es256", "Es256", "ES256 ", ["ES256"]].each do |alg| + token = craft_jwt({"alg" => alg, "kid" => "ec-1"}) { |input| ecdsa_r_and_s(jwks_key(:ec), input).join } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), alg.inspect + end + + # A header that has no `alg` member. + token = craft_jwt({"kid" => "rsa-1"}) { |input| openssl_signature(jwks_key(:rsa), input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token) + end + + def test_authenticate_rejects_token_that_has_a_crit_header + stub_jwks([rsa_jwk, ec_jwk]) + extension = {:crit => ["urn:example:extension"], "urn:example:extension" => true} + + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(header: extension)) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt(header: extension)) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(header: {crit: []})) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt(header: {crit: ["b64"], b64: false})) + end + + def test_authenticate_rejects_es256_token_when_kid_names_p384_key + stub_jwks([rsa_jwk, ec_jwk, p384_jwk]) + + # A correct ES256 signature from a different key, with the key ID of the P-384 key. + result = authenticate_access_token(es256_jwt(kid: "p384-1")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result + + # Signed with the P-384 key. That signature is 96 bytes long. + token = craft_jwt({"alg" => "ES256", "kid" => "p384-1"}) do |input| + ecdsa_r_and_s(jwks_key(:p384), input, size: 48).join + end + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + end + + def test_authenticate_rejects_es256_token_when_p384_key_has_p256_label + stub_jwks([rsa_jwk, ec_jwk(jwks_key(:p384), kid: "p384-1", crv: "P-256", alg: "ES256")]) + + token = craft_jwt({"alg" => "ES256", "kid" => "p384-1"}) do |input| + ecdsa_r_and_s(jwks_key(:p384), input, size: 48).join + end + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt(kid: "p384-1")) + end + + def test_authenticate_rejects_token_when_alg_member_of_key_is_a_different_algorithm + stub_jwks([ + rsa_jwk.merge("alg" => "PS256"), + ec_jwk.merge("alg" => "ES384"), + rsa_jwk(jwks_key(:other_rsa), kid: "rsa-2").merge("alg" => "ES256"), + ec_jwk(jwks_key(:other_ec), kid: "ec-2").merge("alg" => "RS256"), + rsa_jwk(jwks_key(:other_rsa), kid: "rsa-3").merge("alg" => "rs256"), + ec_jwk(jwks_key(:other_ec), kid: "ec-3").merge("alg" => "es256") + ]) + + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt) + ["rsa-2", "rsa-3"].each do |kid| + result = authenticate_access_token(rs256_jwt(jwks_key(:other_rsa), kid: kid)) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result, kid + end + ["ec-2", "ec-3"].each do |kid| + result = authenticate_access_token(es256_jwt(jwks_key(:other_ec), kid: kid)) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result, kid + end + end + + def test_authenticate_rejects_token_when_use_member_of_key_is_not_sig + stub_jwks([rsa_jwk.merge("use" => "enc"), ec_jwk.merge("use" => "enc")]) + + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt) + end + + def test_authenticate_rejects_token_when_the_selected_key_is_not_correct + zero = b64url("\x00".b * 32) + stub_jwks([ + ec_jwk.merge("kid" => "ec-not-on-curve", "y" => b64url(SecureRandom.random_bytes(32))), + ec_jwk.merge("kid" => "ec-zero-point", "x" => zero, "y" => zero), + ec_jwk.merge("kid" => "ec-short-x", "x" => b64url(Base64.urlsafe_decode64(ec_jwk["x"])[0, 31])), + ec_jwk.merge("kid" => "ec-x-is-a-number", "x" => 5), + ec_jwk.merge("kid" => "ec-not-base64", "x" => "!!!"), + ec_jwk.merge("kid" => "ec-no-coordinates").except("x", "y"), + rsa_jwk.merge("kid" => "rsa-not-base64", "n" => "!!!"), + rsa_jwk.merge("kid" => "rsa-e-is-a-number", "e" => 65537), + rsa_jwk.merge("kid" => "rsa-no-modulus").except("n"), + rsa_jwk.merge("kid" => "rsa-empty-modulus", "n" => "") + ]) + + ["ec-not-on-curve", "ec-zero-point", "ec-short-x", "ec-x-is-a-number", "ec-not-base64", "ec-no-coordinates"].each do |kid| + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt(kid: kid)), kid + assert_raises(JWT::DecodeError, kid) { @sm.decode_jwt(es256_jwt(kid: kid)) } + end + ["rsa-not-base64", "rsa-e-is-a-number", "rsa-no-modulus"].each do |kid| + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(kid: kid)), kid + end + # OpenSSL makes a key from an empty modulus on some versions and not on others. + assert_invalid_token nil, authenticate_access_token(rs256_jwt(kid: "rsa-empty-modulus")) + end + + def test_authenticate_rejects_unknown_kid + stub = stub_jwks([rsa_jwk, ec_jwk]) + + result = authenticate_access_token(rs256_jwt(jwks_key(:other_rsa), kid: "rsa-unknown")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result + result = authenticate_access_token(es256_jwt(jwks_key(:other_ec), kid: "ec-unknown")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result + # The key signed the token, but the key ID is not that of the key. + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(kid: "rsa-unknown")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt(kid: "ec-unknown")) + + # The cache is new, so the unknown key IDs do not cause a second request. + assert_requested(stub, times: 1) + end + + def test_authenticate_rejects_token_when_jwks_has_no_keys + stub_jwks([]) + + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt) + end + + def test_authenticate_rejects_token_without_a_string_kid + stub_jwks([rsa_jwk, ec_jwk, rsa_jwk(kid: ""), ec_jwk(kid: "").except("kid")]) + + [nil, "", 1, ["ec-1"], {"kid" => "ec-1"}].each do |kid| + header = {"alg" => "ES256", "kid" => kid}.compact + token = craft_jwt(header) { |input| ecdsa_r_and_s(jwks_key(:ec), input).join } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), kid.inspect + + header = {"alg" => "RS256", "kid" => kid}.compact + token = craft_jwt(header) { |input| openssl_signature(jwks_key(:rsa), input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), kid.inspect + end + end + + def test_authenticate_rejects_token_signed_with_a_different_key_that_has_the_same_kid + stub_jwks([rsa_jwk, ec_jwk]) + + result = authenticate_access_token(rs256_jwt(jwks_key(:other_rsa))) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, result + result = authenticate_access_token(es256_jwt(jwks_key(:other_ec))) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, result + end + + def test_authenticate_rejects_es256_token_when_the_signature_is_changed + stub_jwks([rsa_jwk, ec_jwk]) + header, payload, signature = es256_jwt.split(".") + bytes = Base64.urlsafe_decode64(signature) + + [0, 31, 32, 63].each do |index| + changed = bytes.dup + changed.setbyte(index, changed.getbyte(index) ^ 0x01) + result = authenticate_access_token([header, payload, b64url(changed)].join(".")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, result, "byte #{index}" + end + + # r and s in the opposite sequence. + result = authenticate_access_token([header, payload, b64url(bytes[32, 32] + bytes[0, 32])].join(".")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, result + + # The same signature on different claims. + other_payload = b64url(JSON.generate(user_claims("sid" => "session_43"))) + result = authenticate_access_token([header, other_payload, signature].join(".")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, result + end + + def test_authenticate_accepts_es256_signature_only_in_the_raw_form_of_64_bytes + stub_jwks([rsa_jwk, ec_jwk]) + header = {"alg" => "ES256", "kid" => "ec-1"} + r = s = der = nil + correct = craft_jwt(header) do |input| + der = jwks_key(:ec).sign(OpenSSL::Digest.new("SHA256"), input) + r, s = OpenSSL::ASN1.decode(der).value.map { |integer| integer.value.to_s(2).rjust(32, "\x00".b) } + r + s + end + assert_authenticated authenticate_access_token(correct) + + zero = "\x00".b + signatures = { + "empty" => "", + "63 bytes" => (r + s)[0, 63], + "65 bytes, one more byte at the end" => r + s + zero, + "65 bytes, one zero byte before r" => zero + r + s, + # ruby-jwt reads these bytes as the same r and s, and thus accepts this signature. + "65 bytes, one zero byte before s" => r + zero + s, + "66 bytes" => zero + r + zero + s, + "128 bytes" => r + s + r + s, + "DER" => der + } + signatures.each do |name, signature| + token = craft_jwt(header) { signature } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, authenticate_access_token(token), name + end + end + + def test_authenticate_rejects_es256_signature_of_63_bytes_when_s_starts_with_a_zero_byte + stub_jwks([rsa_jwk, ec_jwk]) + header = {"alg" => "ES256", "kid" => "ec-1"} + input = [header, user_claims].map { |part| b64url(JSON.generate(part)) }.join(".") + + # ECDSA signatures are random. Sign again until s starts with a zero byte (1 in 256). + r, s = ecdsa_r_and_s(jwks_key(:ec), input) + 100_000.times do + break if s.getbyte(0).zero? + + r, s = ecdsa_r_and_s(jwks_key(:ec), input) + end + assert_equal 0, s.getbyte(0) + + assert_authenticated authenticate_access_token("#{input}.#{b64url(r + s)}") + + # Without its first byte, s is the same integer. ruby-jwt accepts this signature. + short = r + s[1, 31] + assert_equal 63, short.bytesize + result = authenticate_access_token("#{input}.#{b64url(short)}") + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, result + end + + def test_authenticate_gets_the_jwks_again_for_an_unknown_kid_when_the_cooldown_is_over + stub_jwks([rsa_jwk]) + # The cache is 31 seconds old. + @sm.send(:fetch_jwks, now: Time.now - 31) + assert_requested(:get, JWKS_URL, times: 1) + + # The API starts to use a new key. + stub_jwks([rsa_jwk, ec_jwk]) + assert_authenticated authenticate_access_token(es256_jwt) + assert_requested(:get, JWKS_URL, times: 2) + + # The last request is new, so one more unknown key ID does not cause a request. + result = authenticate_access_token(es256_jwt(jwks_key(:other_ec), kid: "ec-unknown")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result + assert_authenticated authenticate_access_token(rs256_jwt) + assert_requested(:get, JWKS_URL, times: 2) + end + + def test_authenticate_does_not_get_the_jwks_again_for_an_unknown_kid_during_the_cooldown + stub_jwks([rsa_jwk]) + # The cache is 10 seconds old. + @sm.send(:fetch_jwks, now: Time.now - 10) + + stub_jwks([rsa_jwk, ec_jwk]) + 3.times do + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt) + end + assert_requested(:get, JWKS_URL, times: 1) + end + + def test_refetch_jwks_uses_the_cooldown_and_fetch_jwks_uses_the_cache_ttl + kids = ->(jwks) { jwks["keys"].map { |jwk| jwk["kid"] } } + start = Time.now + stub_jwks([rsa_jwk]) + assert_equal ["rsa-1"], kids.call(@sm.send(:fetch_jwks, now: start)) + + stub_jwks([rsa_jwk, ec_jwk]) + assert_equal ["rsa-1"], kids.call(@sm.send(:refetch_jwks, now: start + 29)) + assert_requested(:get, JWKS_URL, times: 1) + assert_equal ["rsa-1", "ec-1"], kids.call(@sm.send(:refetch_jwks, now: start + 30)) + assert_requested(:get, JWKS_URL, times: 2) + + # The cache stays for 5 minutes after the last request. + assert_equal ["rsa-1", "ec-1"], kids.call(@sm.send(:fetch_jwks, now: start + 329)) + assert_requested(:get, JWKS_URL, times: 2) + assert_equal ["rsa-1", "ec-1"], kids.call(@sm.send(:fetch_jwks, now: start + 330)) + assert_requested(:get, JWKS_URL, times: 3) + end + + def test_authenticate_uses_the_cached_keys_when_the_jwks_request_for_an_unknown_kid_fails + failures = { + "status 503" => ->(stub) { stub.to_return(status: 503, body: {"message" => "unavailable"}.to_json) }, + "timeout" => ->(stub) { stub.to_timeout }, + "TLS error" => ->(stub) { stub.to_raise(OpenSSL::SSL::SSLError.new("handshake failure")) }, + "body that is not JSON" => ->(stub) { stub.to_return(status: 200, body: "maintenance") }, + "empty body" => ->(stub) { stub.to_return(status: 200, body: "") }, + "document without a keys array" => ->(stub) { stub.to_return(status: 200, body: {"keys" => "none"}.to_json) } + } + + failures.each do |name, failure| + WebMock.reset! + sm = WorkOS::Client.new(api_key: "sk_test_session", client_id: "client_001", max_retries: 0).session_manager + stub_jwks([rsa_jwk]) + # The cache is 31 seconds old. + sm.send(:fetch_jwks, now: Time.now - 31) + + failure.call(stub_request(:get, JWKS_URL)) + 2.times do + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt, session_manager: sm), name + end + assert_authenticated authenticate_access_token(rs256_jwt, session_manager: sm) + # The request that failed starts a new cooldown. + assert_requested(:get, JWKS_URL, times: 2) + end + end + + def test_authenticate_does_not_report_a_jwks_request_failure_as_a_token_that_is_not_valid + sm = WorkOS::Client.new(api_key: "sk_test_session", client_id: "client_001", max_retries: 0).session_manager + sealed = sm.seal_data({"access_token" => es256_jwt}, PASSWORD) + + stub_request(:get, JWKS_URL).to_return(status: 503, body: {"message" => "unavailable"}.to_json) + assert_raises(WorkOS::APIError) { sm.authenticate(seal_data: sealed, cookie_password: PASSWORD) } + + # A TLS failure of the JWKS request is an OpenSSL error, but it is not an error of the token. + stub_request(:get, JWKS_URL).to_raise(OpenSSL::SSL::SSLError.new("handshake failure")) + error = assert_raises(StandardError) { sm.authenticate(seal_data: sealed, cookie_password: PASSWORD) } + refute_kind_of JWT::DecodeError, error + + stub_jwks([ec_jwk]) + assert_authenticated sm.authenticate(seal_data: sealed, cookie_password: PASSWORD) + end + + def test_authenticate_rejects_token_and_does_not_cache_a_jwks_document_without_a_keys_array + [{"keys" => "not an array"}, {"keys" => {"kid" => "rsa-1"}}, {"keys" => nil}, {}, [], "keys", nil].each do |document| + WebMock.reset! + sm = WorkOS::Client.new(api_key: "sk_test_session", client_id: "client_001").session_manager + + stub_request(:get, JWKS_URL).to_return(status: 200, body: document.to_json) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt, session_manager: sm), document.inspect + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt, session_manager: sm), document.inspect + + stub_jwks([rsa_jwk, ec_jwk]) + assert_authenticated authenticate_access_token(rs256_jwt, session_manager: sm) + assert_authenticated authenticate_access_token(es256_jwt, session_manager: sm) + assert_requested(:get, JWKS_URL, times: 3) + end + end + + def test_authenticate_rejects_token_and_does_not_cache_a_jwks_response_that_is_not_json + document = {"keys" => [rsa_jwk, ec_jwk]}.to_json + responses = { + "HTML" => {status: 200, body: "maintenance"}, + "empty body" => {status: 200, body: ""}, + "no content" => {status: 204, body: nil}, + "JSON that is not complete" => {status: 200, body: document[0, document.size / 2]}, + "bytes that are not UTF-8" => {status: 200, body: "\xFF\xFE{".b}, + "too many levels" => {status: 200, body: ("[" * 200) + ("]" * 200)} + } + + responses.each do |name, response| + WebMock.reset! + sm = WorkOS::Client.new(api_key: "sk_test_session", client_id: "client_001").session_manager + + # The first JWKS request of this client gets the response. + stub_request(:get, JWKS_URL).to_return(response) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt, session_manager: sm), name + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt, session_manager: sm), name + assert_raises(JWT::DecodeError, name) { sm.decode_jwt(rs256_jwt) } + + stub_jwks([rsa_jwk, ec_jwk]) + assert_authenticated authenticate_access_token(rs256_jwt, session_manager: sm) + assert_authenticated authenticate_access_token(es256_jwt, session_manager: sm) + assert_requested(:get, JWKS_URL, times: 4) + end + end + + def test_authenticate_reads_keys_from_the_jwks_response_and_not_from_the_token + stub_jwks([rsa_jwk, ec_jwk]) + attacker = jwks_key(:other_ec) + header = {"alg" => "ES256", "kid" => "ec-1", "jwk" => ec_jwk(attacker), "jku" => "https://attacker.example/jwks"} + token = craft_jwt(header) { |input| ecdsa_r_and_s(attacker, input).join } + + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, authenticate_access_token(token) + assert_not_requested(:get, "https://attacker.example/jwks") + end + + def test_refresh_returns_refresh_success_for_es256_access_token + old_access = es256_jwt(claims: user_claims("sid" => "session_old", "exp" => Time.now.to_i - 60)) + sealed = @sm.seal_data({"access_token" => old_access, "refresh_token" => "rt_old", "user" => {"id" => "u_1"}}, PASSWORD) + new_access = es256_jwt(claims: user_claims("sid" => "session_new", "org_id" => "org_1")) + + stub_request(:post, "https://api.workos.com/user_management/authenticate") + .to_return(status: 200, body: {"access_token" => new_access, "refresh_token" => "rt_new", "user" => {"id" => "u_1"}}.to_json) + stub_jwks([rsa_jwk, ec_jwk]) + + result = @sm.load(seal_data: sealed, cookie_password: PASSWORD).refresh + assert_kind_of WorkOS::SessionManager::RefreshSuccess, result + assert result.authenticated + assert_equal "session_new", result.session_id + assert_equal "org_1", result.organization_id + assert_equal new_access, @sm.unseal_data(result.sealed_session, PASSWORD)["access_token"] + end + + def test_authenticate_returns_expired_jwt_for_expired_es256_token + stub_jwks([rsa_jwk, ec_jwk]) + token = es256_jwt(claims: user_claims("exp" => Time.now.to_i - 60)) + + assert_invalid_token WorkOS::SessionManager::EXPIRED_JWT, authenticate_access_token(token) + end + # --- Session constructor validation --------------------------------------- def test_session_load_requires_cookie_password From 2496d0afc75da872fa60e4769599377baeeac443 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 30 Nov 2026 21:16:03 -0500 Subject: [PATCH 2/2] ci: update ruby/setup-ruby in the lint workflow The Lint job reads the Ruby version from `.ruby-version`. The pinned release of ruby/setup-ruby cannot install that version on the current runner image. Thus the job stops before the lint step. This commit pins the release that the `main` branch uses. --- .github/workflows/lint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index ddc608c0..4e880705 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -16,7 +16,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # 6.0.3 - - uses: ruby/setup-ruby@12fd324f1d0b43274fdc8130f6980590a667c455 # 1.312.0 + - uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: bundler-cache: true