Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 103 additions & 61 deletions lib/workos/session_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,36 +34,21 @@ 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

# 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
private_constant :JWKS_CACHE_TTL, :JWKS_REFETCH_COOLDOWN

# H04 success / failure shapes — kept minimal & frozen.
class AuthSuccess
Expand Down Expand Up @@ -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).
#
Expand All @@ -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
}
Expand All @@ -236,50 +230,74 @@ 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

# 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)
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

key
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).
Expand All @@ -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
Expand Down
4 changes: 4 additions & 0 deletions rbi/workos/session_manager.rbi
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading