Skip to content

Commit

Permalink
fix(workerd): avoid "The script will never generate a response" edge …
Browse files Browse the repository at this point in the history
…cases completely

closes #355
closes #509
  • Loading branch information
panva committed Mar 2, 2023
1 parent 2421496 commit 96a8c99
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 28 deletions.
44 changes: 17 additions & 27 deletions src/jwks/remote.ts
Expand Up @@ -103,36 +103,26 @@ class RemoteJWKSet<T extends KeyLike = KeyLike> extends LocalJWKSet<T> {
}

async reload() {
// see https://github.com/panva/jose/issues/355
// Do not assume a fetch created in another request reliably resolves
// see https://github.com/panva/jose/issues/355 and https://github.com/panva/jose/issues/509
if (this._pendingFetch && isCloudflareWorkers()) {
return new Promise<void>((resolve) => {
const isDone = () => {
if (this._pendingFetch === undefined) {
resolve()
} else {
setTimeout(isDone, 5)
}
}
isDone()
})
this._pendingFetch = undefined
}

if (!this._pendingFetch) {
this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options)
.then((json) => {
if (!isJWKSLike(json)) {
throw new JWKSInvalid('JSON Web Key Set malformed')
}

this._jwks = { keys: json.keys }
this._jwksTimestamp = Date.now()
this._pendingFetch = undefined
})
.catch((err: Error) => {
this._pendingFetch = undefined
throw err
})
}
this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options)
.then((json) => {
if (!isJWKSLike(json)) {
throw new JWKSInvalid('JSON Web Key Set malformed')
}

this._jwks = { keys: json.keys }
this._jwksTimestamp = Date.now()
this._pendingFetch = undefined
})
.catch((err: Error) => {
this._pendingFetch = undefined
throw err
})

await this._pendingFetch
}
Expand Down
2 changes: 1 addition & 1 deletion tap/jwks.ts
Expand Up @@ -16,7 +16,7 @@ export default (QUnit: QUnit, lib: typeof jose) => {
jwks({ kid: 'foo', alg: 'RS256' }),
'no applicable key found in the JSON Web Key Set',
)
t.ok(await jwks({ alg, kid }))
t.ok(await Promise.all([jwks({ alg, kid }), jwks({ alg, kid })]))
})

test('[createLocalJWKSet] establishes local JWKSet', async (t: typeof QUnit.assert) => {
Expand Down

0 comments on commit 96a8c99

Please sign in to comment.