Skip to content

Commit

Permalink
fix a refresh token race condition (#4695)
Browse files Browse the repository at this point in the history
that would be triggered when uploading multiple files in parallell
if a 401 occurs, it would cause multiple refresh-token requests to be fired in parallel
also only call refresh-token if we have a token
and reset the token if refresh-token fails with 401
  • Loading branch information
mifi authored Sep 25, 2023
1 parent 87a28ed commit b1e4a5b
Showing 1 changed file with 25 additions and 14 deletions.
39 changes: 25 additions & 14 deletions packages/@uppy/companion-client/src/Provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,22 +161,33 @@ export default class Provider extends RequestClient {

try {
// throw Object.assign(new Error(), { isAuthError: true }) // testing simulate access token expired (to refresh token)
// A better way to test this is for example with Google Drive:
// While uploading, go to your google account settings,
// "Third-party apps & services", then click "Companion" and "Remove access".

return await super.request(...args)
} catch (err) {
if (!err.isAuthError) throw err // only handle auth errors (401 from provider)

await this.#refreshingTokenPromise

// Many provider requests may be starting at once, however refresh token should only be called once.
// Once a refresh token operation has started, we need all other request to wait for this operation (atomically)
this.#refreshingTokenPromise = (async () => {
try {
const response = await super.request({ path: this.refreshTokenUrl(), method: 'POST' })
await this.setAuthToken(response.uppyAuthToken)
} finally {
this.#refreshingTokenPromise = undefined
}
})()
// only handle auth errors (401 from provider), and only handle them if we have a (refresh) token
if (!err.isAuthError || !(await this.#getAuthToken())) throw err

if (this.#refreshingTokenPromise == null) {
// Many provider requests may be starting at once, however refresh token should only be called once.
// Once a refresh token operation has started, we need all other request to wait for this operation (atomically)
this.#refreshingTokenPromise = (async () => {
try {
const response = await super.request({ path: this.refreshTokenUrl(), method: 'POST' })
await this.setAuthToken(response.uppyAuthToken)
} catch (refreshTokenErr) {
if (refreshTokenErr.isAuthError) {
// if refresh-token has failed with auth error, delete token, so we don't keep trying to refresh in future
await this.#removeAuthToken()
}
throw err
} finally {
this.#refreshingTokenPromise = undefined
}
})()
}

await this.#refreshingTokenPromise

Expand Down

0 comments on commit b1e4a5b

Please sign in to comment.