Skip to content
Closed
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
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
189 changes: 177 additions & 12 deletions lib/workos/session_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

require "json"
require "jwt"
require "openssl"

module WorkOS
# Manages sealed-session lifecycle: loading, authenticating, refreshing,
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Loading
Loading