Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion lib/connection/auth/tokenProvider/CachedTokenProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
173 changes: 162 additions & 11 deletions lib/connection/auth/tokenProvider/FederationProvider.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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;
Expand All @@ -80,15 +100,33 @@ export default class FederationProvider implements ITokenProvider {

private readonly returnOriginalTokenOnFailure: boolean;

private readonly refreshThresholdMs: number;

private readonly getAgent?: (url: string) => Promise<http.Agent | undefined>;

/** 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<Token> | 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(
Expand All @@ -97,13 +135,15 @@ export default class FederationProvider implements ITokenProvider {
options?: {
clientId?: string;
returnOriginalTokenOnFailure?: boolean;
refreshThresholdMs?: number;
getAgent?: (url: string) => Promise<http.Agent | undefined>;
},
) {
this.baseProvider = baseProvider;
this.databricksHost = databricksHost;
this.clientId = options?.clientId;
this.returnOriginalTokenOnFailure = options?.returnOriginalTokenOnFailure ?? true;
this.refreshThresholdMs = options?.refreshThresholdMs ?? DEFAULT_REFRESH_THRESHOLD_MS;
this.getAgent = options?.getAgent;
}

Expand All @@ -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 {
Expand Down Expand Up @@ -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;
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
}

/**
* 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<Token> {
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.
Expand Down Expand Up @@ -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, {
Expand Down
Loading
Loading