Repository navigation
feat(session): accept each JWT algorithm that the JWKS key can verify - #593
Open
gjtorikian wants to merge 5 commits into
Open
gjtorikian wants to merge 5 commits into
gjtorikian wants to merge 5 commits into
Conversation
The session token verifier has no list of permitted algorithms now. After pull request #589, that list had only RS256 and ES256. Thus a different algorithm needed a new SDK release. The `kid` header selects the JWKS key. The algorithm must agree with it. ruby-jwt has the algorithms for the key type and verifies the signature. An unsigned token and a token with a MAC are never valid. `JWK_ALGORITHMS` stays as a public constant. The SDK does not read it. No public name, parameter, return type or failure reason constant changes.
Contributor
Confidence Score: 5/5
[Critical impact] The PR appears safe to merge; no new blocking issue was found. SummaryThe PR lets the selected JWKS key determine which JWT algorithms can verify a session token. Since the previous review, it also adds helpers for storing large sealed sessions across several cookies.
|
This commit removes `WorkOS::SessionManager::JWK_ALGORITHMS`. It also removes the signature of the constant from the rbi file. After the previous commit, the SDK did not read the constant. Its value was not the list of the algorithms that the SDK accepts. An application that reads the constant now gets a `NameError`. The comment of `key_algorithm?` now names no algorithm family.
The new package rule is for the JWT library and its crypto library. For these packages, the rule sets `schedule` to any time. The monthly schedule stays for each other dependency. The rule also sets `internalChecksFilter` to `none`. Thus Renovate opens the pull request before the release has the minimum release age of the shared preset, and automerge waits for that age. These updates use the commit type `fix(deps:crypto)`, thus a merge of such an update makes a patch release.
The comment said that a new algorithm needs no change of the SDK. That is true only for an algorithm that obeys the rules of the SDK. The comment now gives the rule for an RSA key and for each other key. It also says that each other new algorithm needs a change of the SDK.
A browser does not store a cookie that is larger than 4096 bytes. A sealed session with a large access token can be larger. The new module `WorkOS::SessionCookie` has three functions. `split_session_cookie` gives the cookies to write and the names to delete. `join_session_cookie` gives the sealed session from the request cookies. `session_cookie_names` gives each cookie name of the session for a logout. The functions need no client, and they do no I/O. They do not seal, unseal or verify a session. No other public name, parameter, return type, default or error changes. The commit adds no dependency.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
On
main, the session token verifier accepts a token only if its algorithm is RS256 or ES256. Pull request #589 added ES256 toJWK_ALGORITHMSand added a private table of key types. No release has #589. This pull request removes the table and theJWK_ALGORITHMSconstant. This pull request also adds three helper functions for session cookies.The SDK now has no list of permitted algorithm names. The
kidheader selects the JWKS key. The type, the curve and thealgmember of that key give the permitted algorithms. Thus a different algorithm needs no new list of names in an SDK release. The SDK accepts a token of that algorithm only if ruby-jwt and OpenSSL have the algorithm for the key.How the SDK selects the key and the algorithm
decode_jwtgets the algorithm object for thealgheader fromJWT::JWA.findand givesJWT.decodethat one object and a block that finds the key. The block gets the JWKS keys that have thekidof the token. If a key has analgmember, that member must be equal to thealgheader.JWT::JWK.importselects the key class fromkty, and the SDK makes the key from the public members of that class (members, thenverify_key). For an EC key, the token must use the one algorithm of the curve (jwa). For an RSA key, the token must use aJWT::JWA::RsaorJWT::JWA::Psalgorithm. ruby-jwt then verifies the signature with OpenSSL and checks the claims.An unsigned token and a token with a MAC are never valid. ruby-jwt gives an algorithm of the class
JWT::JWA::NoneorJWT::JWA::Hmacfor such a token, and the SDK then givesJWT.decodean empty algorithm list.JWT.decodethen raisesJWT::IncorrectAlgorithmbefore the block looks for a key. The SDK also uses no key that is a String, and the key of a symmetric JWK is a String.Checks in SDK code
JWT::JWA::NoneorJWT::JWA::Hmacalgorithm, the SDK gives ruby-jwt an empty algorithm list. Cause: ruby-jwt accepts an unsigned token if the list has itsnonealgorithm, and it verifies a MAC with a String key. The check stops such a token before the SDK looks for a key, with the reasoninvalid_jwt_algorithm.algheader must be equal to the name of the algorithm, with the same letter case. Cause: ruby-jwt compares names without case, so it accepts a token withrs256for RS256.algmember of the key must be equal to thealgheader, andusemust be absent orsig. Cause: ruby-jwt gets the OpenSSL key from the SDK, so it does not read these members.key_algorithm?). Cause: ruby-jwt gives no algorithm for an RSA key that has noalgmember. Thus the SDK code has theJWT::JWA::RsaandJWT::JWA::Psclasses. This check also selects the key when two keys have the samekid.r || 0x00 || s, which has one more byte.algmember replaces the algorithm of the curve.verify_keyof a symmetric key is the secret, which is a String.NoMethodErrorfor a member that is not a String, andJWT::UnsupportedKeyTypefor aktythat it does not have.algname that is not UTF-8, the SDK gives ruby-jwt an empty algorithm list. Cause:JWT::EncodedToken.newandJWT::JWA.findraiseArgumentErrorfor them.JWT::JWK.importraisesEncodingErrorfor that name. The SDK then uses the key without that member.verify_jwtraisesJWT::DecodeErrorfor anOpenSSL::OpenSSLErrorand for anArgumentError. Cause:JWT.decoderaisesArgumentErrorfor a token that is a number or an Array, and it does not rescue each OpenSSL error.Algorithms
invalid_jwt_algorithm.No change
SessionManagerandSession, and the failure reason constants. The one exception is theJWK_ALGORITHMSconstant (see the subsequent section).critrejection, the check ofkid, and the dependencies (workos.gemspec,Gemfile.lock).kid(not more than one in 30 seconds).Behavior changes
algmember, or it has thatalgmember. Onmain:invalid_jwt_algorithm. Now: valid.main:invalid_jwt_algorithm. Now:invalid_jwt_signaturefor an incorrect signature,expired_jwtfor an expired token, andinvalid_jwtfor other causes. Examples of other causes: a differentalgmember of the key, an unknownkid, acritheader. Also a key of a different type or curve.kid, when the last JWKS request is older than 30 seconds. Onmain: no new JWKS request. Now: one new JWKS request, as for RS256 onmain.kid, and the first key is not correct. Examples: an EC point that is not on the curve, a member that is not Base64. Onmain:invalid_jwt. Now: the SDK ignores that key and uses the subsequent key.true, an Array, a Hash). Also annorxmember of a JWKS key that is not UTF-8. Onmain:authenticateanddecode_jwtraise anArgumentError. Now: the reason isinvalid_jwt, anddecode_jwtraisesJWT::DecodeError.decode_jwtwhen the key of the token is not correct. Onmain:JWT::JWKErrororJWT::Base64DecodeError. Now:JWT::DecodeError. The two classes are subclasses ofJWT::DecodeError.main:invalid_jwt_algorithm. Now: valid for a correct signature, if the key class has themembers,jwaandverify_keymethods. The SDK makes the key again frommembers, andjwaof that key must give the algorithm object of the token. The tests of this pull request show this with a test key class and a test algorithm. A key class with nomembersmethod, or with a String key, givesinvalid_jwt.WorkOS::SessionManager::JWK_ALGORITHMS. This pull request removes the constant and its signature inrbi/workos/session_manager.rbi. Each release from 7.0.0 through 10.7.0 has the constant with the value["RS256"]. Onmain: a frozen Array with RS256 and ES256. Now: Ruby raisesNameError(uninitialized constant WorkOS::SessionManager::JWK_ALGORITHMS). Sorbet gives the errorUnable to resolve constantfor a typed file that reads the constant. Remove each use of the constant from the application.authenticateanddecode_jwthave no algorithm parameter. If the application uses the value in its own code, define the value there.Tests
algmember and for a key with thatalgmember.session.rb,session_manager.rbandsession_manager.rbihave none of these algorithm names, and a test asserts this. A test also asserts thatSessionManagerhas noJWK_ALGORITHMSconstant.algheader that is not thealgmember of the key.none, and HS256, HS384 and HS512 with the public key as the secret. Also HS256, HS384 and HS512 with the secret of anoctkey that has thekidof the token.jwk,jku,x5corx5uheader member.ktyorcrv, anoctkey, a member that is not correct.mainhave a new name and new assertions, because they test the list. The first now asserts that the SDK accepts ES384. For a key withalgRS256, it assertsinvalid_jwtfor RS384, RS512 and PS256. The second now asserts thatSessionManagerhas noJWK_ALGORITHMSconstant. A third test ofmaingets assertions forx5candx5u. The pull request removes no test.Session cookie helpers
A browser does not store a cookie that is larger than 4096 bytes. A sealed session with a large access token (for example a token with many claims) can be larger. The new module
WorkOS::SessionCookiehas three functions that keep one sealed session in more than one cookie. The SDK does not read or write HTTP cookies: the application does that.Functions
WorkOS::SessionCookie.split_session_cookie(name, value, existing_names, max_total_size, max_cookie_size = DEFAULT_MAX_COOKIE_SIZE)gives aWorkOS::SessionCookie::SplitResult. Itscookiesmember has the pairs of cookie name and cookie value to write. Itsstale_namesmember has the cookie names to delete.WorkOS::SessionCookie.join_session_cookie(name, cookies)gives the sealed session from the request cookies, ornil.WorkOS::SessionCookie.session_cookie_names(name, existing_names)gives each cookie name of the session, for a logout.WorkOS::SessionCookie::DEFAULT_MAX_COOKIE_SIZEis 3936: 4096 bytes minus 160 bytes for the cookie attributes.existing_namesandmax_total_sizehave no default.existing_namesis an Enumerable of cookie names, or the request cookies (a Hash, or the cookie jar of Rails).cookiesis an object that has the[]method with a String key.SplitResultis aDataobject, and each Array that the functions give is frozen.rbi/workos/session_cookie.rbihas the signatures. In a local run, Sorbet 0.6.13672 accepted a typed caller of each function. The doc comment ofWorkOS::SessionCookieand a new README section have the rules for the application.Cookies of a session
name. If the session fits in one cookie, the head cookie has the sealed value, and there is no other cookie.chunks-N-T. The chunk cookiesname_0toname_{N-1}then have the parts of the sealed value.Nis the count of the chunk cookies, 999 at most.Tis the tag: the first 16 hexadecimal characters of the SHA-256 digest of the sealed value.join_session_cookiereads the head cookie and then only the chunk cookies that the marker names. It givesnilif the head cookie or a chunk cookie is absent or empty, or if the parts together are not valid UTF-8. It also givesnilif the tag of the parts is not equal toT.Example (a Rails controller;
sealedis the result ofseal_session_from_auth_response)Limits
Cookierequest header, and the server sends them inSet-Cookieresponse headers.max_total_size: the largest size, in bytes, that all cookies of the session can have together.split_session_cookieraisesArgumentErrorif the cookies together are larger thanmax_total_size. It then gives no cookie to write.max_total_sizeis the smaller of two numbers: the request limit and the response limit. The doc comment ofWorkOS::SessionCookietells how to calculate each number from the limits of the server and of each proxy.80 * 1024(81,920) bytes for one header value (FIELD_VALUEinext/puma_http11/puma_http11.c).Cookieheader value of 81,920 bytes. It gave status 400 for 81,921 bytes.large_client_header_bufferswith the default4 8k. A local run with that default also sent each request in pieces of 16 bytes. nginx accepted aCookieheader value of 8182 bytes and gave status 400 for 8183 bytes.proxy_buffer_size. In a local run withproxy_buffer_size 8k, nginx gave status 502 for response headers that were too large for that buffer.=and the value. Each byte that is not an ASCII letter, a digit,-,_or.counts as 3 bytes. A framework can write such a byte in the percent-encoded form. Thus the size is an upper limit. In a local run on Rails 8.1.4.1 with Rack 3.2.9, the session cookies in theCookieheader had exactly the calculated size. Do not increasemax_total_sizefor a framework that writes fewer bytes.stale_namesin the same response that writescookies. The size check counts only the cookies incookies. If a chunk cookie ofstale_namesstays in the browser, the subsequentCookieheader can be larger than the limit of the server.stale_nameshas each request cookie name of the formname_<digits>that the new session does not use. Each deletion adds oneSet-Cookieline to the response.split_session_cookieraisesArgumentErrorbecause ofmax_total_size, write no session cookie. The browser then keeps the cookies of the earlier session, andjoin_session_cookiegives that earlier value on the subsequent request. Then delete the session cookies (session_cookie_names) so that the user signs in again, or keep the earlier session.split_session_cookieraisesArgumentError.pathanddomainoptions as for the write. In the Rails run, the attributes of one cookie had 40 bytes.join_session_cookieneeds the decoded cookie values. Write and read the cookies with the cookie functions of one framework.name_0,name_1and so on.join_session_cookiegivesnil. The user then signs in again.Deploy sequence (for an application with more than one instance)
join_session_cookieand writes the session in one cookie. When this version writes or deletes that cookie, it also deletes each other name thatsession_cookie_namesgives.split_session_cookie.A version that does not use
join_session_cookiecannot read a session in chunks. It reads the marker as the sealed value, andauthenticategives the reasoninvalid_session_cookie. Rollback hazard: a version that does not delete the chunk cookies leaves them in the browser. TheCookieheader can then be larger than the limit of the server. Roll back only to the version of step 1.Compatibility
split_session_cookiegives one cookie with the namename. Its value is the sealed value with no change. If the head value is not a marker,join_session_cookiegives that value with no change. Thus it also reads a cookie that an earlier application version wrote.WorkOS::SessionCookie, its three functions,SplitResultandDEFAULT_MAX_COOKIE_SIZE. They change no other public name, parameter, return type, default or error.digest, and the tag comparison usesOpenSSL.fixed_length_secure_compare. The SDK already uses the two libraries.workos.gemspecandGemfile.lockdo not change.workos.gemspecputs each tracked file in the gem, so the gem also has the test fixture file (567,304 bytes). In a local build, the gem file increased from 375,296 to 451,584 bytes.Tests of the helpers
test/workos/test_session_cookie.rbhas 1365 tests. They pass on Ruby 3.3.11, 3.4.11 and 4.0.0 in a local run, and they make no network request.test/fixtures/session_cookie_cases.json: 642 forsplit_session_cookie, 509 forjoin_session_cookie, 134 forsession_cookie_names, and 42 sequences of write, read and logout. 429 of these cases assertArgumentError.join_session_cookiegives the value thatsplit_session_cookiegot, and that no cookie is larger thanmax_cookie_size. The second asserts the same value when cookies of an earlier session stay in the request. The third asserts that one different character in a chunk cookie givesnil.join_session_cookiegivesniland no error for a marker with an absent chunk cookie and for 10,000 chunk cookies with no head cookie. It also gives no error for a cookie value that is not a String. A request cookie with a name or a value that is not valid UTF-8 also gives no error..,*,+,^or|operates as plain text.lib/workos/session_cookie.rbhas no regular expression.seal_session_from_auth_response.split_session_cookieandjoin_session_cookiethen give the same sealed value again, andunseal_datagives the access token.cookiesjar. A sealed session of 5484 bytes used 3 cookies, and one of 9884 bytes used 4 cookies.join_session_cookiegave the sealed value after each write. Noname=valuepair in aSet-Cookieline was larger than 3936 bytes.Renovate
renovate.jsonhas one new package rule. It is for this package:jwt.scheduleto any time. Each other dependency keeps the monthly schedule of the shared preset.internalChecksFiltertonone. Thus Renovate opens the pull request before the release has the minimum release age of the shared preset, and automerge waits for that age.fix(deps:crypto). Thus a merge of such an update makes a patch release.Documentation
Does this require changes to the WorkOS Docs? E.g. the API Reference or code snippets need updates.
If yes, link a related docs PR and add a docs maintainer as a reviewer. Their approval is required.