diff --git a/lib/workos/session_manager.rb b/lib/workos/session_manager.rb index 4a021172..f2e11058 100644 --- a/lib/workos/session_manager.rb +++ b/lib/workos/session_manager.rb @@ -34,27 +34,13 @@ module WorkOS # cookie_password: ENV["COOKIE_PASSWORD"] # ) class SessionManager - # 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. + # This list does not limit the signature algorithms that the SDK accepts. + # The SDK has no list of permitted algorithms: the JWKS key that a token + # names selects the algorithm (see {#decode_jwt}). The SDK does not read + # this constant. The constant stays because earlier versions made it + # public. 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 @@ -62,8 +48,7 @@ class SessionManager # 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 + private_constant :JWKS_CACHE_TTL, :JWKS_REFETCH_COOLDOWN # H04 success / failure shapes — kept minimal & frozen. class AuthSuccess @@ -204,10 +189,19 @@ 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 + # The SDK has no list of permitted signature algorithms. WorkOS selects + # the algorithm when it publishes a key in the JWKS. The `kid` header of + # the token selects the JWKS key. If that key has an `alg` member, the + # `alg` header of the token must be equal to it. The token must use an + # algorithm that ruby-jwt has for the type of the key. For an EC key, + # this is the one algorithm of its curve. The SDK accepts each such + # algorithm that ruby-jwt and OpenSSL can verify with that key. Thus a + # new algorithm needs a newer ruby-jwt or OpenSSL, and no change of the + # SDK. + # + # The SDK verifies a token only with a public key. An unsigned token and + # a token with a MAC are thus never valid. The SDK ignores all other keys + # in the JWKS, also keys that ruby-jwt cannot read. A token that has a # `crit` header is not valid, because the SDK implements no header # extension (RFC 7515, section 4.1.11). # @@ -223,7 +217,7 @@ def seal_session_from_auth_response(access_token:, refresh_token:, cookie_passwo def decode_jwt(access_token, verify_expiration: true) jwks = fetch_jwks options = { - algorithms: JWK_ALGORITHMS, + algorithms: token_algorithms(access_token), verify_aud: false, verify_expiration: verify_expiration } @@ -236,17 +230,39 @@ def decode_jwt(access_token, verify_expiration: true) private + # Give the ruby-jwt algorithm for the `alg` header of a token, as the + # list that ruby-jwt uses to verify the token. The SDK has no list of + # algorithm names: ruby-jwt finds the algorithm. + # + # The list is empty for an unsigned token and for a token with a MAC. The + # SDK verifies a token only with a public key. ruby-jwt then reports that + # the algorithm is not correct, and the SDK reads no key. + def token_algorithms(access_token) + # ruby-jwt reports a token that is not a String. + return [] unless access_token.is_a?(String) + + name = JWT::EncodedToken.new(access_token).header["alg"] + # ruby-jwt raises an ArgumentError for a name that has bytes that are + # not UTF-8. Such a name is not the name of an algorithm. + return [] if name.is_a?(String) && !name.valid_encoding? + + algorithm = JWT::JWA.find(name) + (algorithm.is_a?(JWT::JWA::None) || algorithm.is_a?(JWT::JWA::Hmac)) ? [] : [algorithm] + end + # 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) + verification_key(header, access_token, jwks, options[:algorithms]) 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. + rescue OpenSSL::OpenSSLError, ArgumentError => e + # ruby-jwt does not catch all OpenSSL errors. ruby-jwt raises an + # ArgumentError for a token that is not a String. An algorithm from an + # extension of ruby-jwt can raise an ArgumentError for a signature that + # it cannot read. Each of these errors makes the token not valid. raise JWT::DecodeError, "Could not verify the token (#{e.class})" end @@ -254,25 +270,26 @@ def verify_jwt(access_token, options, jwks) # 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) + def verification_key(header, access_token, jwks, algorithms) # 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) + algorithm = algorithms.find { |candidate| candidate.alg == header["alg"] } + raise JWT::IncorrectAlgorithm, "Expected a different algorithm" unless 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)) + key = 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 + # A JWS ECDSA signature is r || s: two integers that each have the byte + # length of the curve (RFC 7518, section 3.4). ruby-jwt reads the first + # bytes as r and all subsequent bytes as s, so it also accepts some + # signatures that do not have this length. + if key.is_a?(OpenSSL::PKey::EC) && + JWT::EncodedToken.new(access_token).signature.bytesize != 2 * ((key.group.degree + 7) / 8) raise JWT::VerificationError, "Signature verification failed" end @@ -280,6 +297,7 @@ def verification_key(header, access_token, jwks) end # Find the JWKS key that has this key ID and can verify this algorithm. + # Give its public key. # # 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). @@ -289,33 +307,57 @@ def find_jwk(jwks, kid, algorithm) 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}") + keys.lazy.filter_map { |jwk| import_jwk(jwk, algorithm) if jwk_for_algorithm?(jwk, algorithm) }.first || + raise(JWT::DecodeError, "The public key for kid #{kid} cannot verify #{algorithm.alg}") 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. + # 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 read + # these members, because the SDK gives it the key and not the JWK. 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"]) + [nil, algorithm.alg].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"]}" + # Make a public key from a JWKS key. Return nil if ruby-jwt cannot read + # the key, or if the key cannot verify this algorithm. + # + # ruby-jwt selects the key class from the `kty` member, so the SDK has no + # list of key types. The SDK makes the key only from the members that + # ruby-jwt reads for that key type. Thus a private member, or a member + # that the SDK does not use, cannot change the key. The SDK never uses a + # symmetric key. + def import_jwk(jwk, algorithm) + # ruby-jwt raises an EncodingError for a member name that has bytes that + # are not UTF-8. ruby-jwt reads no member with such a name, so the SDK + # does not give that member to ruby-jwt. + members = JWT::JWK.import(jwk.select { |name, _value| name.valid_encoding? }).members + public_jwk = JWT::JWK.import(members, kid: jwk["kid"]) + # ruby-jwt gets the key of each key class with the `verify_key` method. + # A key class from an extension of ruby-jwt can have no other method + # that gives the key. + key = public_jwk.verify_key if key_algorithm?(public_jwk, algorithm) + # The verification key of a symmetric key is the secret, which is a + # String. A public key is not a String. + key unless key.is_a?(String) + rescue + # ruby-jwt, the key class or OpenSSL cannot make a key from this JWKS + # key, so the SDK ignores the JWKS key. The SDK has no list of error + # classes, because a key class can raise an error of any class. For + # example, ruby-jwt raises a NoMethodError for a member that is not a + # String, and an ArgumentError for a String that is not UTF-8. A key + # class from an extension of ruby-jwt can have no `members` method. The + # SDK then cannot get the public members of the key. + nil + end + + # Tell if ruby-jwt has this algorithm for the type of the key. ruby-jwt + # gives the one algorithm of an EC key from the curve of the key. It + # gives no algorithm for an RSA key, because an RSA key can verify the + # algorithms of two ruby-jwt classes (RSASSA-PKCS1-v1_5 and RSASSA-PSS). + def key_algorithm?(public_jwk, algorithm) + return algorithm.is_a?(JWT::JWA::Rsa) || algorithm.is_a?(JWT::JWA::Ps) if public_jwk.is_a?(JWT::JWK::RSA) + + public_jwk.jwa.equal?(algorithm) end # Validate a cookie_password is non-empty and at least the minimum diff --git a/rbi/workos/session_manager.rbi b/rbi/workos/session_manager.rbi index 84c56816..035c1fb4 100644 --- a/rbi/workos/session_manager.rbi +++ b/rbi/workos/session_manager.rbi @@ -6,6 +6,10 @@ module WorkOS class SessionManager + # This list does not limit the signature algorithms that the SDK accepts. + # The JWKS key that a token names selects the algorithm. The SDK does not + # read this constant. The constant stays because earlier versions made it + # public. JWK_ALGORITHMS = T.let(["RS256", "ES256"].freeze, T::Array[String]) NO_SESSION_COOKIE_PROVIDED = T.let("no_session_cookie_provided", String) diff --git a/test/workos/test_session.rb b/test/workos/test_session.rb index 1a2db084..fbe0bb17 100644 --- a/test/workos/test_session.rb +++ b/test/workos/test_session.rb @@ -536,11 +536,24 @@ def test_refresh_persists_seal_data_even_when_access_token_decode_fails # --- 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. + # The SDK has no list of permitted algorithms. The `kid` header selects the + # JWKS key, and that key selects the algorithm. The SDK ignores the keys + # that it cannot use. JWKS_URL = "https://api.workos.com/sso/jwks/client_001" + # The algorithms that ruby-jwt has for an RSA key. + RSA_ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512"].freeze + + # The algorithm that ruby-jwt has for each EC curve: the name of the test + # key, the `crv` member, and the byte length of r and of s. + EC_ALGORITHMS = { + "ES256" => [:ec, "P-256", 32], + "ES384" => [:p384, "P-384", 48], + "ES512" => [:p521, "P-521", 66], + "ES256K" => [:k256, "secp256k1", 32] + }.freeze + INVALID_TOKEN_REASONS = [ WorkOS::SessionManager::INVALID_JWT, WorkOS::SessionManager::INVALID_JWT_ALGORITHM, @@ -554,10 +567,17 @@ def self.jwks_keys 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") + p384: OpenSSL::PKey::EC.generate("secp384r1"), + p521: OpenSSL::PKey::EC.generate("secp521r1"), + k256: OpenSSL::PKey::EC.generate("secp256k1") }.freeze end + # RSA keys of 3072 and 4096 bits. Only one test uses them, because OpenSSL needs some seconds to make them. + def self.large_rsa_keys + @large_rsa_keys ||= [3072, 4096].to_h { |bits| [bits, OpenSSL::PKey::RSA.generate(bits)] }.freeze + end + def jwks_key(name) self.class.jwks_keys.fetch(name) end @@ -595,7 +615,12 @@ 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. + # An EC key for each algorithm of EC_ALGORITHMS. The key ID is the name of the algorithm. + def ec_jwks + EC_ALGORITHMS.map { |alg, (name, crv, _size)| ec_jwk(jwks_key(name), kid: alg, crv: crv, alg: alg) } + end + + # Keys of types that ruby-jwt cannot import: 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))}, @@ -612,20 +637,30 @@ def es256_jwt(key = jwks_key(:ec), kid: "ec-1", claims: user_claims, header: {}) JWT.encode(claims, key, "ES256", {kid: kid}.merge(header)) end + # A token that ruby-jwt signs with this algorithm. + def signed_jwt(alg, key, kid:, claims: user_claims) + JWT.encode(claims, key, alg, {kid: kid}) + 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) + # The SHA-2 digest that an algorithm uses, for example SHA384 for ES384. + def digest_of(alg) + "SHA#{alg.delete("^0-9")}" 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) + # The signature that OpenSSL makes, with SHA-256 by default. For an EC key, it is in the DER form. + def openssl_signature(key, input, digest: "SHA256") + key.sign(OpenSSL::Digest.new(digest), input) + end + + # r and s of an ECDSA signature, each as a string of `size` bytes. + def ecdsa_r_and_s(key, input, size: 32, digest: "SHA256") + der = openssl_signature(key, input, digest: digest) OpenSSL::ASN1.decode(der).value.map { |integer| integer.value.to_s(2).rjust(size, "\x00".b) } end @@ -638,10 +673,10 @@ def authenticate_access_token(access_token, session_manager: @sm) 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 + def assert_authenticated(result, message = nil) + assert_kind_of WorkOS::SessionManager::AuthSuccess, result, message + assert result.authenticated, message + assert_equal "session_42", result.session_id, message end # The token is not valid: the result is an AuthError, and no exception escapes. @@ -842,7 +877,7 @@ def test_authenticate_rejects_alg_none end end - def test_authenticate_rejects_algorithms_that_are_not_in_the_allow_list + def test_authenticate_has_no_allow_list_and_the_alg_member_of_the_key_selects_the_algorithm stub_jwks([rsa_jwk, ec_jwk, p384_jwk]) tokens = { "RS384" => JWT.encode(user_claims, jwks_key(:rsa), "RS384", {kid: "rsa-1"}), @@ -853,7 +888,16 @@ def test_authenticate_rejects_algorithms_that_are_not_in_the_allow_list 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 + refute_includes WorkOS::SessionManager::JWK_ALGORITHMS, alg + end + + # The P-384 key has the `alg` member ES384, so the SDK accepts the ES384 token. + assert_authenticated authenticate_access_token(tokens.delete("ES384")) + + # The RSA key has the `alg` member RS256, so it cannot verify a different algorithm. + assert_equal ["RS384", "RS512", "PS256"], tokens.keys + tokens.each do |alg, token| + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), alg end end @@ -1228,6 +1272,16 @@ def test_authenticate_reads_keys_from_the_jwks_response_and_not_from_the_token assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, authenticate_access_token(token) assert_not_requested(:get, "https://attacker.example/jwks") + + # The same for a key that the token gives as a certificate chain. + header = { + "alg" => "ES256", "kid" => "ec-1", + "x5c" => [Base64.strict_encode64(attacker.public_to_der)], "x5u" => "https://attacker.example/chain.pem" + } + 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/chain.pem") end def test_refresh_returns_refresh_success_for_es256_access_token @@ -1261,6 +1315,873 @@ def test_authenticate_rejects_es256_token_that_is_not_a_user_access_token assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) end + # --- The JWKS key selects the algorithm ----------------------------------- + # + # The SDK source code names no algorithm of the tests below, except RS256 + # and ES256 in the JWK_ALGORITHMS constant. ruby-jwt has each algorithm. + + def test_authenticate_accepts_each_algorithm_that_ruby_jwt_has_for_a_key_without_an_alg_member + stub = stub_jwks([rsa_jwk.except("alg")] + ec_jwks.map { |jwk| jwk.except("alg") }) + + RSA_ALGORITHMS.each do |alg| + assert_authenticated authenticate_access_token(signed_jwt(alg, jwks_key(:rsa), kid: "rsa-1")), alg + end + EC_ALGORITHMS.each do |alg, (name, _crv, size)| + token = signed_jwt(alg, jwks_key(name), kid: alg) + assert_equal 2 * size, Base64.urlsafe_decode64(token.split(".").last).bytesize + assert_authenticated authenticate_access_token(token), alg + end + + # The public constant is not the list of the algorithms that the SDK accepts. + assert_equal ["RS256", "ES256"], (RSA_ALGORITHMS + EC_ALGORITHMS.keys) & WorkOS::SessionManager::JWK_ALGORITHMS + assert_requested(stub, times: 1) + end + + def test_authenticate_accepts_each_algorithm_when_it_is_the_alg_member_of_the_key + rsa_jwks = RSA_ALGORITHMS.map { |alg| rsa_jwk(kid: alg).merge("alg" => alg) } + stub_jwks(rsa_jwks + ec_jwks) + + RSA_ALGORITHMS.each do |alg| + assert_authenticated authenticate_access_token(signed_jwt(alg, jwks_key(:rsa), kid: alg)), alg + assert_equal "session_42", @sm.decode_jwt(signed_jwt(alg, jwks_key(:rsa), kid: alg))["sid"], alg + end + EC_ALGORITHMS.each do |alg, (name, _crv, _size)| + assert_authenticated authenticate_access_token(signed_jwt(alg, jwks_key(name), kid: alg)), alg + end + end + + def test_authenticate_accepts_rs256_token_of_an_rsa_key_of_2048_3072_and_4096_bits + keys = {2048 => jwks_key(:rsa)}.merge(self.class.large_rsa_keys) + stub_jwks(keys.map { |bits, key| rsa_jwk(key, kid: "rsa-#{bits}") }) + + keys.each do |bits, key| + assert_equal bits, key.n.num_bits + assert_authenticated authenticate_access_token(rs256_jwt(key, kid: "rsa-#{bits}")), bits + end + end + + def test_authenticate_rejects_token_when_its_algorithm_is_not_the_alg_member_of_the_key + rsa_jwks = RSA_ALGORITHMS.map { |alg| rsa_jwk(kid: alg).merge("alg" => alg) } + stub_jwks(rsa_jwks) + + # Each token has a correct signature of the RSA key. Only the `alg` member of the key rejects it. + RSA_ALGORITHMS.each do |key_alg| + (RSA_ALGORITHMS - [key_alg]).each do |alg| + result = authenticate_access_token(signed_jwt(alg, jwks_key(:rsa), kid: key_alg)) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result, "#{alg} token, #{key_alg} key" + end + end + end + + # The keys of this method 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. Each signature is a correct signature of the key that the + # token names. + def assert_rejects_each_algorithm_for_a_key_of_a_different_type + # The algorithm of an RSA key with the key ID of an EC key. The signature is in the DER form. + RSA_ALGORITHMS.each do |alg| + EC_ALGORITHMS.each do |kid, (name, _crv, _size)| + token = craft_jwt({"alg" => alg, "kid" => kid}) { |input| openssl_signature(jwks_key(name), input, digest: digest_of(alg)) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), "#{alg} token, #{kid} key" + end + end + + EC_ALGORITHMS.each_key do |alg| + # The algorithm of an EC key with the key ID of the RSA key. + token = craft_jwt({"alg" => alg, "kid" => "rsa-1"}) { |input| openssl_signature(jwks_key(:rsa), input, digest: digest_of(alg)) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), "#{alg} token, RSA key" + + # The algorithm of an EC key with the key ID of a key on a different curve. + EC_ALGORITHMS.except(alg).each do |kid, (name, _crv, size)| + token = craft_jwt({"alg" => alg, "kid" => kid}) do |input| + ecdsa_r_and_s(jwks_key(name), input, size: size, digest: digest_of(alg)).join + end + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), "#{alg} token, #{kid} key" + end + end + end + + def test_authenticate_binds_each_algorithm_to_the_key_type_and_the_curve_when_keys_have_no_alg_member + stub_jwks([rsa_jwk.except("alg")] + ec_jwks.map { |jwk| jwk.except("alg") }) + + assert_rejects_each_algorithm_for_a_key_of_a_different_type + end + + def test_authenticate_binds_each_algorithm_to_the_key_type_and_the_curve_when_alg_member_of_key_agrees_with_the_token + (RSA_ALGORITHMS + EC_ALGORITHMS.keys).each do |alg| + WebMock.reset! + sm = WorkOS::Client.new(api_key: "sk_test_session", client_id: "client_001").session_manager + # Each key says that it is a key for the algorithm of the token. + stub_jwks([rsa_jwk.merge("alg" => alg)] + ec_jwks.map { |jwk| jwk.merge("alg" => alg) }) + + EC_ALGORITHMS.each do |kid, (name, _crv, size)| + next if kid == alg + + token = craft_jwt({"alg" => alg, "kid" => kid}) do |input| + # The form of the signature that the algorithm of the token has. + if RSA_ALGORITHMS.include?(alg) + openssl_signature(jwks_key(name), input, digest: digest_of(alg)) + else + ecdsa_r_and_s(jwks_key(name), input, size: size, digest: digest_of(alg)).join + end + end + result = authenticate_access_token(token, session_manager: sm) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result, "#{alg} token, #{kid} key" + end + next if RSA_ALGORITHMS.include?(alg) + + token = craft_jwt({"alg" => alg, "kid" => "rsa-1"}) { |input| openssl_signature(jwks_key(:rsa), input, digest: digest_of(alg)) } + result = authenticate_access_token(token, session_manager: sm) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result, "#{alg} token, RSA key" + end + end + + def test_authenticate_rejects_token_when_ec_key_has_the_label_of_a_different_curve + labels = EC_ALGORITHMS.values.map { |_name, crv, _size| crv } + jwks = EC_ALGORITHMS.flat_map do |alg, (name, crv, _size)| + (labels - [crv]).map { |label| ec_jwk(jwks_key(name), kid: "#{alg}-as-#{label}", crv: label).except("alg") } + end + stub_jwks(jwks) + + jwks.each do |jwk| + alg, label = jwk["kid"].split("-as-") + name, _crv, size = EC_ALGORITHMS.fetch(alg) + # A token with the algorithm of the curve of the key. + token = signed_jwt(alg, jwks_key(name), kid: jwk["kid"]) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), jwk["kid"] + + # A token with the algorithm of the curve that the key names. + label_alg = EC_ALGORITHMS.keys.find { |candidate| EC_ALGORITHMS.fetch(candidate)[1] == label } + token = craft_jwt({"alg" => label_alg, "kid" => jwk["kid"]}) do |input| + ecdsa_r_and_s(jwks_key(name), input, size: size, digest: digest_of(label_alg)).join + end + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), jwk["kid"] + end + end + + # The signature of an RSA key for the signing input: RSASSA-PKCS1-v1_5 for an RS algorithm, RSASSA-PSS for a PS algorithm. + def rsa_signature(alg, key, input) + return openssl_signature(key, input, digest: digest_of(alg)) if alg.start_with?("RS") + + key.sign_pss(digest_of(alg), input, salt_length: :digest, mgf1_hash: digest_of(alg)) + end + + def test_authenticate_compares_the_name_of_each_algorithm_exactly + stub_jwks([rsa_jwk.except("alg")] + ec_jwks.map { |jwk| jwk.except("alg") }) + + # Each token has a correct signature. Only the algorithm name is not correct. + RSA_ALGORITHMS.each do |alg| + token = craft_jwt({"alg" => alg, "kid" => "rsa-1"}) { |input| rsa_signature(alg, jwks_key(:rsa), input) } + assert_authenticated authenticate_access_token(token), alg + + [alg.downcase, alg.capitalize, "#{alg} ", " #{alg}", [alg]].each do |name| + token = craft_jwt({"alg" => name, "kid" => "rsa-1"}) { |input| rsa_signature(alg, jwks_key(:rsa), input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), name.inspect + end + end + EC_ALGORITHMS.each do |alg, (name, _crv, size)| + [alg.downcase, alg.capitalize, "#{alg} ", [alg]].each do |header_alg| + token = craft_jwt({"alg" => header_alg, "kid" => alg}) do |input| + ecdsa_r_and_s(jwks_key(name), input, size: size, digest: digest_of(alg)).join + end + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), header_alg.inspect + end + end + end + + def test_authenticate_rejects_alg_none_when_keys_have_no_alg_member_or_the_alg_member_none + stub_jwks([ + rsa_jwk.except("alg"), ec_jwk.except("alg"), + rsa_jwk(kid: "rsa-none").merge("alg" => "none"), ec_jwk(kid: "ec-none", alg: "none") + ]) + signature = rs256_jwt.split(".").last + + ["none", "None", "NONE", "nOnE"].each do |alg| + ["rsa-1", "ec-1", "rsa-none", "ec-none"].each do |kid| + token = craft_jwt({"alg" => alg, "kid" => kid}) { "" } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), "#{alg} #{kid}" + + # 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} #{kid}" + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token + signature), "#{alg} #{kid}" + assert_raises(JWT::DecodeError, "#{alg} #{kid}") { @sm.decode_jwt(token) } + assert_raises(JWT::DecodeError, "#{alg} #{kid}") { @sm.decode_jwt(token.delete_suffix(".")) } + end + end + end + + def test_authenticate_rejects_hmac_token_signed_with_public_key_as_secret_when_keys_have_no_alg_member + stub_jwks([ + rsa_jwk.except("alg"), ec_jwk.except("alg"), + rsa_jwk(kid: "rsa-hs256").merge("alg" => "HS256"), ec_jwk(kid: "ec-hs256", alg: "HS256") + ]) + rsa_public = jwks_key(:rsa).public_key + ec_point = jwks_key(:ec).public_key.to_octet_string(:uncompressed) + rsa_secrets = [rsa_public.to_pem, rsa_public.to_der, rsa_public.n.to_s(2), rsa_jwk["n"]] + ec_secrets = [jwks_key(:ec).public_to_pem, jwks_key(:ec).public_to_der, ec_point, ec_jwk["x"]] + secrets = {"rsa-1" => rsa_secrets, "rsa-hs256" => rsa_secrets, "ec-1" => ec_secrets, "ec-hs256" => ec_secrets} + + 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), "#{alg} #{kid}" + assert_raises(JWT::DecodeError, "#{alg} #{kid}") { @sm.decode_jwt(token) } + end + end + end + end + + def test_authenticate_rejects_hmac_token_when_the_jwks_has_an_oct_key_with_the_kid_of_the_token + secret = SecureRandom.random_bytes(64) + pem = jwks_key(:rsa).public_key.to_pem + oct_jwk = ->(kid, k, members = {}) { {"kty" => "oct", "kid" => kid, "k" => b64url(k)}.merge(members) } + stub_jwks([ + oct_jwk.call("oct-1", secret), + oct_jwk.call("oct-sig", secret, "use" => "sig"), + oct_jwk.call("oct-HS256", secret, "alg" => "HS256"), + oct_jwk.call("oct-HS384", secret, "alg" => "HS384"), + oct_jwk.call("oct-HS512", secret, "alg" => "HS512"), + # The secret is the text of the RSA public key. + oct_jwk.call("oct-pem", pem), + # This key has the key ID of the RSA key, and it is before the RSA key. + oct_jwk.call("rsa-1", secret), + rsa_jwk.except("alg") + ]) + + # Each token has a correct MAC for the `k` member of the key that it names. + ["HS256", "HS384", "HS512"].each do |alg| + {"oct-1" => secret, "oct-sig" => secret, "oct-#{alg}" => secret, "oct-pem" => pem, "rsa-1" => secret}.each do |kid, k| + token = craft_jwt({"alg" => alg, "kid" => kid}) { |input| OpenSSL::HMAC.digest(alg.sub("HS", "SHA"), k, input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), "#{alg} #{kid}" + assert_raises(JWT::DecodeError, "#{alg} #{kid}") { @sm.decode_jwt(token) } + end + end + + # A token of a public key algorithm cannot use a symmetric key. + ["oct-1", "oct-sig", "oct-pem"].each do |kid| + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(kid: kid)), kid + token = craft_jwt({"alg" => "RS256", "kid" => kid}) { |input| OpenSSL::HMAC.digest("SHA256", secret, input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), kid + end + + # The symmetric key does not stop the RSA key that has the same key ID. + assert_authenticated authenticate_access_token(rs256_jwt) + end + + def test_authenticate_reads_no_key_for_an_unsigned_token_or_a_token_with_a_mac + stub_jwks([rsa_jwk.except("alg")]) + # The cache is 31 seconds old, so a token that names an unknown key ID causes a JWKS request. + @sm.send(:fetch_jwks, now: Time.now - 31) + + ["none", "HS256", "HS384", "HS512"].each do |alg| + token = craft_jwt({"alg" => alg, "kid" => "unknown"}) { |input| OpenSSL::HMAC.digest("SHA256", "secret", input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), alg + end + assert_requested(:get, JWKS_URL, times: 1) + + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(kid: "unknown")) + assert_requested(:get, JWKS_URL, times: 2) + end + + def test_authenticate_rejects_an_algorithm_that_ruby_jwt_does_not_have + stub_jwks(unusable_jwks + [rsa_jwk.except("alg"), ec_jwk.except("alg")]) + + # Each token has a correct signature of the key for a different algorithm. + # The first names are not algorithms. A later version of ruby-jwt can have + # the algorithms of the other names, and then the reason can change. + { + "RS1" => WorkOS::SessionManager::INVALID_JWT_ALGORITHM, "RS256K" => WorkOS::SessionManager::INVALID_JWT_ALGORITHM, + "PS128" => WorkOS::SessionManager::INVALID_JWT_ALGORITHM, "ES256 K" => WorkOS::SessionManager::INVALID_JWT_ALGORITHM, + "FUTURE512" => WorkOS::SessionManager::INVALID_JWT_ALGORITHM, "" => WorkOS::SessionManager::INVALID_JWT_ALGORITHM, + "EdDSA" => nil, "Ed25519" => nil, "ML-DSA-65" => nil + }.each do |alg, reason| + token = craft_jwt({"alg" => alg, "kid" => "rsa-1"}) { |input| openssl_signature(jwks_key(:rsa), input) } + assert_invalid_token reason, authenticate_access_token(token), alg + token = craft_jwt({"alg" => alg, "kid" => "ec-1"}) { |input| ecdsa_r_and_s(jwks_key(:ec), input).join } + assert_invalid_token reason, authenticate_access_token(token), alg + assert_raises(JWT::DecodeError, alg) { @sm.decode_jwt(token) } + end + end + + EC_ALGORITHMS.except("ES256").each do |alg, (name, _crv, size)| + define_method(:"test_authenticate_accepts_#{alg.downcase}_signature_only_in_the_raw_form_of_#{2 * size}_bytes") do + stub_jwks(ec_jwks.map { |jwk| jwk.except("alg") }) + header = {"alg" => alg, "kid" => alg} + r = s = der = nil + correct = craft_jwt(header) do |input| + der = openssl_signature(jwks_key(name), input, digest: digest_of(alg)) + r, s = OpenSSL::ASN1.decode(der).value.map { |integer| integer.value.to_s(2).rjust(size, "\x00".b) } + r + s + end + assert_authenticated authenticate_access_token(correct) + + zero = "\x00".b + signatures = { + "empty" => "", + "one byte less" => (r + s)[0, 2 * size - 1], + "one more byte at the end" => r + s + zero, + "one zero byte before r" => zero + r + s, + # ruby-jwt reads these bytes as the same r and s, and thus accepts this signature. + "one zero byte before s" => r + zero + s, + "two more bytes" => zero + r + zero + s, + "two signatures" => r + s + r + s, + "DER" => der + } + signatures.each do |description, signature| + token = craft_jwt(header) { signature } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, authenticate_access_token(token), description + end + end + end + + def test_authenticate_ignores_keys_that_ruby_jwt_cannot_import + skipped = [ + ec_jwk.merge("kid" => "ec-unknown-crv", "crv" => "P-999"), + ec_jwk.merge("kid" => "ec-crv-is-a-number", "crv" => 256), + {"kty" => "OKP", "crv" => "Ed448", "kid" => "okp-unknown-crv", "x" => b64url(SecureRandom.random_bytes(57))}, + {"kty" => "AKP", "kid" => "akp-no-alg", "pub" => b64url(SecureRandom.random_bytes(1312))}, + {"kty" => "rsa", "kid" => "kty-lower-case", "n" => rsa_jwk["n"], "e" => rsa_jwk["e"]}, + {"kty" => ["RSA"], "kid" => "kty-is-an-array", "n" => rsa_jwk["n"], "e" => rsa_jwk["e"]}, + {"kid" => "no-kty", "n" => rsa_jwk["n"], "e" => rsa_jwk["e"]}, + {"kty" => "oct", "kid" => "oct-no-k"}, + {"kty" => "oct", "kid" => "oct-1", "k" => b64url(SecureRandom.random_bytes(32))} + ] + stub = stub_jwks(unusable_jwks + skipped + [rsa_jwk, ec_jwk, p384_jwk]) + + # The other keys verify their tokens. + assert_authenticated authenticate_access_token(rs256_jwt) + assert_authenticated authenticate_access_token(es256_jwt) + assert_authenticated authenticate_access_token(signed_jwt("ES384", jwks_key(:p384), kid: "p384-1")) + + # A token that names a key that the SDK ignores is not valid, and no error escapes. + (unusable_jwks + skipped).each do |jwk| + kid = jwk["kid"] + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(kid: kid)), 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 + + assert_requested(stub, times: 1) + end + + def test_authenticate_skips_a_key_that_it_cannot_use_when_keys_share_a_kid + stub_jwks([ + {"kty" => "FUTURE", "kid" => "shared", "x" => false}, + {"kty" => "oct", "kid" => "shared", "k" => b64url(SecureRandom.random_bytes(32))}, + ec_jwk(kid: "shared").merge("y" => b64url(SecureRandom.random_bytes(32))).except("alg"), + ec_jwk(kid: "shared").merge("x" => 5).except("alg"), + ec_jwk(kid: "shared").merge("x" => "!!!").except("alg"), + ec_jwk(kid: "shared").merge("crv" => "P-999").except("alg"), + rsa_jwk(kid: "shared").merge("n" => "!!!").except("alg"), + rsa_jwk(kid: "shared").merge("e" => 65537).except("alg"), + rsa_jwk(jwks_key(:other_rsa), kid: "shared").merge("use" => "enc").except("alg"), + rsa_jwk(jwks_key(:other_rsa), kid: "shared").merge("alg" => "RSA-OAEP"), + ec_jwk(kid: "shared").except("alg"), + rsa_jwk(kid: "shared").except("alg") + ]) + + # The SDK uses the first key with the key ID that can verify the algorithm of the token. + assert_authenticated authenticate_access_token(es256_jwt(kid: "shared")) + assert_authenticated authenticate_access_token(rs256_jwt(kid: "shared")) + assert_authenticated authenticate_access_token(signed_jwt("PS256", jwks_key(:rsa), kid: "shared")) + + # No key with the key ID can verify these tokens. + result = authenticate_access_token(signed_jwt("ES384", jwks_key(:p384), kid: "shared")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, result + result = authenticate_access_token(rs256_jwt(jwks_key(:other_rsa), kid: "shared")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, result + end + + { + "rsa_then_ec" => ->(rsa, ec) { [rsa, ec] }, + "ec_then_rsa" => ->(rsa, ec) { [ec, rsa] } + }.each do |order, keys| + define_method(:"test_authenticate_selects_key_by_key_type_when_keys_without_an_alg_member_share_a_kid_#{order}") do + stub_jwks(keys.call(rsa_jwk(kid: "shared").except("alg"), ec_jwk(kid: "shared").except("alg"))) + assert_authenticated authenticate_access_token(rs256_jwt(kid: "shared")) + assert_authenticated authenticate_access_token(es256_jwt(kid: "shared")) + end + end + + def test_authenticate_does_not_read_the_private_members_of_a_jwks_key + private_rsa = JWT::JWK.new(jwks_key(:rsa)).export(include_private: true).transform_keys(&:to_s) + private_ec = JWT::JWK.new(jwks_key(:ec)).export(include_private: true).transform_keys(&:to_s) + stub_jwks([ + private_rsa.merge("kid" => "rsa-private"), + # ruby-jwt cannot make a key from these private members. + rsa_jwk(kid: "rsa-only-d").merge("d" => private_rsa.fetch("d")), + rsa_jwk(kid: "rsa-d-is-a-number").merge("d" => 5, "p" => "!!!"), + private_ec.merge("kid" => "ec-private"), + ec_jwk(kid: "ec-d-is-a-number").merge("d" => 5), + ec_jwk(kid: "ec-d-not-base64").merge("d" => "!!!") + ]) + + ["rsa-private", "rsa-only-d", "rsa-d-is-a-number"].each do |kid| + assert_authenticated authenticate_access_token(rs256_jwt(kid: kid)), kid + end + ["ec-private", "ec-d-is-a-number", "ec-d-not-base64"].each do |kid| + assert_authenticated authenticate_access_token(es256_jwt(kid: kid)), kid + end + # The SDK gives ruby-jwt a key that has no private part. + refute_predicate @sm.send(:import_jwk, private_rsa.merge("kid" => "rsa-private"), JWT::JWA.find("RS256")), :private? + refute_predicate @sm.send(:import_jwk, private_ec.merge("kid" => "ec-private"), JWT::JWA.find("ES256")), :private_key? + end + + def test_decode_jwt_raises_a_decode_error_for_a_token_that_is_nil_or_has_no_header + stub_jwks([rsa_jwk, ec_jwk]) + + [nil, "", ".", "..", "a.b.c", "#{b64url("[]")}.e30.e30", "#{b64url("null")}.e30.e30"].each do |token| + assert_raises(JWT::DecodeError, token.inspect) { @sm.decode_jwt(token) } + end + ["", "..", "a.b.c"].each do |token| + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), token.inspect + end + end + + # Byte sequences that are not UTF-8. UTF-8 does not use the bytes 0xFF and + # 0xC1. The byte 0xC3 starts a sequence of two bytes, but the tests put no + # second byte after it. + NOT_UTF8_BYTES = ["\xFF", "\xC1", "\xC3"].map { |bytes| bytes.b.freeze }.freeze + + # Build a token from the bytes of a header and the signature that the block gives for the signing input. + # JSON.generate does not accept text that is not UTF-8, so the caller writes the JSON text of the header. + def craft_jwt_from_header_bytes(header, claims = user_claims) + input = "#{b64url(header)}.#{b64url(JSON.generate(claims))}" + "#{input}.#{b64url(yield(input))}" + end + + # Stub a JWKS response that has the byte sequence `bytes` at each place where a key has the text NOT_UTF8. + def stub_jwks_with_bytes(keys, bytes) + stub_request(:get, JWKS_URL).to_return(status: 200, body: {"keys" => keys}.to_json.b.gsub("NOT_UTF8", bytes)) + end + + def test_authenticate_rejects_an_algorithm_name_that_has_bytes_that_are_not_utf8 + stub_jwks([rsa_jwk.except("alg"), ec_jwk.except("alg")]) + # The key ID and the signature of a token for each algorithm. + tokens = { + "RS256" => ["rsa-1", ->(input) { rsa_signature("RS256", jwks_key(:rsa), input) }], + "PS256" => ["rsa-1", ->(input) { rsa_signature("PS256", jwks_key(:rsa), input) }], + "ES256" => ["ec-1", ->(input) { ecdsa_r_and_s(jwks_key(:ec), input).join }], + "HS256" => ["rsa-1", ->(input) { OpenSSL::HMAC.digest("SHA256", jwks_key(:rsa).public_key.to_pem, input) }], + "none" => ["rsa-1", ->(_input) { "" }] + } + + tokens.each do |alg, (kid, signature)| + # With the correct algorithm name, the token of a public key algorithm is valid. + unless ["HS256", "none"].include?(alg) + token = craft_jwt_from_header_bytes(%({"alg":"#{alg}","kid":"#{kid}"}), &signature) + assert_authenticated authenticate_access_token(token), alg + end + + # The algorithm name of each of these tokens is not UTF-8. The last name is in an array. + NOT_UTF8_BYTES.each do |bytes| + names = [%("#{alg}#{bytes}"), %("#{bytes}#{alg}"), %("#{bytes}"), %("#{bytes}#{bytes}"), %(["#{alg}#{bytes}"])] + names.each do |name| + refute_predicate name.dup.force_encoding("UTF-8"), :valid_encoding? + token = craft_jwt_from_header_bytes(%({"alg":#{name},"kid":"#{kid}"}).b, &signature) + + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token), name.inspect + assert_raises(JWT::DecodeError, name.inspect) { @sm.decode_jwt(token) } + end + end + end + end + + def test_authenticate_ignores_a_jwks_member_when_its_name_has_bytes_that_are_not_utf8 + NOT_UTF8_BYTES.each do |bytes| + WebMock.reset! + sm = WorkOS::Client.new(api_key: "sk_test_session", client_id: "client_001").session_manager + # The SDK and ruby-jwt read no member that has one of these names. + unknown = {"xNOT_UTF8" => "1", "NOT_UTF8" => ["a", {"b" => 2}]} + stub = stub_jwks_with_bytes([ + rsa_jwk.merge(unknown), + rsa_jwk(kid: "rsa-no-alg").except("alg").merge(unknown), + ec_jwk.merge(unknown), + # The name of each member is not the name of a member that the SDK reads. + rsa_jwk(kid: "rsa-no-use").except("alg", "use").merge("algNOT_UTF8" => "ES256", "useNOT_UTF8" => "enc"), + ec_jwk(kid: "ec-no-y").except("y").merge("yNOT_UTF8" => ec_jwk["y"]) + ], bytes) + + # The key verifies its tokens, as it does without the member. + assert_authenticated authenticate_access_token(rs256_jwt, session_manager: sm), bytes.inspect + assert_equal "session_42", sm.decode_jwt(rs256_jwt)["sid"], bytes.inspect + token = signed_jwt("PS256", jwks_key(:rsa), kid: "rsa-no-alg") + assert_authenticated authenticate_access_token(token, session_manager: sm), bytes.inspect + assert_authenticated authenticate_access_token(es256_jwt, session_manager: sm), bytes.inspect + assert_authenticated authenticate_access_token(rs256_jwt(kid: "rsa-no-use"), session_manager: sm), bytes.inspect + + # This key has no `y` member, so the SDK ignores the key. + token = es256_jwt(kid: "ec-no-y") + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token, session_manager: sm), bytes.inspect + assert_raises(JWT::DecodeError, bytes.inspect) { sm.decode_jwt(token) } + + assert_requested(stub, times: 1) + end + end + + def test_authenticate_rejects_token_when_a_member_of_the_selected_key_has_bytes_that_are_not_utf8 + rsa = rsa_jwk.except("alg") + ec = ec_jwk.except("alg") + # Each key has one member that is not correct. The key ID has the name of that member. + rsa_entries = { + "kty" => "RSANOT_UTF8", "alg" => "RS256NOT_UTF8", "use" => "sigNOT_UTF8", + "n" => "NOT_UTF8#{rsa["n"]}", "e" => "#{rsa["e"]}NOT_UTF8" + }.map { |member, value| rsa.merge("kid" => "rsa-#{member}", member => value) } + ec_entries = { + "crv" => "P-256NOT_UTF8", "x" => "NOT_UTF8#{ec["x"]}", "y" => "#{ec["y"]}NOT_UTF8" + }.map { |member, value| ec.merge("kid" => "ec-#{member}", member => value) } + + NOT_UTF8_BYTES.each do |bytes| + WebMock.reset! + sm = WorkOS::Client.new(api_key: "sk_test_session", client_id: "client_001").session_manager + stub = stub_jwks_with_bytes(rsa_entries + ec_entries + [ + # The key that is not correct is before a correct key that has the same key ID. + rsa.merge("kid" => "shared", "n" => "NOT_UTF8#{rsa["n"]}"), rsa.merge("kid" => "shared"), + # The SDK does not read these members of a key. + rsa_jwk(kid: "rsa-other-members").merge("x5t#S256" => "NOT_UTF8", "key_ops" => ["NOT_UTF8"], "d" => "NOT_UTF8"), + rsa, ec + ], bytes) + + # A token that names a key that is not correct is not valid, and no error escapes. + rsa_entries.each do |jwk| + ["RS256", "PS256", "RS384"].each do |alg| + token = signed_jwt(alg, jwks_key(:rsa), kid: jwk["kid"]) + message = "#{alg} #{jwk["kid"]} #{bytes.inspect}" + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token, session_manager: sm), message + assert_raises(JWT::DecodeError, message) { sm.decode_jwt(token) } + end + end + ec_entries.each do |jwk| + token = es256_jwt(kid: jwk["kid"]) + message = "#{jwk["kid"]} #{bytes.inspect}" + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token, session_manager: sm), message + assert_raises(JWT::DecodeError, message) { sm.decode_jwt(token) } + end + + # The other keys verify their tokens. + assert_authenticated authenticate_access_token(rs256_jwt, session_manager: sm), bytes.inspect + assert_authenticated authenticate_access_token(es256_jwt, session_manager: sm), bytes.inspect + assert_authenticated authenticate_access_token(rs256_jwt(kid: "shared"), session_manager: sm), bytes.inspect + assert_authenticated authenticate_access_token(rs256_jwt(kid: "rsa-other-members"), session_manager: sm), bytes.inspect + + assert_requested(stub, times: 1) + end + end + + def test_refresh_returns_refresh_success_for_access_token_of_each_algorithm + stub_jwks([rsa_jwk.except("alg")] + ec_jwks) + keys = {"PS256" => [jwks_key(:rsa), "rsa-1"], "RS512" => [jwks_key(:rsa), "rsa-1"], "ES384" => [jwks_key(:p384), "ES384"], "ES512" => [jwks_key(:p521), "ES512"]} + + keys.each do |alg, (key, kid)| + old_access = signed_jwt(alg, key, kid: kid, 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 = signed_jwt(alg, key, kid: kid, 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) + + assert_invalid_token WorkOS::SessionManager::EXPIRED_JWT, authenticate_access_token(old_access), alg + result = @sm.load(seal_data: sealed, cookie_password: PASSWORD).refresh + assert_kind_of WorkOS::SessionManager::RefreshSuccess, result, alg + assert_equal "session_new", result.session_id, alg + assert_equal new_access, @sm.unseal_data(result.sealed_session, PASSWORD)["access_token"], alg + end + end + + # --- Key types and algorithms from an extension of ruby-jwt --------------- + # + # A gem can give ruby-jwt a key class and an algorithm that ruby-jwt does + # not have. For example, the jwt-eddsa gem gives the OKP key type and the + # EdDSA algorithm. The classes below do the same for the tests. A key class + # has the methods that ruby-jwt calls to verify a token: `jwa` and + # `verify_key`. It has no `public_key` method. A key class also has the + # `members` method. The SDK gets the public members of a key from that + # method. The comment of a key class shows which of these methods the class + # does not have. + # + # ruby-jwt has no method that removes a key class or an algorithm. Thus the + # names below are not the names of a real key type or of a real algorithm, + # and no other test uses them. The SDK source code does not have the names. + + class ExtensionJwk < JWT::JWK::KeyBase + def initialize(key, params = nil, options = {}) + super(options, key.transform_keys(&:to_sym).merge((params || {}).transform_keys(&:to_sym))) + end + end + + # An Ed25519 public key with the key type TEST-OKP. OpenSSL makes the key. + class TestOkpJwk < ExtensionJwk + KTYS = ["TEST-OKP"].freeze + + def members + {kty: self[:kty], x: self[:x]} + end + + def jwa + JWT::JWA.find("TEST-EdDSA") + end + + def verify_key + OpenSSL::PKey.new_raw_public_key("ED25519", Base64.urlsafe_decode64(self[:x])) + end + end + + # The algorithm of a TEST-OKP key. OpenSSL verifies the Ed25519 signature. + class TestEddsa + include JWT::JWA::SigningAlgorithm + + def initialize + @alg = "TEST-EdDSA" + end + + def verify(data:, signature:, verification_key:) + # The Ed25519 library of the jwt-eddsa gem raises this error for a signature that does not have 64 bytes. + raise ArgumentError, "expected 64 byte signature, got #{signature.bytesize}" unless signature.bytesize == 64 + + verification_key.verify(nil, signature, data) + end + + register_algorithm(new) + end + + # A symmetric key with the key type TEST-SECRET. + class TestSecretJwk < ExtensionJwk + KTYS = ["TEST-SECRET"].freeze + + def members + {k: self[:k], kty: self[:kty]} + end + + def jwa + JWT::JWA.find("TEST-MAC") + end + + def verify_key + Base64.urlsafe_decode64(self[:k]) + end + end + + # The algorithm of a TEST-SECRET key: an HMAC with SHA-256. + class TestMac + include JWT::JWA::SigningAlgorithm + + def initialize + @alg = "TEST-MAC" + end + + def verify(data:, signature:, verification_key:) + signature == OpenSSL::HMAC.digest("SHA256", verification_key, data) + end + + register_algorithm(new) + end + + # An Ed25519 public key with the key type TEST-NO-MEMBERS. The key class has no `members` method. + class TestNoMembersJwk < ExtensionJwk + KTYS = ["TEST-NO-MEMBERS"].freeze + + def jwa + JWT::JWA.find("TEST-EdDSA") + end + + def verify_key + OpenSSL::PKey.new_raw_public_key("ED25519", Base64.urlsafe_decode64(self[:x])) + end + end + + # A key class with the key type TEST-BROKEN. Its `members` method raises an error for each key. + # The error class is not a class of Ruby, of ruby-jwt or of OpenSSL. The key class has no other method. + class TestBrokenJwk < ExtensionJwk + KTYS = ["TEST-BROKEN"].freeze + + class Error < StandardError; end + + def members + raise Error, "The key class cannot read the key" + end + end + + # The JWKS form of an Ed25519 public key with the key type of the extension. + def extension_jwk(key, kid: "ext-1") + {"kty" => "TEST-OKP", "kid" => kid, "x" => b64url(key.raw_public_key)} + end + + # A token with the algorithm of the extension and the Ed25519 signature of the key. + def extension_jwt(key, kid: "ext-1") + craft_jwt({"alg" => "TEST-EdDSA", "kid" => kid}) { |input| key.sign(nil, input) } + end + + def test_authenticate_accepts_a_key_type_and_an_algorithm_from_an_extension_of_ruby_jwt + key = OpenSSL::PKey.generate_key("ED25519") + stub = stub_jwks([ + extension_jwk(key), + extension_jwk(key, kid: "ext-alg").merge("alg" => "TEST-EdDSA", "use" => "sig"), + rsa_jwk.except("alg"), ec_jwk.except("alg") + ]) + + ["ext-1", "ext-alg"].each do |kid| + token = extension_jwt(key, kid: kid) + assert_authenticated authenticate_access_token(token), kid + assert_equal "session_42", @sm.decode_jwt(token)["sid"], kid + end + assert_authenticated authenticate_access_token(rs256_jwt) + assert_authenticated authenticate_access_token(es256_jwt) + + # The signature of a different key, and a signature that no key makes. + other_key = OpenSSL::PKey.generate_key("ED25519") + [extension_jwt(other_key), craft_jwt({"alg" => "TEST-EdDSA", "kid" => "ext-1"}) { "\x00".b * 64 }].each do |token| + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_SIGNATURE, authenticate_access_token(token) + assert_raises(JWT::VerificationError) { @sm.decode_jwt(token) } + end + + # ruby-jwt has one algorithm for the key type of the extension. This is not the algorithm of a different key type. + ["rsa-1", "ec-1"].each do |kid| + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(extension_jwt(key, kid: kid)), kid + end + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(kid: "ext-1")) + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(es256_jwt(kid: "ext-1")) + + # The SDK compares the algorithm name exactly. + token = craft_jwt({"alg" => "test-eddsa", "kid" => "ext-1"}) { |input| key.sign(nil, input) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT_ALGORITHM, authenticate_access_token(token) + + assert_requested(stub, times: 1) + end + + def test_authenticate_skips_a_key_when_openssl_raises_an_error_for_the_key + key = OpenSSL::PKey.generate_key("ED25519") + # An Ed25519 public key has 32 bytes. OpenSSL raises an error for this key of 31 bytes. + # The key class does not catch the error. + short_jwk = extension_jwk(key, kid: "shared").merge("x" => b64url(key.raw_public_key[0, 31])) + assert_raises(OpenSSL::PKey::PKeyError) { JWT::JWK.import(short_jwk).verify_key } + stub_jwks([short_jwk, extension_jwk(key, kid: "shared"), short_jwk.merge("kid" => "short")]) + + # The key that OpenSSL cannot read does not stop the correct key that has the same key ID. + assert_authenticated authenticate_access_token(extension_jwt(key, kid: "shared")) + + # A token that names only the key that OpenSSL cannot read is not valid, and no error escapes. + token = extension_jwt(key, kid: "short") + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + assert_raises(JWT::DecodeError) { @sm.decode_jwt(token) } + end + + def test_authenticate_skips_a_key_when_the_key_class_raises_an_error_for_the_key + key = OpenSSL::PKey.generate_key("ED25519") + # The `x` member of this key is not Base64. The key class does not catch the ArgumentError of the Base64 decoder. + not_base64_jwk = extension_jwk(key, kid: "shared").merge("x" => "!!!") + assert_raises(ArgumentError) { JWT::JWK.import(not_base64_jwk).verify_key } + # The key class of this key raises an error of its own class. + broken_jwk = {"kty" => "TEST-BROKEN", "kid" => "shared", "x" => b64url(key.raw_public_key)} + assert_raises(TestBrokenJwk::Error) { JWT::JWK.import(broken_jwk).members } + stub_jwks([not_base64_jwk, broken_jwk, extension_jwk(key, kid: "shared"), broken_jwk.merge("kid" => "broken")]) + + # The keys that a key class cannot read do not stop the correct key that has the same key ID. + assert_authenticated authenticate_access_token(extension_jwt(key, kid: "shared")) + + # A token that names only a key that the key class cannot read is not valid, and no error escapes. + token = extension_jwt(key, kid: "broken") + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + assert_raises(JWT::DecodeError) { @sm.decode_jwt(token) } + end + + def test_authenticate_rejects_token_when_the_key_class_has_no_members_method + key = OpenSSL::PKey.generate_key("ED25519") + no_members_jwk = {"kty" => "TEST-NO-MEMBERS", "kid" => "no-members", "x" => b64url(key.raw_public_key)} + assert_raises(NoMethodError) { JWT::JWK.import(no_members_jwk).members } + stub_jwks([no_members_jwk, no_members_jwk.merge("kid" => "shared"), extension_jwk(key, kid: "shared"), rsa_jwk]) + + # ruby-jwt verifies the signature of this token when it gets the key. + token = extension_jwt(key, kid: "no-members") + input, _dot, signature = token.rpartition(".") + assert JWT::JWK.import(no_members_jwk).verify(data: input, signature: Base64.urlsafe_decode64(signature)) + + # The SDK cannot get the public members of the key, so it does not use the key. + # The token is not valid, and no error escapes. + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + assert_raises(JWT::DecodeError) { @sm.decode_jwt(token) } + # A token that has the algorithm of a different key type is also not valid. + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs256_jwt(kid: "no-members")) + + # The key does not stop the correct key that has the same key ID. The other keys verify their tokens. + assert_authenticated authenticate_access_token(extension_jwt(key, kid: "shared")) + assert_authenticated authenticate_access_token(rs256_jwt) + end + + def test_authenticate_rejects_token_when_ruby_jwt_or_an_extension_raises_an_argument_error + key = OpenSSL::PKey.generate_key("ED25519") + # The `x` member of this key is not Base64. The key class does not catch the ArgumentError of the Base64 decoder. + not_base64_jwk = extension_jwk(key, kid: "ext-not-base64").merge("x" => "!!!") + assert_raises(ArgumentError) { JWT::JWK.import(not_base64_jwk).verify_key } + stub_jwks([not_base64_jwk, extension_jwk(key), rsa_jwk]) + + token = extension_jwt(key, kid: "ext-not-base64") + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token) + assert_raises(JWT::DecodeError) { @sm.decode_jwt(token) } + + # The algorithm of the extension raises an ArgumentError for a signature that does not have 64 bytes. + [0, 63, 65].each do |size| + token = craft_jwt({"alg" => "TEST-EdDSA", "kid" => "ext-1"}) { |input| (key.sign(nil, input) * 2)[0, size] } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), size + assert_raises(JWT::DecodeError, size.to_s) { @sm.decode_jwt(token) } + end + + # ruby-jwt raises an ArgumentError for a token that is not a String. + [123, 1.5, true, ["a"], {"a" => 1}].each do |not_a_string| + assert_raises(ArgumentError, not_a_string.inspect) { JWT.decode(not_a_string, nil, false) } + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(not_a_string), not_a_string.inspect + assert_raises(JWT::DecodeError, not_a_string.inspect) { @sm.decode_jwt(not_a_string) } + end + + # The other keys verify their tokens. + assert_authenticated authenticate_access_token(extension_jwt(key)) + assert_authenticated authenticate_access_token(rs256_jwt) + end + + def test_authenticate_never_uses_a_symmetric_key_from_an_extension_of_ruby_jwt + secret = SecureRandom.random_bytes(32) + secret_jwk = {"kty" => "TEST-SECRET", "kid" => "secret-1", "k" => b64url(secret)} + stub_jwks([secret_jwk, secret_jwk.merge("kid" => "secret-alg", "alg" => "TEST-MAC", "use" => "sig"), rsa_jwk]) + + ["secret-1", "secret-alg"].each do |kid| + # The token has a correct MAC for the `k` member of the key that it names. + # ruby-jwt verifies this MAC when it gets the key. + mac = nil + token = craft_jwt({"alg" => "TEST-MAC", "kid" => kid}) { |input| mac = OpenSSL::HMAC.digest("SHA256", secret, input) } + assert JWT::JWK.import(secret_jwk).verify(data: token.rpartition(".").first, signature: mac), kid + + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(token), kid + assert_raises(JWT::DecodeError, kid) { @sm.decode_jwt(token) } + end + + assert_authenticated authenticate_access_token(rs256_jwt) + end + + def test_authenticate_rejects_token_when_openssl_raises_an_error_in_the_verification + stub_jwks([rsa_jwk.except("alg")]) + rs512 = signed_jwt("RS512", jwks_key(:rsa), kid: "rsa-1") + assert_authenticated authenticate_access_token(rs512) + + # Until the `ensure` clause, `OpenSSL::Digest.new` raises an OpenSSL error for the SHA-512 digest. + # ruby-jwt does not catch this error. + OpenSSL::Digest.singleton_class.define_method(:new) do |name, *arguments| + raise OpenSSL::Digest::DigestError, "Digest initialization failed" if name.to_s.casecmp?("SHA512") + + super(name, *arguments) + end + begin + assert_invalid_token WorkOS::SessionManager::INVALID_JWT, authenticate_access_token(rs512) + assert_raises(JWT::DecodeError) { @sm.decode_jwt(rs512) } + # A token that uses a different digest is valid. + assert_authenticated authenticate_access_token(rs256_jwt) + ensure + OpenSSL::Digest.singleton_class.remove_method(:new) + end + + assert_authenticated authenticate_access_token(rs512) + end + # --- Session constructor validation --------------------------------------- def test_session_load_requires_cookie_password