diff --git a/CHANGELOG.md b/CHANGELOG.md index d2a9bfc0..ff7fc208 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. 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/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..b5e78202 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,18 @@ 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; + +/** + * 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. */ @@ -70,6 +83,13 @@ 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. 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; @@ -80,15 +100,33 @@ 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; + + /** + * 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; + + private exchangeSubjectToken: string | null = null; + /** * Creates a new FederationProvider. * @param baseProvider - The underlying token provider * @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 */ constructor( @@ -97,6 +135,7 @@ export default class FederationProvider implements ITokenProvider { options?: { clientId?: string; returnOriginalTokenOnFailure?: boolean; + refreshThresholdMs?: number; getAgent?: (url: string) => Promise; }, ) { @@ -104,6 +143,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 +155,40 @@ 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; + } + + // 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) { + return this.exchangePromise; + } + + 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 tracked; } getName(): string { @@ -152,6 +216,88 @@ 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; + } + + /** + * 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 + */ + private async exchangeAndCache(token: Token): Promise { + try { + const exchanged = await this.exchangeToken(token); + // 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 }; + // A successful exchange replaces any fallback cache for this subject. + this.cachedFallback = null; + } + return exchanged; + } catch (error) { + if (this.returnOriginalTokenOnFailure) { + // 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; + } + } + /** * Exchanges the token for a Databricks-compatible token using RFC 8693. * Includes retry logic for transient errors with exponential backoff. @@ -207,10 +353,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..1d27d2a1 100644 --- a/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts +++ b/tests/unit/connection/auth/tokenProvider/FederationProvider.test.ts @@ -204,6 +204,458 @@ 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 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); + + // 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 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); + 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'); + 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); + + const token1 = await federationProvider.getToken(); + expect(token1.accessToken).to.equal(foreignJwt); + expect(fetchStub.callCount).to.equal(1); + + // 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(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 () => { + 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); + }); + + 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', () => { it('should return wrapped name', () => { const baseProvider = new MockTokenProvider('token');