Repository navigation
perf(auth): reuse the imported key and join concurrent JWKS requests in getClaims() #3016
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
martijn00
wants to merge
1
commit into
supabase:master
Choose a base branch
from
martijn00:perf/auth-getclaims-key-cache
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+277
−11
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
194 changes: 194 additions & 0 deletions
194
packages/core/auth-js/test/GoTrueClient.getClaimsCache.test.ts
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| import GoTrueClient from '../src/GoTrueClient' | ||
| import type { JWK } from '../src/lib/types' | ||
|
|
||
| const b64url = (input: string | Uint8Array) => Buffer.from(input).toString('base64url') | ||
|
|
||
| type Signer = { jwk: JWK; sign: (payload?: object) => Promise<string> } | ||
|
|
||
| async function createSigner(kid: string): Promise<Signer> { | ||
| const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [ | ||
| 'sign', | ||
| 'verify', | ||
| ]) | ||
| const jwk = { | ||
| ...(await crypto.subtle.exportKey('jwk', pair.publicKey)), | ||
| kid, | ||
| alg: 'ES256', | ||
| use: 'sig', | ||
| } as unknown as JWK | ||
|
|
||
| return { | ||
| jwk, | ||
| async sign(payload: object = {}) { | ||
| const header = b64url(JSON.stringify({ alg: 'ES256', kid, typ: 'JWT' })) | ||
| const body = b64url( | ||
| JSON.stringify({ | ||
| sub: 'user-1', | ||
| role: 'authenticated', | ||
| exp: Math.floor(Date.now() / 1000) + 3600, | ||
| ...payload, | ||
| }) | ||
| ) | ||
| const signature = await crypto.subtle.sign( | ||
| { name: 'ECDSA', hash: 'SHA-256' }, | ||
| pair.privateKey, | ||
| Buffer.from(`${header}.${body}`) | ||
| ) | ||
| return `${header}.${body}.${b64url(new Uint8Array(signature))}` | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // Every test uses its own storage key, so the JWKS cache (shared per storage key) starts empty. | ||
| let clientCounter = 0 | ||
| const nextStorageKey = () => `getclaims-cache-${++clientCounter}` | ||
|
|
||
| function jwksFetch(keys: () => JWK[]) { | ||
| return jest.fn(async () => { | ||
| // Answer on a later tick, like a real request would | ||
| await new Promise((resolve) => setTimeout(resolve, 5)) | ||
| return new Response(JSON.stringify({ keys: keys() }), { | ||
| status: 200, | ||
| headers: { 'content-type': 'application/json' }, | ||
| }) | ||
| }) | ||
| } | ||
|
|
||
| function createClient(storageKey: string, fetch: jest.Mock) { | ||
| return new GoTrueClient({ | ||
| url: 'http://localhost:9999', | ||
| autoRefreshToken: false, | ||
| persistSession: false, | ||
| storageKey, | ||
| fetch: fetch as unknown as typeof globalThis.fetch, | ||
| }) | ||
| } | ||
|
|
||
| describe('getClaims() key and JWKS reuse', () => { | ||
| let importKey: jest.SpyInstance | ||
|
|
||
| beforeEach(() => { | ||
| importKey = jest.spyOn(crypto.subtle, 'importKey') | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| importKey.mockRestore() | ||
| jest.restoreAllMocks() | ||
| }) | ||
|
|
||
| describe('imported key', () => { | ||
| test('imports the signing key once for repeated calls', async () => { | ||
| const signer = await createSigner('key-1') | ||
| const fetch = jwksFetch(() => [signer.jwk]) | ||
| const client = createClient(nextStorageKey(), fetch) | ||
|
|
||
| for (let i = 0; i < 5; i++) { | ||
| const { data, error } = await client.getClaims(await signer.sign({ n: i })) | ||
| expect(error).toBeNull() | ||
| expect(data?.claims.n).toBe(i) | ||
| } | ||
|
|
||
| expect(importKey).toHaveBeenCalledTimes(1) | ||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| test('a reused key still rejects a token with a bad signature', async () => { | ||
| const signer = await createSigner('key-1') | ||
| const other = await createSigner('key-1') // same kid, different key | ||
| const client = createClient( | ||
| nextStorageKey(), | ||
| jwksFetch(() => [signer.jwk]) | ||
| ) | ||
|
|
||
| expect((await client.getClaims(await signer.sign())).error).toBeNull() | ||
|
|
||
| const { data, error } = await client.getClaims(await other.sign()) | ||
| expect(data).toBeNull() | ||
| expect(error?.name).toBe('AuthInvalidJwtError') | ||
| expect(importKey).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| test('imports again when the JWKS is fetched again', async () => { | ||
| const first = await createSigner('key-1') | ||
| const second = await createSigner('key-2') | ||
| let keys = [first.jwk] | ||
| const fetch = jwksFetch(() => keys) | ||
| const client = createClient(nextStorageKey(), fetch) | ||
|
|
||
| expect((await client.getClaims(await first.sign())).error).toBeNull() | ||
|
|
||
| // The project rotates its key: a token with an unknown kid makes the client refetch | ||
| keys = [second.jwk, first.jwk] | ||
| expect((await client.getClaims(await second.sign())).error).toBeNull() | ||
| expect((await client.getClaims(await first.sign())).error).toBeNull() | ||
| expect((await client.getClaims(await second.sign())).error).toBeNull() | ||
|
|
||
| expect(fetch).toHaveBeenCalledTimes(2) | ||
| // key-1 from the first JWKS, then key-2 and key-1 from the second | ||
| expect(importKey).toHaveBeenCalledTimes(3) | ||
| }) | ||
|
|
||
| test('reuses the key of a jwks object passed by the caller, per object', async () => { | ||
| const signer = await createSigner('key-1') | ||
| const other = await createSigner('key-1') // same kid, different key | ||
| const fetch = jwksFetch(() => []) | ||
| const client = createClient(nextStorageKey(), fetch) | ||
| const jwks = { keys: [signer.jwk] } | ||
|
|
||
| for (let i = 0; i < 3; i++) { | ||
| expect((await client.getClaims(await signer.sign(), { jwks })).error).toBeNull() | ||
| } | ||
| expect(importKey).toHaveBeenCalledTimes(1) | ||
|
|
||
| // A different JWK object is a different key, even with the same kid | ||
| const result = await client.getClaims(await signer.sign(), { jwks: { keys: [other.jwk] } }) | ||
| expect(result.error?.name).toBe('AuthInvalidJwtError') | ||
| expect(importKey).toHaveBeenCalledTimes(2) | ||
| expect(fetch).not.toHaveBeenCalled() | ||
| }) | ||
| }) | ||
|
|
||
| describe('in-flight JWKS request', () => { | ||
| test('concurrent calls on a cold client send one request', async () => { | ||
| const signer = await createSigner('key-1') | ||
| const fetch = jwksFetch(() => [signer.jwk]) | ||
| const client = createClient(nextStorageKey(), fetch) | ||
| const jwt = await signer.sign() | ||
|
|
||
| const results = await Promise.all(Array.from({ length: 10 }, () => client.getClaims(jwt))) | ||
|
|
||
| for (const { data, error } of results) { | ||
| expect(error).toBeNull() | ||
| expect(data?.claims.sub).toBe('user-1') | ||
| } | ||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| test('a failed request fails the calls that joined it, and the next call tries again', async () => { | ||
| const signer = await createSigner('key-1') | ||
| const ok = jwksFetch(() => [signer.jwk]) | ||
| let down = true | ||
| const fetch = jest.fn(async () => { | ||
| if (down) { | ||
| await new Promise((resolve) => setTimeout(resolve, 5)) | ||
| throw new TypeError('fetch failed') | ||
| } | ||
| return ok() | ||
| }) | ||
| const client = createClient(nextStorageKey(), fetch) | ||
| const jwt = await signer.sign() | ||
|
|
||
| const failed = await Promise.all([client.getClaims(jwt), client.getClaims(jwt)]) | ||
| for (const { data, error } of failed) { | ||
| expect(data).toBeNull() | ||
| expect(error?.name).toBe('AuthRetryableFetchError') | ||
| } | ||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
|
|
||
| down = false | ||
| const { error } = await client.getClaims(jwt) | ||
| expect(error).toBeNull() | ||
| expect(fetch).toHaveBeenCalledTimes(2) | ||
| }) | ||
| }) | ||
| }) |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cached keys can outlive in-place JWK changes in caller-supplied JWKS.
importVerificationKeyreturns the cached key for a JWK object andalgwithout checking the key material.getClaims()passes the caller'soptions.jwksoroptions.keysobjects by reference, so the cache key is the caller's object. If a caller replaces a JWK's key material in place and keeps itskid, tokens signed with the new key are rejected. Tokens signed with the replaced key continue to verify. Before this change, each call imported the current material.The public
getClaims()contract does not state that supplied JWK objects are immutable. The helper's JSDoc does, but that does not bind public callers.The cache must not return a key that was imported from different key material. Either detect material changes on a cache hit, or stop reusing keys for caller-supplied objects. Alternatively, document and enforce immutability as part of the public
getClaims()contract. The choice among these options is open. Each option must prevent a stale key from verifying tokens.Source: Learnings