From a946cb09245a2494df9d24548d2757f514fa7bce Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:48:03 +0000 Subject: [PATCH 1/5] Cache the federation-exchanged token in FederationProvider FederationProvider performed an RFC 8693 token exchange on every getToken() call, which the Thrift path issues per HTTP request. Cache the exchanged token and reuse it while the subject token is unchanged and the exchanged token is not within the 5-minute refresh threshold shared with CachedTokenProvider. Concurrent callers share one in-flight exchange, and failures or fallback results are never cached, so the next call re-attempts. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 1 + .../auth/tokenProvider/CachedTokenProvider.ts | 2 +- .../auth/tokenProvider/FederationProvider.ts | 107 +++++++- .../tokenProvider/FederationProvider.test.ts | 244 ++++++++++++++++++ 4 files changed, 343 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2a9bfc0..ba242750 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- With token federation enabled, the exchanged token is now cached and reused until it nears expiry or the subject token changes, instead of exchanging a new token on every request. - Preserve wide negative DECIMAL values exactly with `preserveBigNumericPrecision: true`, including nested arrays and structs, on both backends. The default number conversion is unchanged. - Kernel backend: `port` is passed to the kernel as is, so a custom port works over HTTPS as on Thrift. IPv6 hosts need brackets, an invalid port or host fails with a `ParameterError`, and the published `@databricks/databricks-sql-kernel-*` native packages must be bumped to a release that includes databricks/databricks-sql-kernel#505, since older packages ignore `port`. - Release completed Thrift CloudFetch body-reader listeners so idle connections do not retain downloaded result buffers. diff --git a/lib/connection/auth/tokenProvider/CachedTokenProvider.ts b/lib/connection/auth/tokenProvider/CachedTokenProvider.ts index 7172ea0b..56bad702 100644 --- a/lib/connection/auth/tokenProvider/CachedTokenProvider.ts +++ b/lib/connection/auth/tokenProvider/CachedTokenProvider.ts @@ -5,7 +5,7 @@ import Token from './Token'; * Default refresh threshold in milliseconds (5 minutes). * Tokens will be refreshed when they are within this threshold of expiring. */ -const DEFAULT_REFRESH_THRESHOLD_MS = 5 * 60 * 1000; +export const DEFAULT_REFRESH_THRESHOLD_MS = 5 * 60 * 1000; /** * A token provider that wraps another provider with automatic caching. diff --git a/lib/connection/auth/tokenProvider/FederationProvider.ts b/lib/connection/auth/tokenProvider/FederationProvider.ts index 62adbd9a..0aa168d7 100644 --- a/lib/connection/auth/tokenProvider/FederationProvider.ts +++ b/lib/connection/auth/tokenProvider/FederationProvider.ts @@ -1,5 +1,6 @@ import http from 'http'; import nodeFetch from 'node-fetch'; +import { DEFAULT_REFRESH_THRESHOLD_MS } from './CachedTokenProvider'; import ITokenProvider from './ITokenProvider'; import Token from './Token'; import { getJWTIssuer, isSameHost } from './utils'; @@ -33,6 +34,12 @@ const SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt'; */ const DEFAULT_SCOPE = 'sql'; +/** + * Lifetime assumed for an exchanged token when neither `expires_in` nor a JWT + * `exp` claim is available (1 hour). Mirrors the Python driver's default. + */ +const DEFAULT_EXCHANGED_TOKEN_TTL_MS = 60 * 60 * 1000; + /** * Timeout for token exchange requests in milliseconds. */ @@ -70,6 +77,10 @@ class TokenExchangeError extends Error { * A token provider that wraps another provider with automatic token federation. * When the base provider returns a token from a different issuer, this provider * exchanges it for a Databricks-compatible token using RFC 8693. + * + * The exchanged token is cached and reused while the subject token is unchanged + * and the exchanged token is not near expiry, so repeated calls do not trigger + * a network exchange every time. */ export default class FederationProvider implements ITokenProvider { private readonly baseProvider: ITokenProvider; @@ -80,8 +91,18 @@ export default class FederationProvider implements ITokenProvider { private readonly returnOriginalTokenOnFailure: boolean; + private readonly refreshThresholdMs: number; + private readonly getAgent?: (url: string) => Promise; + /** The last successful exchange result, keyed by the subject token it was exchanged from. */ + private cachedExchange: { subjectToken: string; token: Token } | null = null; + + /** In-flight exchange, shared by concurrent callers for the same subject token. */ + private exchangePromise: Promise | null = null; + + private exchangeSubjectToken: string | null = null; + /** * Creates a new FederationProvider. * @param baseProvider - The underlying token provider @@ -89,6 +110,7 @@ export default class FederationProvider implements ITokenProvider { * @param options - Optional configuration * @param options.clientId - Client ID for M2M/service principal federation * @param options.returnOriginalTokenOnFailure - Return original token if exchange fails (default: true) + * @param options.refreshThresholdMs - Re-exchange tokens this many ms before expiry (default: 5 minutes) * @param options.getAgent - Agent for the exchange request, so the connection's proxy and TLS options apply */ constructor( @@ -97,6 +119,7 @@ export default class FederationProvider implements ITokenProvider { options?: { clientId?: string; returnOriginalTokenOnFailure?: boolean; + refreshThresholdMs?: number; getAgent?: (url: string) => Promise; }, ) { @@ -104,6 +127,7 @@ export default class FederationProvider implements ITokenProvider { this.databricksHost = databricksHost; this.clientId = options?.clientId; this.returnOriginalTokenOnFailure = options?.returnOriginalTokenOnFailure ?? true; + this.refreshThresholdMs = options?.refreshThresholdMs ?? DEFAULT_REFRESH_THRESHOLD_MS; this.getAgent = options?.getAgent; } @@ -115,16 +139,26 @@ export default class FederationProvider implements ITokenProvider { return token; } - // Attempt token exchange - try { - return await this.exchangeToken(token); - } catch (error) { - if (this.returnOriginalTokenOnFailure) { - // Fall back to original token - return token; - } - throw error; + // Reuse the cached exchange while the subject token is unchanged and the + // exchanged token is not near expiry. + const cached = this.getCachedExchange(token.accessToken); + if (cached) { + return cached; + } + + // Coalesce concurrent callers so one subject token triggers a single + // exchange. A rejected in-flight promise is cleared, so later calls retry. + if (this.exchangePromise && this.exchangeSubjectToken === token.accessToken) { + return this.exchangePromise; } + + this.exchangeSubjectToken = token.accessToken; + this.exchangePromise = this.exchangeAndCache(token).finally(() => { + this.exchangePromise = null; + this.exchangeSubjectToken = null; + }); + + return this.exchangePromise; } getName(): string { @@ -152,6 +186,54 @@ export default class FederationProvider implements ITokenProvider { return true; } + /** + * Returns the cached exchanged token if it was exchanged from the given + * subject token and is not near expiry. + * @param subjectToken - The current subject token's access token + * @returns The cached exchanged token, or undefined if a new exchange is needed + */ + private getCachedExchange(subjectToken: string): Token | undefined { + const cached = this.cachedExchange; + if (!cached || cached.subjectToken !== subjectToken) { + return undefined; + } + return this.isNearExpiry(cached.token) ? undefined : cached.token; + } + + /** + * Determines if a token should be re-exchanged, using the same refresh + * threshold convention as CachedTokenProvider. + * @param token - The exchanged token to check + * @returns true if the token is within the refresh threshold of expiring + */ + private isNearExpiry(token: Token): boolean { + if (!token.expiresAt) { + return false; + } + return Date.now() >= token.expiresAt.getTime() - this.refreshThresholdMs; + } + + /** + * Exchanges the token and caches the result on success. Failures and + * fallback results are not cached, so a later call re-attempts. + * @param token - The subject token to exchange + * @returns The exchanged token, or the original token on failure when + * `returnOriginalTokenOnFailure` is enabled + */ + private async exchangeAndCache(token: Token): Promise { + try { + const exchanged = await this.exchangeToken(token); + this.cachedExchange = { subjectToken: token.accessToken, token: exchanged }; + return exchanged; + } catch (error) { + if (this.returnOriginalTokenOnFailure) { + // Fall back to original token; do not cache the fallback. + return token; + } + throw error; + } + } + /** * Exchanges the token for a Databricks-compatible token using RFC 8693. * Includes retry logic for transient errors with exponential backoff. @@ -207,10 +289,15 @@ export default class FederationProvider implements ITokenProvider { throw new Error('Token exchange response missing access_token'); } - // Calculate expiration from expires_in + // Calculate expiration from expires_in. When the response has no + // expires_in, fall back to the exchanged JWT's exp claim, and assume a + // default lifetime when neither is available (mirrors the Python + // driver), so the cached token is eventually refreshed. let expiresAt: Date | undefined; if (typeof data.expires_in === 'number') { expiresAt = new Date(Date.now() + data.expires_in * 1000); + } else { + expiresAt = Token.fromJWT(data.access_token).expiresAt ?? new Date(Date.now() + DEFAULT_EXCHANGED_TOKEN_TTL_MS); } return new Token(data.access_token, { diff --git a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts index abb4c694..581a64c1 100644 --- a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts +++ b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts @@ -204,6 +204,250 @@ describe('FederationProvider', () => { }); }); + describe('caching', () => { + let clock: sinon.SinonFakeTimers; + + beforeEach(() => { + clock = sinon.useFakeTimers(Date.now()); + }); + + afterEach(() => { + clock.restore(); + setFederationFetchForTest(); // restore real node-fetch + }); + + // Same fake-response helper as the 'exchange path' block above. + function buildFakeResponse(opts: { + ok: boolean; + status?: number; + statusText?: string; + body?: unknown; + text?: string; + }): nodeFetch.Response { + return { + ok: opts.ok, + status: opts.status ?? (opts.ok ? 200 : 500), + statusText: opts.statusText ?? '', + json: async () => opts.body, + text: async () => opts.text ?? '', + } as unknown as nodeFetch.Response; + } + + function stubExchangedTokens(tokens: string[], expiresIn = 3600): sinon.SinonStub { + let call = 0; + const stub = sinon.stub, ReturnType>(); + stub.callsFake(async () => { + const accessToken = tokens[Math.min(call, tokens.length - 1)]; + call += 1; + return buildFakeResponse({ + ok: true, + body: { access_token: accessToken, token_type: 'Bearer', expires_in: expiresIn }, + }); + }); + return stub; + } + + it('should reuse the exchanged token on repeated calls', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + const fetchStub = stubExchangedTokens(['exchanged-1']); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + const token1 = await federationProvider.getToken(); + const token2 = await federationProvider.getToken(); + const token3 = await federationProvider.getToken(); + + expect(fetchStub.callCount).to.equal(1); // One exchange for all calls + expect(token1.accessToken).to.equal('exchanged-1'); + expect(token2).to.equal(token1); + expect(token3).to.equal(token1); + }); + + it('should re-exchange when the subject token changes', async () => { + const foreignJwt1 = createJWT({ iss: 'https://idp.example.com', sub: 'a' }); + const foreignJwt2 = createJWT({ iss: 'https://idp.example.com', sub: 'b' }); + const baseProvider = new MockTokenProvider(foreignJwt1); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + const fetchStub = stubExchangedTokens(['exchanged-1', 'exchanged-2']); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + const token1 = await federationProvider.getToken(); + expect(token1.accessToken).to.equal('exchanged-1'); + + baseProvider.tokenToReturn = new Token(foreignJwt2); + const token2 = await federationProvider.getToken(); + + expect(fetchStub.callCount).to.equal(2); + expect(token2.accessToken).to.equal('exchanged-2'); + // The second exchange must use the new subject token. + const secondBody = fetchStub.secondCall.args[1]!.body as string; + expect(secondBody).to.contain(encodeURIComponent(foreignJwt2)); + }); + + it('should not re-exchange while the exchanged token is outside the refresh threshold', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com', { + refreshThresholdMs: 5 * 60 * 1000, + }); + const fetchStub = stubExchangedTokens(['exchanged-1']); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + await federationProvider.getToken(); + clock.tick(4 * 60 * 1000); // Still 6 minutes until expiry + await federationProvider.getToken(); + + expect(fetchStub.callCount).to.equal(1); + }); + + it('should re-exchange when the exchanged token nears expiry', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com', { + refreshThresholdMs: 5 * 60 * 1000, + }); + // 10-minute lifetime so the 5-minute threshold is reachable in the test. + const fetchStub = stubExchangedTokens(['exchanged-1', 'exchanged-2'], 10 * 60); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + const token1 = await federationProvider.getToken(); + expect(token1.accessToken).to.equal('exchanged-1'); + + clock.tick(6 * 60 * 1000); // Now within the 5-minute refresh threshold + const token2 = await federationProvider.getToken(); + + expect(fetchStub.callCount).to.equal(2); + expect(token2.accessToken).to.equal('exchanged-2'); + }); + + it('should coalesce concurrent calls into a single exchange', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + + let resolveFetch: ((response: nodeFetch.Response) => void) | undefined; + const fetchStub = sinon.stub, ReturnType>(); + fetchStub.callsFake( + () => + new Promise((resolve) => { + resolveFetch = resolve; + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + const promise1 = federationProvider.getToken(); + const promise2 = federationProvider.getToken(); + const promise3 = federationProvider.getToken(); + + // Let the microtask chain reach the fetch stub before resolving it. + for (let i = 0; i < 10 && !resolveFetch; i += 1) { + await clock.tickAsync(0); + } + + resolveFetch!( + buildFakeResponse({ + ok: true, + body: { access_token: 'exchanged-concurrent', token_type: 'Bearer', expires_in: 3600 }, + }), + ); + + const [token1, token2, token3] = await Promise.all([promise1, promise2, promise3]); + + expect(fetchStub.callCount).to.equal(1); + expect(token1.accessToken).to.equal('exchanged-concurrent'); + expect(token2.accessToken).to.equal('exchanged-concurrent'); + expect(token3.accessToken).to.equal('exchanged-concurrent'); + }); + + it('should retry the exchange after a failure instead of caching it', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + const fetchStub = sinon.stub, ReturnType>(); + fetchStub + .onFirstCall() + .resolves(buildFakeResponse({ ok: false, status: 400, statusText: 'Bad Request', text: 'invalid_grant' })); + fetchStub.onSecondCall().resolves( + buildFakeResponse({ + ok: true, + body: { access_token: 'exchanged-later', token_type: 'Bearer', expires_in: 3600 }, + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + // First call falls back to the original token; nothing is cached. + const token1 = await federationProvider.getToken(); + expect(token1.accessToken).to.equal(foreignJwt); + expect(fetchStub.callCount).to.equal(1); + + // The next call re-attempts the exchange. + const token2 = await federationProvider.getToken(); + expect(fetchStub.callCount).to.equal(2); + expect(token2.accessToken).to.equal('exchanged-later'); + }); + + it('should reject and retry on the next call when returnOriginalTokenOnFailure is false', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com', { + returnOriginalTokenOnFailure: false, + }); + const fetchStub = sinon.stub, ReturnType>(); + fetchStub + .onFirstCall() + .resolves(buildFakeResponse({ ok: false, status: 400, statusText: 'Bad Request', text: 'invalid_grant' })); + fetchStub.onSecondCall().resolves( + buildFakeResponse({ + ok: true, + body: { access_token: 'exchanged-later', token_type: 'Bearer', expires_in: 3600 }, + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + let firstError: Error | undefined; + try { + await federationProvider.getToken(); + } catch (error) { + firstError = error as Error; + } + expect(firstError, 'first call must reject').to.exist; + expect(firstError!.message).to.contain('400'); + expect(fetchStub.callCount).to.equal(1); + + // The failure must not be cached or poison later calls: the second + // call re-attempts the exchange and succeeds. + const token2 = await federationProvider.getToken(); + expect(fetchStub.callCount).to.equal(2); + expect(token2.accessToken).to.equal('exchanged-later'); + }); + + it('should assume a default TTL when the response has no expires_in', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + + // 'exchanged-no-expiry' is not a JWT, so there is no exp claim either; + // the default 1-hour TTL applies. + const fetchStub = sinon.stub, ReturnType>().resolves( + buildFakeResponse({ + ok: true, + body: { access_token: 'exchanged-no-expiry', token_type: 'Bearer' }, + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + const token = await federationProvider.getToken(); + + expect(token.expiresAt).to.exist; + expect(token.expiresAt!.getTime() - Date.now()).to.equal(60 * 60 * 1000); + + // And it is still cached until the threshold. + await federationProvider.getToken(); + expect(fetchStub.callCount).to.equal(1); + }); + }); + describe('getName', () => { it('should return wrapped name', () => { const baseProvider = new MockTokenProvider('token'); From 4aebba50cc8b7b80b328480bf4e6e421d4ad69a2 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:53:10 +0000 Subject: [PATCH 2/5] Fix in-flight race when subject token changes mid-exchange A late-settling exchange for an older subject cleared the shared in-flight reference even after a newer subject's exchange had replaced it, causing duplicate exchanges, and could evict the newer subject's cached entry. Track each exchange's own promise and only clear the shared fields when it is still the tracked exchange; write the cache only while the exchange is still tracked for its subject. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- .../auth/tokenProvider/FederationProvider.ts | 24 +++++++--- .../tokenProvider/FederationProvider.test.ts | 47 +++++++++++++++++++ 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/lib/connection/auth/tokenProvider/FederationProvider.ts b/lib/connection/auth/tokenProvider/FederationProvider.ts index 0aa168d7..c0c459c4 100644 --- a/lib/connection/auth/tokenProvider/FederationProvider.ts +++ b/lib/connection/auth/tokenProvider/FederationProvider.ts @@ -152,13 +152,20 @@ export default class FederationProvider implements ITokenProvider { return this.exchangePromise; } - this.exchangeSubjectToken = token.accessToken; - this.exchangePromise = this.exchangeAndCache(token).finally(() => { - this.exchangePromise = null; - this.exchangeSubjectToken = null; + const exchange = this.exchangeAndCache(token); + const tracked = exchange.finally(() => { + // Clear only our own reference: a newer exchange (e.g. started for a + // different subject token while this one was in flight) may already be + // tracked, and clearing its reference would cause duplicate exchanges. + if (this.exchangePromise === tracked) { + this.exchangePromise = null; + this.exchangeSubjectToken = null; + } }); + this.exchangeSubjectToken = token.accessToken; + this.exchangePromise = tracked; - return this.exchangePromise; + return tracked; } getName(): string { @@ -223,7 +230,12 @@ export default class FederationProvider implements ITokenProvider { private async exchangeAndCache(token: Token): Promise { try { const exchanged = await this.exchangeToken(token); - this.cachedExchange = { subjectToken: token.accessToken, token: exchanged }; + // Write the cache only while this exchange is still the tracked one for + // its subject: a late-settling exchange whose subject was superseded by + // a newer one must not evict the newer subject's cached entry. + if (this.exchangeSubjectToken === token.accessToken) { + this.cachedExchange = { subjectToken: token.accessToken, token: exchanged }; + } return exchanged; } catch (error) { if (this.returnOriginalTokenOnFailure) { diff --git a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts index 581a64c1..f5a45817 100644 --- a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts +++ b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts @@ -360,6 +360,53 @@ describe('FederationProvider', () => { expect(token3.accessToken).to.equal('exchanged-concurrent'); }); + it('should keep a newer subject exchange intact when an older one settles late', async () => { + const jwtA = createJWT({ iss: 'https://idp.example.com', sub: 'a' }); + const jwtB = createJWT({ iss: 'https://idp.example.com', sub: 'b' }); + const baseProvider = new MockTokenProvider(jwtA); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + + const resolvers: Array<(response: nodeFetch.Response) => void> = []; + const fetchStub = sinon.stub, ReturnType>(); + fetchStub.callsFake( + () => + new Promise((resolve) => { + resolvers.push(resolve); + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + // Start an exchange for subject A, then switch the subject to B and + // start a second exchange while A is still in flight. + const promiseA = federationProvider.getToken(); + baseProvider.tokenToReturn = new Token(jwtB); + const promiseB = federationProvider.getToken(); + + // Let the microtask chain reach the fetch stub for both exchanges. + for (let i = 0; i < 10 && resolvers.length < 2; i += 1) { + await clock.tickAsync(0); + } + expect(resolvers.length).to.equal(2); + + // A settles after B's exchange has already been started. + resolvers[0]( + buildFakeResponse({ ok: true, body: { access_token: 'exchanged-a', token_type: 'Bearer', expires_in: 3600 } }), + ); + resolvers[1]( + buildFakeResponse({ ok: true, body: { access_token: 'exchanged-b', token_type: 'Bearer', expires_in: 3600 } }), + ); + + expect((await promiseA).accessToken).to.equal('exchanged-a'); + expect((await promiseB).accessToken).to.equal('exchanged-b'); + expect(fetchStub.callCount).to.equal(2); + + // A's late settlement must neither clear B's in-flight reference nor + // evict B's cached entry: the next B call reuses the cache. + const tokenB = await federationProvider.getToken(); + expect(fetchStub.callCount).to.equal(2); + expect(tokenB.accessToken).to.equal('exchanged-b'); + }); + it('should retry the exchange after a failure instead of caching it', async () => { const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); const baseProvider = new MockTokenProvider(foreignJwt); From c47f512e7252883b1a125ad33c2d359c6584ff3f Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:54:50 +0000 Subject: [PATCH 3/5] Cover the exchanged JWT exp fallback in tests Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- .../tokenProvider/FederationProvider.test.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts index f5a45817..3ecb017f 100644 --- a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts +++ b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts @@ -493,6 +493,27 @@ describe('FederationProvider', () => { await federationProvider.getToken(); expect(fetchStub.callCount).to.equal(1); }); + + it('should fall back to the exchanged JWT exp claim when the response has no expires_in', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + + const expSeconds = Math.floor(Date.now() / 1000) + 45 * 60; + const exchangedJwt = createJWT({ iss: 'https://my-workspace.cloud.databricks.com', exp: expSeconds }); + const fetchStub = sinon.stub, ReturnType>().resolves( + buildFakeResponse({ + ok: true, + body: { access_token: exchangedJwt, token_type: 'Bearer' }, + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + const token = await federationProvider.getToken(); + + expect(token.expiresAt).to.exist; + expect(token.expiresAt!.getTime()).to.equal(expSeconds * 1000); + }); }); describe('getName', () => { From 880aa5f95da2c8bec65ca079aeb5d626c9dc1d35 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:12:35 +0000 Subject: [PATCH 4/5] Cache the fallback token after a failed exchange When returnOriginalTokenOnFailure is enabled and the exchange fails, cache the original token for the subject and re-attempt the exchange at most once per 5 minutes (or when the subject token changes or nears expiry), matching the Python driver, instead of failing on every call. A successful exchange replaces the fallback cache; errors with returnOriginalTokenOnFailure disabled still throw and are not cached. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 +- .../auth/tokenProvider/FederationProvider.ts | 62 +++++++++++- .../tokenProvider/FederationProvider.test.ts | 96 ++++++++++++++++++- 3 files changed, 150 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba242750..ff7fc208 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- With token federation enabled, the exchanged token is now cached and reused until it nears expiry or the subject token changes, instead of exchanging a new token on every request. +- With token federation enabled, the exchanged token is now cached and reused until it nears expiry or the subject token changes, instead of exchanging a new token on every request. When the exchange fails, the original token is served from a cache for up to 5 minutes and the exchange is retried at most that often. - Preserve wide negative DECIMAL values exactly with `preserveBigNumericPrecision: true`, including nested arrays and structs, on both backends. The default number conversion is unchanged. - Kernel backend: `port` is passed to the kernel as is, so a custom port works over HTTPS as on Thrift. IPv6 hosts need brackets, an invalid port or host fails with a `ParameterError`, and the published `@databricks/databricks-sql-kernel-*` native packages must be bumped to a release that includes databricks/databricks-sql-kernel#505, since older packages ignore `port`. - Release completed Thrift CloudFetch body-reader listeners so idle connections do not retain downloaded result buffers. diff --git a/lib/connection/auth/tokenProvider/FederationProvider.ts b/lib/connection/auth/tokenProvider/FederationProvider.ts index c0c459c4..b5e78202 100644 --- a/lib/connection/auth/tokenProvider/FederationProvider.ts +++ b/lib/connection/auth/tokenProvider/FederationProvider.ts @@ -40,6 +40,12 @@ const DEFAULT_SCOPE = 'sql'; */ const DEFAULT_EXCHANGED_TOKEN_TTL_MS = 60 * 60 * 1000; +/** + * How often the exchange is re-attempted after a failure (5 minutes). In + * between, the original token is served from the fallback cache. + */ +const FALLBACK_RETRY_INTERVAL_MS = 5 * 60 * 1000; + /** * Timeout for token exchange requests in milliseconds. */ @@ -80,7 +86,10 @@ class TokenExchangeError extends Error { * * The exchanged token is cached and reused while the subject token is unchanged * and the exchanged token is not near expiry, so repeated calls do not trigger - * a network exchange every time. + * a network exchange every time. When the exchange fails (and + * `returnOriginalTokenOnFailure` is enabled), the original token is cached as a + * fallback so the exchange is re-attempted at most once per + * `FALLBACK_RETRY_INTERVAL_MS`, mirroring the Python driver. */ export default class FederationProvider implements ITokenProvider { private readonly baseProvider: ITokenProvider; @@ -98,6 +107,13 @@ export default class FederationProvider implements ITokenProvider { /** The last successful exchange result, keyed by the subject token it was exchanged from. */ private cachedExchange: { subjectToken: string; token: Token } | null = null; + /** + * The fallback (original) token served after a failed exchange, keyed by the + * subject token, with the time it was cached so the exchange is re-attempted + * at most once per `FALLBACK_RETRY_INTERVAL_MS`. + */ + private cachedFallback: { subjectToken: string; token: Token; cachedAt: number } | null = null; + /** In-flight exchange, shared by concurrent callers for the same subject token. */ private exchangePromise: Promise | null = null; @@ -109,7 +125,7 @@ export default class FederationProvider implements ITokenProvider { * @param databricksHost - The Databricks workspace host URL * @param options - Optional configuration * @param options.clientId - Client ID for M2M/service principal federation - * @param options.returnOriginalTokenOnFailure - Return original token if exchange fails (default: true) + * @param options.returnOriginalTokenOnFailure - Return original token if exchange fails, cached for up to 5 minutes before the exchange is re-attempted (default: true) * @param options.refreshThresholdMs - Re-exchange tokens this many ms before expiry (default: 5 minutes) * @param options.getAgent - Agent for the exchange request, so the connection's proxy and TLS options apply */ @@ -146,6 +162,13 @@ export default class FederationProvider implements ITokenProvider { return cached; } + // After a failed exchange, serve the original token from the fallback + // cache so the exchange is re-attempted at most once per fallback TTL. + const fallback = this.getCachedFallback(token.accessToken); + if (fallback) { + return fallback; + } + // Coalesce concurrent callers so one subject token triggers a single // exchange. A rejected in-flight promise is cleared, so later calls retry. if (this.exchangePromise && this.exchangeSubjectToken === token.accessToken) { @@ -221,8 +244,31 @@ export default class FederationProvider implements ITokenProvider { } /** - * Exchanges the token and caches the result on success. Failures and - * fallback results are not cached, so a later call re-attempts. + * Returns the cached fallback (original) token if it was cached for the + * given subject token and is still within the fallback retry interval, the + * subject token itself is not near expiry, and the subject token has not + * changed. + * @param subjectToken - The current subject token's access token + * @returns The cached fallback token, or undefined if a new exchange should + * be attempted + */ + private getCachedFallback(subjectToken: string): Token | undefined { + const cached = this.cachedFallback; + if (!cached || cached.subjectToken !== subjectToken) { + return undefined; + } + if (Date.now() - cached.cachedAt >= FALLBACK_RETRY_INTERVAL_MS) { + return undefined; + } + return this.isNearExpiry(cached.token) ? undefined : cached.token; + } + + /** + * Exchanges the token and caches the result on success. When the exchange + * fails and `returnOriginalTokenOnFailure` is enabled, the original token is + * cached as a fallback so the exchange is re-attempted at most once per + * `FALLBACK_RETRY_INTERVAL_MS`. With `returnOriginalTokenOnFailure` + * disabled, failures are thrown and nothing is cached. * @param token - The subject token to exchange * @returns The exchanged token, or the original token on failure when * `returnOriginalTokenOnFailure` is enabled @@ -235,11 +281,17 @@ export default class FederationProvider implements ITokenProvider { // a newer one must not evict the newer subject's cached entry. if (this.exchangeSubjectToken === token.accessToken) { this.cachedExchange = { subjectToken: token.accessToken, token: exchanged }; + // A successful exchange replaces any fallback cache for this subject. + this.cachedFallback = null; } return exchanged; } catch (error) { if (this.returnOriginalTokenOnFailure) { - // Fall back to original token; do not cache the fallback. + // Cache the fallback so the exchange is re-attempted at most once per + // FALLBACK_RETRY_INTERVAL_MS instead of on every call. + if (this.exchangeSubjectToken === token.accessToken) { + this.cachedFallback = { subjectToken: token.accessToken, token, cachedAt: Date.now() }; + } return token; } throw error; diff --git a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts index 3ecb017f..24f76591 100644 --- a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts +++ b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts @@ -407,7 +407,27 @@ describe('FederationProvider', () => { expect(tokenB.accessToken).to.equal('exchanged-b'); }); - it('should retry the exchange after a failure instead of caching it', async () => { + it('should cache the fallback after a failed exchange and not re-attempt immediately', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + const fetchStub = sinon + .stub, ReturnType>() + .resolves(buildFakeResponse({ ok: false, status: 400, statusText: 'Bad Request', text: 'invalid_grant' })); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + // First call falls back to the original token. + const token1 = await federationProvider.getToken(); + expect(token1.accessToken).to.equal(foreignJwt); + expect(fetchStub.callCount).to.equal(1); + + // The refusal is cached: the second call makes no new exchange. + const token2 = await federationProvider.getToken(); + expect(token2.accessToken).to.equal(foreignJwt); + expect(fetchStub.callCount).to.equal(1); + }); + + it('should re-attempt the exchange after the fallback retry interval', async () => { const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); const baseProvider = new MockTokenProvider(foreignJwt); const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); @@ -423,15 +443,83 @@ describe('FederationProvider', () => { ); setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); - // First call falls back to the original token; nothing is cached. const token1 = await federationProvider.getToken(); expect(token1.accessToken).to.equal(foreignJwt); expect(fetchStub.callCount).to.equal(1); - // The next call re-attempts the exchange. + // Just before the 5-minute retry interval the fallback is still cached. + clock.tick(4 * 60 * 1000); const token2 = await federationProvider.getToken(); + expect(token2.accessToken).to.equal(foreignJwt); + expect(fetchStub.callCount).to.equal(1); + + // At the interval the exchange is re-attempted and succeeds. + clock.tick(1 * 60 * 1000); + const token3 = await federationProvider.getToken(); expect(fetchStub.callCount).to.equal(2); - expect(token2.accessToken).to.equal('exchanged-later'); + expect(token3.accessToken).to.equal('exchanged-later'); + }); + + it('should re-attempt the exchange when the subject token changes after a fallback', async () => { + const foreignJwt1 = createJWT({ iss: 'https://idp.example.com', sub: 'a' }); + const foreignJwt2 = createJWT({ iss: 'https://idp.example.com', sub: 'b' }); + const baseProvider = new MockTokenProvider(foreignJwt1); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + const fetchStub = sinon.stub, ReturnType>(); + fetchStub + .onFirstCall() + .resolves(buildFakeResponse({ ok: false, status: 400, statusText: 'Bad Request', text: 'invalid_grant' })); + fetchStub.onSecondCall().resolves( + buildFakeResponse({ + ok: true, + body: { access_token: 'exchanged-b', token_type: 'Bearer', expires_in: 3600 }, + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + const token1 = await federationProvider.getToken(); + expect(token1.accessToken).to.equal(foreignJwt1); + expect(fetchStub.callCount).to.equal(1); + + // A changed subject token bypasses the fallback cache and re-attempts. + baseProvider.tokenToReturn = new Token(foreignJwt2); + const token2 = await federationProvider.getToken(); + expect(fetchStub.callCount).to.equal(2); + expect(token2.accessToken).to.equal('exchanged-b'); + const secondBody = fetchStub.secondCall.args[1]!.body as string; + expect(secondBody).to.contain(encodeURIComponent(foreignJwt2)); + }); + + it('should prefer a successful exchange over a cached fallback', async () => { + const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); + const baseProvider = new MockTokenProvider(foreignJwt); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + const fetchStub = sinon.stub, ReturnType>(); + fetchStub + .onFirstCall() + .resolves(buildFakeResponse({ ok: false, status: 400, statusText: 'Bad Request', text: 'invalid_grant' })); + fetchStub.onSecondCall().resolves( + buildFakeResponse({ + ok: true, + body: { access_token: 'exchanged-after-failure', token_type: 'Bearer', expires_in: 3600 }, + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + const token1 = await federationProvider.getToken(); + expect(token1.accessToken).to.equal(foreignJwt); + expect(fetchStub.callCount).to.equal(1); + + // After the retry interval the exchange succeeds. + clock.tick(5 * 60 * 1000); + const token2 = await federationProvider.getToken(); + expect(fetchStub.callCount).to.equal(2); + expect(token2.accessToken).to.equal('exchanged-after-failure'); + + // The success replaced the fallback: the next call uses the exchanged cache. + const token3 = await federationProvider.getToken(); + expect(fetchStub.callCount).to.equal(2); + expect(token3.accessToken).to.equal('exchanged-after-failure'); }); it('should reject and retry on the next call when returnOriginalTokenOnFailure is false', async () => { From 7bb635a1e737304a8da9812625db26e6bc14bc1f Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:20:24 +0000 Subject: [PATCH 5/5] Make the mid-exchange subject-swap tests guard-sensitive Resolve the newer subject's exchange first so a missing cache-write guard lets the stale exchange evict its entry, and add a test that settles the older exchange first to cover the in-flight reference clear guard. Both tests fail when their guard is removed. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- .../tokenProvider/FederationProvider.test.ts | 64 +++++++++++++++++-- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts index 24f76591..1d27d2a1 100644 --- a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts +++ b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts @@ -388,25 +388,77 @@ describe('FederationProvider', () => { } expect(resolvers.length).to.equal(2); - // A settles after B's exchange has already been started. - resolvers[0]( - buildFakeResponse({ ok: true, body: { access_token: 'exchanged-a', token_type: 'Bearer', expires_in: 3600 } }), - ); + // Settle B first, then A: if the cache-write guard were missing, A's + // stale write would land last and evict B's entry, and the final B call + // would re-exchange instead of hitting the cache. resolvers[1]( buildFakeResponse({ ok: true, body: { access_token: 'exchanged-b', token_type: 'Bearer', expires_in: 3600 } }), ); + resolvers[0]( + buildFakeResponse({ ok: true, body: { access_token: 'exchanged-a', token_type: 'Bearer', expires_in: 3600 } }), + ); expect((await promiseA).accessToken).to.equal('exchanged-a'); expect((await promiseB).accessToken).to.equal('exchanged-b'); expect(fetchStub.callCount).to.equal(2); - // A's late settlement must neither clear B's in-flight reference nor - // evict B's cached entry: the next B call reuses the cache. + // A's late settlement must not have evicted B's cached entry: the next + // B call reuses the cache. const tokenB = await federationProvider.getToken(); expect(fetchStub.callCount).to.equal(2); expect(tokenB.accessToken).to.equal('exchanged-b'); }); + it('should let later callers join the in-flight exchange when an older one settles first', async () => { + const jwtA = createJWT({ iss: 'https://idp.example.com', sub: 'a' }); + const jwtB = createJWT({ iss: 'https://idp.example.com', sub: 'b' }); + const baseProvider = new MockTokenProvider(jwtA); + const federationProvider = new FederationProvider(baseProvider, 'my-workspace.cloud.databricks.com'); + + const resolvers: Array<(response: nodeFetch.Response) => void> = []; + const fetchStub = sinon.stub, ReturnType>(); + fetchStub.callsFake( + () => + new Promise((resolve) => { + resolvers.push(resolve); + }), + ); + setFederationFetchForTest(fetchStub as unknown as typeof nodeFetch); + + // Start an exchange for subject A, then switch the subject to B and + // start a second exchange while A is still in flight. + const promiseA = federationProvider.getToken(); + baseProvider.tokenToReturn = new Token(jwtB); + const promiseB = federationProvider.getToken(); + + // Let the microtask chain reach the fetch stub for both exchanges. + for (let i = 0; i < 10 && resolvers.length < 2; i += 1) { + await clock.tickAsync(0); + } + expect(resolvers.length).to.equal(2); + + // Settle A while B's exchange is still in flight, and let A's settlement + // (including its cleanup) fully run before the next call. + resolvers[0]( + buildFakeResponse({ ok: true, body: { access_token: 'exchanged-a', token_type: 'Bearer', expires_in: 3600 } }), + ); + await clock.tickAsync(0); + + // A's settlement must not clear B's in-flight reference: a later B call + // joins the existing exchange instead of starting a duplicate. + const promiseB2 = federationProvider.getToken(); + await clock.tickAsync(0); + + resolvers[1]( + buildFakeResponse({ ok: true, body: { access_token: 'exchanged-b', token_type: 'Bearer', expires_in: 3600 } }), + ); + + expect((await promiseA).accessToken).to.equal('exchanged-a'); + expect((await promiseB).accessToken).to.equal('exchanged-b'); + expect((await promiseB2).accessToken).to.equal('exchanged-b'); + expect(fetchStub.callCount).to.equal(2); + }); + it('should cache the fallback after a failed exchange and not re-attempt immediately', async () => { const foreignJwt = createJWT({ iss: 'https://idp.example.com' }); const baseProvider = new MockTokenProvider(foreignJwt);