Skip to content
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

Fix concurrent token renewal issues #10794

Merged
merged 2 commits into from
Jun 24, 2022
Merged
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
22 changes: 19 additions & 3 deletions components/server/src/user/token-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,33 @@ export class TokenService implements TokenProvider {
});
}

protected getTokenForHostCache = new Map<string, Promise<Token>>();

async getTokenForHost(user: User, host: string): Promise<Token> {
// (AT) when it comes to token renewal, the awaited http requests may
// cause "parallel" calls to repeat the renewal, which will fail.
// Caching for pending operations should solve this issue.
const key = `${host}-${user.id}`;
let promise = this.getTokenForHostCache.get(key);
if (!promise) {
promise = this.doGetTokenForHost(user, host);
this.getTokenForHostCache.set(key, promise);
promise.finally(() => this.getTokenForHostCache.delete(key));
}
return promise;
}

async doGetTokenForHost(user: User, host: string): Promise<Token> {
const identity = this.getIdentityForHost(user, host);
let token = await this.userDB.findTokenForIdentity(identity);
if (!token) {
throw new Error(
`No token found for user ${identity.authProviderId}/${identity.authId}/${identity.authName}!`,
);
}
const refreshTime = new Date();
refreshTime.setTime(refreshTime.getTime() + 30 * 60 * 1000);
if (token.expiryDate && token.expiryDate < refreshTime.toISOString()) {
const aboutToExpireTime = new Date();
aboutToExpireTime.setTime(aboutToExpireTime.getTime() + 5 * 60 * 1000);
if (token.expiryDate && token.expiryDate < aboutToExpireTime.toISOString()) {
Comment on lines +55 to +57
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was this renamed?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renaming was not necessary, but that reflect the purpose of this time, while refreshTime does not.

Also note the change from 30 to 5 minutes before expiration.

const { authProvider } = this.hostContextProvider.get(host)!;
if (authProvider.refreshToken) {
await authProvider.refreshToken(user);
Expand Down