-
Notifications
You must be signed in to change notification settings - Fork 2
feat: per-issuer session cache — stop re-running the full auth flow (popup included) on every 401 #11
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
Draft
jeswr
wants to merge
2
commits into
main
Choose a base branch
from
feat/dpop-session-cache
base: main
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.
Draft
feat: per-issuer session cache — stop re-running the full auth flow (popup included) on every 401 #11
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,11 +4,44 @@ import type { GetCodeCallback } from "./GetCodeCallback.js" | |
| import type { TokenProvider } from "./TokenProvider.js" | ||
| import type { GetIssuerCallback } from "./GetIssuerCallback.js" | ||
|
|
||
| /** The client metadata shape produced by dynamic client registration. */ | ||
| type ClientRegistration = Awaited<ReturnType<typeof oauth.processDynamicClientRegistrationResponse>> | ||
|
|
||
| /** Authentication state for one issuer, reused across upgrades. */ | ||
| interface IssuerSession { | ||
| authorizationServer: oauth.AuthorizationServer | ||
| clientRegistration: ClientRegistration | ||
| dpopKey: CryptoKeyPair | ||
| accessToken: string | ||
| /** Epoch milliseconds after which the access token is considered expired, or undefined when the server gave no expiry. */ | ||
| expiresAt: number | undefined | ||
| } | ||
|
|
||
| /** | ||
| * Refresh this much before the server-reported expiry, so clock skew between us | ||
| * and the resource server does not produce a window of rejected requests. | ||
| */ | ||
| const expirySkewMs = 30_000 | ||
|
|
||
| export class DPoPTokenProvider implements TokenProvider { | ||
| readonly #getCode: GetCodeCallback | ||
| readonly #callbackUri: string | ||
| readonly #getIssuer: GetIssuerCallback | ||
|
|
||
| /** | ||
| * Single-flight session cache per issuer: concurrent upgrades share one | ||
| * authorization-code flow (one popup), and later upgrades reuse the | ||
| * established token until it expires instead of re-running the flow. | ||
| */ | ||
| readonly #sessions = new Map<string, Promise<IssuerSession>>() | ||
|
|
||
| /** | ||
| * The shared authentication work is provider-owned, so it is deliberately | ||
| * not tied to any single request's AbortSignal — aborting one request must | ||
| * not cancel the login that other concurrent upgrades are waiting on. | ||
| */ | ||
| readonly #authSignal = new AbortController().signal | ||
|
|
||
| constructor(callbackUri: string, getCodeCallback: GetCodeCallback, getIssuerCallback: GetIssuerCallback) { | ||
| this.#getCode = getCodeCallback | ||
| this.#callbackUri = callbackUri | ||
|
|
@@ -21,11 +54,62 @@ export class DPoPTokenProvider implements TokenProvider { | |
|
|
||
| async upgrade(request: Request): Promise<Request> { | ||
| const issuer = await this.#getIssuer(request) | ||
| const session = await this.#session(issuer) | ||
|
|
||
| const headers = new Headers(request.headers) | ||
|
|
||
| headers.set("DPoP", await DPoP.generateProof(session.dpopKey, request.url, request.method, undefined, session.accessToken)) | ||
| headers.set("Authorization", ["DPoP", session.accessToken].join(" ")) | ||
|
|
||
| return new Request(request, {headers}) | ||
| } | ||
|
|
||
| /** | ||
| * Returns the cached session for the issuer, renewing it when expired and | ||
| * establishing it when absent. A failed flow is not cached, so the next | ||
| * upgrade retries. | ||
| */ | ||
| async #session(issuer: URL): Promise<IssuerSession> { | ||
|
Contributor
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. We need to think about whether we always want to be caching by issuer - I am not sure that this will always be the case. |
||
| const pending = this.#sessions.get(issuer.href) | ||
| if (pending === undefined) { | ||
| return this.#begin(issuer, this.#authenticate(issuer)) | ||
| } | ||
|
|
||
| const session = await pending | ||
| if (!hasExpired(session)) { | ||
| return session | ||
| } | ||
|
|
||
| // Renew, unless a concurrent caller already replaced the expired session. | ||
| if (this.#sessions.get(issuer.href) === pending) { | ||
| this.#sessions.delete(issuer.href) | ||
| return this.#begin(issuer, this.#authenticate(issuer)) | ||
| } | ||
|
|
||
| const discoveryResponse = await oauth.discoveryRequest(issuer, {signal: request.signal}) | ||
| return this.#session(issuer) | ||
| } | ||
|
|
||
| /** Caches the in-flight work; evicts it on failure so the flow can be retried. */ | ||
| async #begin(issuer: URL, work: Promise<IssuerSession>): Promise<IssuerSession> { | ||
| this.#sessions.set(issuer.href, work) | ||
| try { | ||
| return await work | ||
| } catch (e) { | ||
| if (this.#sessions.get(issuer.href) === work) { | ||
| this.#sessions.delete(issuer.href) | ||
| } | ||
| throw e | ||
| } | ||
| } | ||
|
|
||
| /** The full authorization-code flow: discovery → registration → PKCE/DPoP code grant. */ | ||
| async #authenticate(issuer: URL): Promise<IssuerSession> { | ||
| const signal = this.#authSignal | ||
|
|
||
| const discoveryResponse = await oauth.discoveryRequest(issuer, {signal}) | ||
| const authorizationServer = await oauth.processDiscoveryResponse(issuer, discoveryResponse) | ||
|
|
||
| const registrationResponse = await oauth.dynamicClientRegistrationRequest(authorizationServer, {redirect_uris: [this.#callbackUri]}, {signal: request.signal}) | ||
| const registrationResponse = await oauth.dynamicClientRegistrationRequest(authorizationServer, {redirect_uris: [this.#callbackUri]}, {signal}) | ||
| const clientRegistration = await oauth.processDynamicClientRegistrationResponse(registrationResponse) | ||
| const [registeredRedirectUri] = clientRegistration.redirect_uris as string[] | ||
| const [registeredResponseType] = clientRegistration.response_types as string[] | ||
|
|
@@ -56,7 +140,7 @@ export class DPoPTokenProvider implements TokenProvider { | |
| } | ||
| } | ||
|
|
||
| const authorizationCodeResponse = await this.#getCode(authorizationUrl, request.signal) | ||
| const authorizationCodeResponse = await this.#getCode(authorizationUrl, signal) | ||
|
|
||
| let authorizationCodeParams | ||
| try { | ||
|
|
@@ -72,23 +156,24 @@ export class DPoPTokenProvider implements TokenProvider { | |
| console.debug("Authorization server requires user interaction, retrying without prompt") | ||
|
|
||
| authorizationUrl.searchParams.delete("prompt") | ||
| const authorizationCodeResponse = await this.#getCode(authorizationUrl, request.signal) | ||
| const authorizationCodeResponse = await this.#getCode(authorizationUrl, signal) | ||
| authorizationCodeParams = oauth.validateAuthResponse(authorizationServer, clientRegistration, new URL(authorizationCodeResponse), state) | ||
| } else { | ||
| throw e | ||
| } | ||
| } | ||
|
|
||
| const tokenResponse = await oauth.authorizationCodeGrantRequest(authorizationServer, clientRegistration, this.getClientAuth(authorizationServer.issuer, clientRegistration), authorizationCodeParams, this.#callbackUri, authorizationServer.code_challenge_methods_supported !== undefined ? codeVerifier : oauth.nopkce, {DPoP: dpop, signal: request.signal}) | ||
| const tokenResponse = await oauth.authorizationCodeGrantRequest(authorizationServer, clientRegistration, this.getClientAuth(authorizationServer.issuer, clientRegistration), authorizationCodeParams, this.#callbackUri, authorizationServer.code_challenge_methods_supported !== undefined ? codeVerifier : oauth.nopkce, {DPoP: dpop, signal}) | ||
|
|
||
| const tokenResult = await oauth.processAuthorizationCodeResponse(authorizationServer, clientRegistration, tokenResponse, {expectedNonce: this.nonceVerificationOverride(authorizationServer.issuer, nonce)}) | ||
|
|
||
| const headers = new Headers(request.headers) | ||
|
|
||
| headers.set("DPoP", await DPoP.generateProof(dpopKey, request.url, request.method, undefined, tokenResult.access_token)) | ||
| headers.set("Authorization", ["DPoP", tokenResult.access_token].join(" ")) | ||
|
|
||
| return new Request(request, {headers}) | ||
| return { | ||
| authorizationServer, | ||
| clientRegistration, | ||
| dpopKey, | ||
| accessToken: tokenResult.access_token, | ||
| expiresAt: expiresAt(tokenResult), | ||
| } | ||
| } | ||
|
|
||
| private getClientAuth(issuer: string, client: oauth.OmitSymbolProperties<oauth.Client>): oauth.ClientAuth { | ||
|
|
@@ -112,6 +197,14 @@ export class DPoPTokenProvider implements TokenProvider { | |
| } | ||
| } | ||
|
|
||
| function expiresAt(token: oauth.TokenEndpointResponse): number | undefined { | ||
| return token.expires_in === undefined ? undefined : Date.now() + token.expires_in * 1000 - expirySkewMs | ||
| } | ||
|
|
||
| function hasExpired(session: IssuerSession): boolean { | ||
| return session.expiresAt !== undefined && Date.now() >= session.expiresAt | ||
| } | ||
|
jeswr marked this conversation as resolved.
|
||
|
|
||
| function isEssMissingIssInteractionNeeded(e: unknown) { | ||
| try { | ||
| return ((((e as oauth.OperationProcessingError).cause as any).parameters) as URLSearchParams).get("error") === "interaction_required" | ||
|
|
||
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,93 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" | ||
| import { DPoPTokenProvider } from "../src/DPoPTokenProvider.js" | ||
| import { createFakeAuthorizationServer, type FakeAuthorizationServer } from "./fakeAuthorizationServer.js" | ||
|
|
||
| const callbackUri = "https://app.test/callback.html" | ||
|
|
||
| let as: FakeAuthorizationServer | ||
|
|
||
| function makeProvider(getCode = vi.fn((url: URL) => as.authorize(url))) { | ||
| const provider = new DPoPTokenProvider(callbackUri, getCode, async () => new URL(as.issuer)) | ||
| return {provider, getCode} | ||
| } | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllGlobals() | ||
| vi.useRealTimers() | ||
| }) | ||
|
|
||
| describe("DPoPTokenProvider session cache", () => { | ||
| beforeEach(async () => { | ||
| as = await createFakeAuthorizationServer() | ||
| vi.stubGlobal("fetch", as.fetch) | ||
| }) | ||
|
|
||
| it("attaches a DPoP-bound access token to the upgraded request", async () => { | ||
| const {provider} = makeProvider() | ||
|
|
||
| const upgraded = await provider.upgrade(new Request("https://pod.test/private")) | ||
|
|
||
| expect(upgraded.headers.get("Authorization")).toMatch(/^DPoP at-\d+$/) | ||
| expect(upgraded.headers.get("DPoP")).toBeTruthy() | ||
| }) | ||
|
|
||
| it("runs the authorization flow once for concurrent upgrades (single-flight)", async () => { | ||
| const {provider, getCode} = makeProvider() | ||
|
|
||
| await Promise.all([ | ||
| provider.upgrade(new Request("https://pod.test/a")), | ||
| provider.upgrade(new Request("https://pod.test/b")), | ||
| provider.upgrade(new Request("https://pod.test/c")), | ||
| ]) | ||
|
|
||
| expect(getCode).toHaveBeenCalledTimes(1) | ||
| expect(as.registrations).toHaveLength(1) | ||
| }) | ||
|
|
||
| it("reuses the established session for later upgrades instead of re-prompting", async () => { | ||
| const {provider, getCode} = makeProvider() | ||
|
|
||
| const first = await provider.upgrade(new Request("https://pod.test/a")) | ||
| const second = await provider.upgrade(new Request("https://pod.test/b")) | ||
|
|
||
| expect(getCode).toHaveBeenCalledTimes(1) | ||
| expect(second.headers.get("Authorization")).toBe(first.headers.get("Authorization")) | ||
| }) | ||
|
|
||
| it("signs a fresh DPoP proof per request while reusing the access token", async () => { | ||
| const {provider} = makeProvider() | ||
|
|
||
| const first = await provider.upgrade(new Request("https://pod.test/a")) | ||
| const second = await provider.upgrade(new Request("https://pod.test/b")) | ||
|
|
||
| expect(second.headers.get("DPoP")).not.toBe(first.headers.get("DPoP")) | ||
| }) | ||
|
|
||
| it("re-authenticates once the access token has expired", async () => { | ||
| const {provider, getCode} = makeProvider() | ||
|
|
||
| const first = await provider.upgrade(new Request("https://pod.test/a")) | ||
|
|
||
| // Step past the reported expiry (minus the skew allowance). | ||
| vi.useFakeTimers() | ||
| vi.setSystemTime(Date.now() + 3601 * 1000) | ||
|
|
||
| const second = await provider.upgrade(new Request("https://pod.test/b")) | ||
|
|
||
| expect(getCode).toHaveBeenCalledTimes(2) | ||
| expect(second.headers.get("Authorization")).not.toBe(first.headers.get("Authorization")) | ||
| }) | ||
|
|
||
| it("does not cache a failed flow: the next upgrade retries", async () => { | ||
| const getCode = vi.fn((url: URL) => as.authorize(url)) | ||
| getCode.mockRejectedValueOnce(new Error("user closed the popup")) | ||
| const {provider} = makeProvider(getCode) | ||
|
|
||
| await expect(provider.upgrade(new Request("https://pod.test/a"))).rejects.toThrow("user closed the popup") | ||
|
|
||
| const second = await provider.upgrade(new Request("https://pod.test/b")) | ||
|
|
||
| expect(second.headers.get("Authorization")).toMatch(/^DPoP at-\d+$/) | ||
| expect(getCode).toHaveBeenCalledTimes(2) | ||
| }) | ||
| }) |
Oops, something went wrong.
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.
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.
Rather than caching being in-memory only; we should have configurable
CacheProvidersto enable context specific caching including: