-
Notifications
You must be signed in to change notification settings - Fork 2
ENG-30: Refresh token #42
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
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b9257cc
Style
langsamu 332064f
Extract
langsamu bff1eb8
Rearrange
langsamu d74f833
Refresh
langsamu cac016d
Remind documenting separating cache by client
langsamu 5c15c17
Cache authorization server alongside tokens
langsamu eb5a653
Use cache entry for refreshing
langsamu 80497d7
Merge branch 'refs/heads/main' into refresh_token
langsamu 169c015
Invalidate cache on token refresh failure
langsamu b5cde2e
Don't reuse refresh tokens
langsamu ba63ecd
Merge branch 'refs/heads/main' into refresh_token
langsamu ab02c07
Don't abort refresh
langsamu 55990f9
Reuse cached refresh token unless rotated
langsamu aa66ad3
Invalidate cache on token refresh failure
langsamu d0c9688
Remind about lock scope
langsamu 47c1367
Minimize construction
langsamu 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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,12 +6,21 @@ import type { AuthorizationServerProvider } from "./AuthorizationServerProvider. | |
| import { ClientProvider } from "./ClientProvider.js" | ||
| import { supportsOfflineAccess } from "./supportsOfflineAccess.js" | ||
|
|
||
| type CacheEntry = { created: number, tokenResult: oauth.TokenEndpointResponse, dpopKey: CryptoKeyPair } | ||
| type CacheEntry = { | ||
| created: number, | ||
| tokenResult: oauth.TokenEndpointResponse, | ||
| dpopKey: CryptoKeyPair, | ||
| client: oauth.Client, | ||
| authorizationServer: oauth.AuthorizationServer, | ||
| } | ||
|
|
||
| export class DPoPTokenProvider implements TokenProvider { | ||
| readonly #codeProvider: CodeProvider | ||
| readonly #callbackUri: string | ||
| readonly #cache = new Map<string, CacheEntry> // TODO: Take cache from caller | ||
|
|
||
| // TODO: Take cache from caller | ||
| // TODO: Once cache is externalized, document that it should not be shared between clients (which would lead to impersonation) | ||
| readonly #cache = new Map<string, CacheEntry> | ||
| readonly #asProvider: AuthorizationServerProvider | ||
| readonly #clientProvider: ClientProvider | ||
|
|
||
|
|
@@ -27,20 +36,43 @@ export class DPoPTokenProvider implements TokenProvider { | |
| } | ||
|
|
||
| async upgrade(request: Request): Promise<Request> { | ||
| // Form a queue per request URI to never reuse refresh tokens. | ||
| // TODO: Revise scope (origin+requestUri) of this lock which might interfere with scenarios that are not bound to origin | ||
| const lockName = `DPoPTokenProvider.upgrade[${request.url}]` | ||
|
jeswr marked this conversation as resolved.
|
||
| const {dpopKey, tokenResult: {access_token}} = await navigator.locks.request(lockName, async _ => | ||
|
langsamu marked this conversation as resolved.
|
||
| await this.getCachedToken(request)) | ||
|
|
||
| const headers = new Headers(request.headers) | ||
|
|
||
| headers.set("DPoP", await DPoP.generateProof(dpopKey, request.url, request.method, undefined, access_token)) | ||
| headers.set("Authorization", ["DPoP", access_token].join(" ")) | ||
|
|
||
| return new Request(request, {headers}) | ||
| } | ||
|
|
||
| private async getCachedToken(request: Request): Promise<CacheEntry> { | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is the substantial change: flowchart TD
start(["Get token"])
getCached["Get token from cache"]
found{"Cached token exists?"}
valid{"Cached token valid?"}
refresh[["Refresh token"]]
refreshed{"Refresh succeed?"}
storeRefreshed["Cache refreshed token"]
obtain[["Get new token"]]
storeNew["Cache new token"]
useRefreshed(["Use refreshed token"])
useCached(["Use cached token"])
useNew(["Use new token"])
start --> getCached
getCached --> found
found -- no --> refresh
found -- yes --> valid
valid -- no --> refresh
valid -- yes --> useCached
refresh --> refreshed
refreshed -- no --> obtain
refreshed -- yes --> storeRefreshed
storeRefreshed --> useRefreshed
obtain --> storeNew
storeNew --> useNew
storeNew ~~~ useCached
storeNew ~~~ useRefreshed
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This logic diagram is super helpful, let's reuse it for documentation of the library when relevant. |
||
| // TODO: More robust key via callback to support complex caching scenarios | ||
| let tokenData = this.#cache.get(request.url) | ||
| const cached = this.#cache.get(request.url) | ||
|
|
||
| // TODO: Support actively refreshing the token | ||
| if (tokenData === undefined || isExpired(tokenData)) { | ||
| tokenData = await this.obtainToken(request) | ||
| this.#cache.set(request.url, tokenData) | ||
| if (cached !== undefined) { | ||
| if (!isExpired(cached)) { | ||
| return cached | ||
| } | ||
|
|
||
| const refreshed = await this.refreshToken(cached, request) | ||
| if (refreshed !== undefined) { | ||
| this.#cache.set(request.url, refreshed) | ||
| return refreshed | ||
| } | ||
| } | ||
|
|
||
| const headers = new Headers(request.headers) | ||
| const fresh = await this.obtainToken(request) | ||
| this.#cache.set(request.url, fresh) | ||
|
|
||
| headers.set("DPoP", await DPoP.generateProof(tokenData.dpopKey, request.url, request.method, undefined, tokenData.tokenResult.access_token)) | ||
| headers.set("Authorization", ["DPoP", tokenData.tokenResult.access_token].join(" ")) | ||
| return new Request(request, {headers}) | ||
| return fresh | ||
| } | ||
|
|
||
| private async obtainToken(request: Request): Promise<CacheEntry> { | ||
| const authorizationServer = await this.#asProvider.getAuthorizationServer(request) | ||
|
|
||
|
|
@@ -106,7 +138,40 @@ export class DPoPTokenProvider implements TokenProvider { | |
|
|
||
| const tokenResult = await oauth.processAuthorizationCodeResponse(authorizationServer, clientRegistration, tokenResponse, {expectedNonce: this.nonceVerificationOverride(authorizationServer.issuer, nonce)}) | ||
|
|
||
| return {created: Date.now(), tokenResult, dpopKey} | ||
| return {created: Date.now(), tokenResult, dpopKey, client: clientRegistration, authorizationServer} | ||
| } | ||
|
|
||
| private async refreshToken(cached: CacheEntry, request: Request): Promise<CacheEntry | undefined> { | ||
| if (cached.tokenResult.refresh_token === undefined) { | ||
| return undefined | ||
| } | ||
|
|
||
| const dpop = oauth.DPoP({}, cached.dpopKey) | ||
| const options = {DPoP: dpop} | ||
|
|
||
| let tokenResult: oauth.TokenEndpointResponse | ||
| try { | ||
| const tokenResponse = await oauth.refreshTokenGrantRequest(cached.authorizationServer, cached.client, this.getClientAuth(cached.authorizationServer.issuer, cached.client), cached.tokenResult.refresh_token, options) | ||
| tokenResult = await oauth.processRefreshTokenResponse(cached.authorizationServer, cached.client, tokenResponse) | ||
| } catch (e) { | ||
| this.#cache.delete(request.url) | ||
|
|
||
| if (e instanceof oauth.ResponseBodyError && e.error === "invalid_grant") { | ||
| console.debug("Access token could not be refreshed") | ||
|
|
||
| return undefined | ||
| } | ||
|
|
||
| throw e | ||
|
langsamu marked this conversation as resolved.
|
||
| } | ||
|
|
||
| // Reuse cached refreshed token if it wasn't rotated (token result didn't have one) | ||
| if (tokenResult.refresh_token === undefined) { | ||
| // Leave rest of token result intact | ||
| tokenResult = {...tokenResult, refresh_token: cached.tokenResult.refresh_token} | ||
| } | ||
|
|
||
| return {created: Date.now(), tokenResult, dpopKey: cached.dpopKey, client: cached.client, authorizationServer: cached.authorizationServer} | ||
| } | ||
|
|
||
| private getClientAuth(issuer: string, client: oauth.OmitSymbolProperties<oauth.Client>): oauth.ClientAuth { | ||
|
|
||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.