diff --git a/CHANGELOG.md b/CHANGELOG.md index d2a9bfc0..29d3eecc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Kernel backend: `authType: 'custom'`, `'token-provider'` and `'external-token'` now work, including `enableTokenFederation`; the deprecated second-argument provider also takes precedence over `authType`. - 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/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index feeed0a1..6348615f 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -58,21 +58,21 @@ Per-statement `useCloudFetch` overrides remain unsupported on the kernel backend | Option | Type | Thrift | Kernel | Default Value | Note | | --------------------------------------------- | ------------------------------------------------------------ | :----: | :----: | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authType` — common modes | `'access-token'` \| `'databricks-oauth'` \| `'static-token'` | ✅ | ✅ | `'access-token'` | `access-token` uses `token`; `static-token` uses `staticToken`. OAuth supports U2M and M2M, with the Kernel qualifications below. | -| `authType` — Thrift-only modes | `'custom'` \| `'token-provider'` \| `'external-token'` | ✅ | ❌ | — | Kernel rejects these auth modes. | +| `authType` — provider modes | `'custom'` \| `'token-provider'` \| `'external-token'` | ✅ | ✅ | — | Kernel calls the provider for the headers of every request, retries included. Kernel ignores a provider `User-Agent` and fails the request on a CR, LF or NUL in a header value. | | `token` | `string` | ✅ | ✅ | required for `access-token` | Thrift sends the PAT as a Bearer token (`Authorization: Bearer `); Kernel uses native PAT auth. Kernel rejects blank/reserved values client-side. | | `staticToken` | `string` | ✅ | ✅ | required for `static-token` | Thrift optionally wraps it in federation. Kernel uses native bearer-token auth with federation always enabled. | -| `provider` | `IAuthentication` | ✅ | ❌ | required for `custom` | Custom Thrift authentication provider. | -| `tokenProvider` | `ITokenProvider` | ✅ | ❌ | required for `token-provider` | Thrift wraps it with caching and optional federation. | -| `getToken` | `TokenCallback` | ✅ | ❌ | required for `external-token` | Callback used by the Thrift external-token provider. | +| `provider` | `IAuthentication` | ✅ | ✅ | required for `custom` | Custom authentication provider. Thrift calls `authenticate()` per RPC; Kernel calls it per HTTP request. | +| `tokenProvider` | `ITokenProvider` | ✅ | ✅ | required for `token-provider` | Both backends wrap it with caching and optional federation. | +| `getToken` | `TokenCallback` | ✅ | ✅ | required for `external-token` | Callback used by the external-token provider, with the same caching and optional federation. | | `oauthScopes` | `Array` | ⚠️ | ⚠️ | flow-dependent | Honored for U2M and workspace-OIDC M2M; entries are split on whitespace and blank values use the default (M2M `all-apis`, U2M `sql offline_access`). Azure Entra-direct uses its fixed resource scope. | | `oauthClientId` | `string` | ✅ | ✅ | flow- and cloud-dependent | In-house OAuth defaults to `databricks-sql-connector`. Thrift Entra-direct defaults to its Azure application id; Kernel Entra-direct M2M requires an explicit id. | | `oauthClientSecret` | `string` | ✅ | ✅ | — | Presence selects M2M; absence selects U2M on both. Kernel forwards blank values for workspace-OIDC parity, but rejects them in the Azure Entra-direct arm. | | `azureTenantId` / `useDatabricksOAuthInAzure` | `string` / `boolean` | ✅ | ⚠️ | — | Kernel ignores both for U2M. On Azure M2M, `useDatabricksOAuthInAzure: false`/omitted selects Entra-direct and `true` selects workspace OIDC; `azureTenantId` applies only to Entra-direct. | | `persistence` | `OAuthPersistence` | ✅ | ❌ | in-memory store / — | Custom OAuth persistence hook. Kernel rejects it; use `tokenCacheEnabled` for the Kernel U2M cache. | | `tokenCacheEnabled` | `boolean` | ❌ | ✅ | — / `false` | Kernel U2M only. Enables its encrypted on-disk refresh-token cache; it has no effect on M2M or other auth types. | -| `enableTokenFederation` | `boolean` | ✅ | ❌ | `false` / — | Thrift federation opt-in. Kernel ignores it because federation is always enabled for `static-token`. | -| `federationClientId` | `string` | ✅ | ⚠️ | — | Thrift uses it when federation is enabled for token-provider, external-token, or static-token auth. Kernel honors it only for `static-token`; a non-empty value selects SP-wide WIF and omission selects account-wide WIF. | -| `authProvider` second argument (deprecated) | `IAuthentication` | ✅ | ❌ | — | Deprecated second argument to `DBSQLClient.connect`. It overrides Thrift authentication; Kernel ignores it and authenticates from `ConnectionOptions`. | +| `enableTokenFederation` | `boolean` | ✅ | ⚠️ | `false` / — | Federation opt-in for `token-provider`, `external-token` and (Thrift) `static-token`. Kernel ignores it for `static-token`, where federation is always enabled. | +| `federationClientId` | `string` | ✅ | ⚠️ | — | Both backends use it when federation is enabled for token-provider, external-token, or static-token auth. For Kernel's `static-token` (always federated), a non-empty value selects SP-wide and omission account-wide WIF. | +| `authProvider` second argument (deprecated) | `IAuthentication` | ✅ | ✅ | — | Deprecated second argument to `DBSQLClient.connect`. It overrides the authentication selected by `ConnectionOptions` on both backends. | ## HTTP client, proxy, and retries @@ -242,8 +242,8 @@ session parameter surface. ## Main backend gaps -Thrift-only capabilities include custom/token-provider authentication, custom -OAuth persistence, SOCKS4 user IDs, authenticated/driver-buffer telemetry knobs, +Thrift-only capabilities include custom OAuth persistence, SOCKS4 user IDs, +authenticated/driver-buffer telemetry knobs, query timeout, Direct Results `maxRows`, per-statement CloudFetch/LZ4 hints, and volume operations. diff --git a/KERNEL_REV b/KERNEL_REV index 418c81d3..bf66d751 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -a29235cbea9532efa5572ebff010045583a19cbe +6d6c1e4eb70e3d5bebea75b76c5b19c459d9a467 diff --git a/lib/DBSQLClient.ts b/lib/DBSQLClient.ts index efc150d9..d0e152a8 100644 --- a/lib/DBSQLClient.ts +++ b/lib/DBSQLClient.ts @@ -802,7 +802,12 @@ export default class DBSQLClient extends EventEmitter implements IDBSQLClient, I // surface a misleading "backend not implemented" / partial-state error // instead of the accurate "DBSQLClient: not connected". try { - await backend.connect(options); + // The deprecated second argument takes precedence over authType on Thrift. + // Preserve that precedence for direct kernel connections and Reyden fallback. + const backendOptions = authProvider + ? { ...options, authType: 'custom' as const, provider: authProvider } + : options; + await backend.connect(backendOptions); } catch (err) { // `IBackend.close()` is documented as safe on a partially-initialized // backend; best-effort cleanup so we don't leak sockets / state. diff --git a/lib/kernel/KernelAuth.ts b/lib/kernel/KernelAuth.ts index ed990ca9..881e4177 100644 --- a/lib/kernel/KernelAuth.ts +++ b/lib/kernel/KernelAuth.ts @@ -13,6 +13,7 @@ // limitations under the License. import os from 'os'; +import { HeadersInit } from 'node-fetch'; import { ConnectionOptions } from '../contracts/IDBSQLClient'; import { ClientConfig } from '../contracts/IClientContext'; import { InternalConnectionOptions } from '../contracts/InternalConnectionOptions'; @@ -316,6 +317,12 @@ export type KernelNativeConnectionOptions = KernelSessionDefaults & azureClientSecret: string; azureTenantId?: string; } + | { + hostName: string; + httpPath: string; + // Headers come from the `headerProvider` that `KernelBackend` passes to `openSession`. + authMode: 'External'; + } ); function prependSlash(str: string): string { @@ -535,10 +542,8 @@ export function buildKernelHttpOptions(options: ConnectionOptions): KernelHttpOp // Per-connection socket read timeout (ms). The public `socketTimeout` // ConnectionOption maps onto the kernel napi `socketTimeoutMs` // (kernel `HttpConfig::request_timeout` / reqwest `Client::timeout`). - // Only forward a POSITIVE value: `socketTimeout: 0` means "disabled / wait - // indefinitely" on the Thrift path, but forwarding `0` would make reqwest - // time out immediately, so we omit it and let the kernel keep its (large) - // default — preserving the "effectively no idle timeout" semantics. + // Only forward a POSITIVE value: `socketTimeout: 0` disables the Thrift + // timeout, while the kernel uses its default timeout for zero or omission. if (typeof socketTimeout === 'number' && socketTimeout > 0) { http.socketTimeoutMs = socketTimeout; } @@ -1117,9 +1122,70 @@ export function buildKernelConnectionOptions(options: ConnectionOptions): Kernel }; } + // The kernel asks `KernelBackend`'s header provider for the headers of every + // request. That provider is the client's own `IAuthentication`, so caching and + // `enableTokenFederation` behave as on Thrift. + if (authType === 'custom' || authType === 'token-provider' || authType === 'external-token') { + return { ...base, authMode: 'External' }; + } + throw new HiveDriverError( `kernel backend: unsupported auth mode '${authType}'. ` + - "Supported modes on the kernel backend today: 'access-token' (PAT), 'static-token', and 'databricks-oauth' " + - '(M2M with oauthClientId+oauthClientSecret, or U2M with neither).', + "Supported modes on the kernel backend today: 'access-token' (PAT), 'static-token', 'databricks-oauth' " + + "(M2M with oauthClientId+oauthClientSecret, or U2M with neither), 'custom', 'token-provider' and 'external-token'.", ); } + +/** + * Convert the headers an `IAuthentication.authenticate()` returns into the napi + * `HeaderEntry` list, with the values node-fetch sends on Thrift: every + * `HeadersInit` shape is accepted, values (string arrays included) are + * stringified, and a repeated name (any case) is combined with `, ` under the + * first name seen. Unlike Thrift, which sends the literal text, `undefined` and + * `null` values are skipped. The kernel ignores the + * headers it manages itself (such as `User-Agent`) and fails the request on a + * CR, LF or NUL in a value. Values are never put in error messages. + */ +export function toKernelHeaderEntries(headers: HeadersInit): Array<{ name: string; value: string }> { + const entries: Array<{ name: string; value: string }> = []; + const byName = new Map(); + const add = (name: unknown, value: unknown) => { + if (value === undefined || value === null) { + return; + } + const text = String(value); + const key = String(name).toLowerCase(); + const existing = byName.get(key); + if (existing) { + existing.value = `${existing.value}, ${text}`; + } else { + const entry = { name: String(name), value: text }; + byName.set(key, entry); + entries.push(entry); + } + }; + + if (!headers || typeof headers !== 'object') { + return entries; + } + if (Array.isArray(headers)) { + headers.forEach((pair: unknown, index) => { + if (!Array.isArray(pair) || pair.length !== 2) { + throw new TypeError( + `Custom credentials provider returned header pair ${index} that is not a [name, value] tuple`, + ); + } + add(pair[0], pair[1]); + }); + } else if (typeof (headers as { forEach?: unknown }).forEach === 'function') { + // `Headers` (node-fetch or WHATWG): `forEach` yields each name once, values already combined. + (headers as { forEach(cb: (value: unknown, name: unknown) => void): void }).forEach((value, name) => + add(name, value), + ); + } else { + for (const [name, value] of Object.entries(headers)) { + add(name, value); + } + } + return entries; +} diff --git a/lib/kernel/KernelBackend.ts b/lib/kernel/KernelBackend.ts index 5c622ea0..9b0e3d63 100644 --- a/lib/kernel/KernelBackend.ts +++ b/lib/kernel/KernelBackend.ts @@ -18,6 +18,8 @@ import IClientContext from '../contracts/IClientContext'; import { ConnectionOptions, OpenSessionRequest } from '../contracts/IDBSQLClient'; import { InternalConnectionOptions } from '../contracts/InternalConnectionOptions'; import { LogLevel } from '../contracts/IDBSQLLogger'; +import IAuthentication from '../connection/contracts/IAuthentication'; +import AuthenticationError from '../errors/AuthenticationError'; import HiveDriverError from '../errors/HiveDriverError'; import { serializeQueryTags } from '../utils'; import { getKernelNative, KernelNativeBinding, KernelConnection } from './KernelNativeLoader'; @@ -27,6 +29,7 @@ import { buildKernelRetryOptions, buildKernelTelemetryOptions, KernelNativeConnectionOptions, + toKernelHeaderEntries, } from './KernelAuth'; import { installKernelLogBridge } from './KernelLogging'; import KernelSessionBackend from './KernelSessionBackend'; @@ -78,6 +81,9 @@ export default class KernelBackend implements IBackend { private nativeOptions?: KernelNativeConnectionOptions; + // The client's provider for `authMode: 'External'` (the same one Thrift uses). + private authProvider?: IAuthentication; + // Drops the kernel-log level-change listener on close. No-op until connect() // installs the bridge (and a no-op closure if the logger/binding can't // retarget at runtime). @@ -101,6 +107,16 @@ export default class KernelBackend implements IBackend { ...buildKernelTelemetryOptions(this.context.getConfig(), options, this.context.getLogger()), }; + if (this.nativeOptions.authMode === 'External') { + this.authProvider = this.context.getAuthProvider?.(); + if (!this.authProvider) { + throw new AuthenticationError( + `kernel backend: authType '${options.authType}' requires its provider ` + + '(`provider`, `tokenProvider` or `getToken`).', + ); + } + } + // Bridge the Rust kernel's `tracing` logs into the SAME `DBSQLLogger` the // driver logs through, so logs from all three layers (driver, napi shim, // kernel) land in one place — and one file when the logger has a file @@ -179,6 +195,13 @@ export default class KernelBackend implements IBackend { } } + // The kernel calls this for the headers of every request, retries included. + const { authProvider } = this; + const headerProvider = + sessionOptions.authMode === 'External' && authProvider + ? async () => toKernelHeaderEntries(await authProvider.authenticate()) + : undefined; + let nativeConnection: KernelConnection; try { // `KernelNativeConnectionOptions.authMode` is a string-literal union @@ -187,9 +210,10 @@ export default class KernelBackend implements IBackend { // is avoided). The literal values are byte-identical to the enum's, so // the only divergence is TS's const-enum strictness; cast to the // binding's parameter type at this single boundary. - nativeConnection = (await this.binding.openSession( - sessionOptions as unknown as Parameters[0], - )) as KernelConnection; + const nativeOpts = sessionOptions as unknown as Parameters[0]; + nativeConnection = (await (headerProvider + ? this.binding.openSession(nativeOpts, headerProvider) + : this.binding.openSession(nativeOpts))) as KernelConnection; } catch (err) { throw decodeNapiKernelError(err); } @@ -205,6 +229,7 @@ export default class KernelBackend implements IBackend { // No backend-level resources to release — each `KernelSessionBackend` // owns its own napi `Connection` lifecycle. this.nativeOptions = undefined; + this.authProvider = undefined; // Stop retargeting the (process-global) kernel log level from this backend's // logger; the kernel sink itself is process-global and is replaced by the diff --git a/lib/kernel/KernelSessionBackend.ts b/lib/kernel/KernelSessionBackend.ts index dd55dd4c..d7a9a465 100644 --- a/lib/kernel/KernelSessionBackend.ts +++ b/lib/kernel/KernelSessionBackend.ts @@ -203,8 +203,8 @@ export default class KernelSessionBackend implements ISessionBackend { // polling past it — a terminal `Statement` (result inline) for a fast // query, or a still-running `AsyncStatement` (poll/cancel handle) for a // slow one. The handle is server-owned, so a long query stays cancellable - // via `op.cancel()` and `close()` is a clean release (no client-side - // drive-to-terminal). `queryTimeout` is a no-op here (see the note + // via `op.cancel()` and `close()` releases it; a concurrent native + // call may be cancelled by close. `queryTimeout` is a no-op here (see the note // below) — it is NOT mapped to the server `wait_timeout`. // // - `runAsync: true` — ASYNC. Submit (`wait_timeout=0s`): the server @@ -231,8 +231,8 @@ export default class KernelSessionBackend implements ISessionBackend { // - a terminal `Statement` (result inline) for a fast query, or // - an `AsyncStatement` (a poll/cancel handle) for a slow one. // Either way the handle is tied to a server-owned statement, so a long - // query stays cancellable via `op.cancel()` and `close()` is a clean - // release (no client-side drive-to-terminal). Fire-and-forget DDL/DML + // query stays cancellable via `op.cancel()`; `close()` releases the handle + // and can cancel a concurrent native call. Fire-and-forget DDL/DML // commits because the server runs it inline during the POST. const execOptions = this.buildExecuteOptions(options); let direct: KernelStatement | KernelNativeAsyncStatement; diff --git a/native/kernel/index.d.ts b/native/kernel/index.d.ts index f4957491..176c6755 100644 --- a/native/kernel/index.d.ts +++ b/native/kernel/index.d.ts @@ -24,6 +24,8 @@ export declare class AsyncResultHandle { * `statementId`. */ get statementId(): string + /** True when the server marked this result as a Volume PUT, GET or REMOVE. */ + get isVolumeOperation(): boolean /** * Pull the next batch of results. Returns `null` when the * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a @@ -151,7 +153,9 @@ export declare class AsyncStatement { * * Also invalidates the handles `awaitResult()` returned: their * `fetchNextBatch()` then rejects with `InvalidStatementHandle`, - * unless a fetch was in progress when `close()` ran. + * unless a fetch was in progress when `close()` ran. If another call on + * the statement is still running, such as an `awaitResult()` and its + * Volume transfer, the statement is cancelled first. */ close(): Promise } @@ -319,7 +323,7 @@ export declare class Connection { * uses (`runAsync: true`): the SEA backend submits, returns a * pending operation handle, and polls to terminal during * fetch. Option semantics (statementConf / queryTags / - * rowLimit / positional + named params) match `executeStatement`. + * rowLimit / lz4Compression / positional + named params) match `executeStatement`. * Submit always sends `wait_timeout=0s` so the call returns * immediately; the caller drives completion via `status()` / * `awaitResult()`. Only the blocking-vs-pending return contract @@ -444,6 +448,8 @@ export declare class Statement { * kernel / server logs which key on the same id. */ get statementId(): string + /** True when the server marked this result as a Volume PUT, GET or REMOVE. */ + get isVolumeOperation(): boolean /** * Number of rows modified by the statement (UPDATE / INSERT / * DELETE / MERGE). `null` for SELECT and on warehouses that don't @@ -593,9 +599,8 @@ export interface ArrowSchema { * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). * * Mirrors the kernel [`AuthConfig`] variants this binding supports. - * `OAuthFederation` / `External` are intentionally not exposed yet — the - * kernel marks federation as not-yet-implemented and `External` is a - * Rust-trait escape hatch with no JS-callback bridge. + * `OAuthFederation` is intentionally not exposed yet — the kernel marks + * federation as not-yet-implemented. */ export declare const enum AuthMode { /** Personal access token (`token`). */ @@ -621,7 +626,12 @@ export declare const enum AuthMode { * `azureWorkspaceResourceId` is set — additionally sends the SP * management token for an RBAC-only service principal. */ - AzureSpM2m = 'AzureSpM2m' + AzureSpM2m = 'AzureSpM2m', + /** + * Caller-supplied credentials: the `headerProvider` passed to + * `openSession`, called once per authenticated request. + */ + External = 'External' } /** @@ -669,7 +679,7 @@ export interface ConnectionOptions { authMode?: AuthMode /** * Personal access token. Required (and non-empty) for - * [`AuthMode::Pat`]; ignored otherwise. + * [`AuthMode::Pat`]; rejected for [`AuthMode::External`], ignored otherwise. */ token?: string /** @@ -1068,7 +1078,8 @@ export interface ConnectionOptions { * long a single HTTP round-trip may block waiting on the server * before the request errors out. Maps onto the kernel * [`HttpConfig::request_timeout`] (the internal reqwest - * `Client::timeout`). + * `Client::timeout`), which is also the idle limit for Volume file + * transfers. `0` keeps the kernel default. * * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs * serialises `u32` as JS `number`; the largest representable value @@ -1090,6 +1101,7 @@ export interface ConnectionOptions { * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` * produces (`lib/utils/queryTags.ts`). Backslashes in keys are * doubled; backslash/colon/comma in values are backslash-escaped. + * - `lz4Compression` — override the session default for Arrow result compression * * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) @@ -1142,6 +1154,8 @@ export interface ExecuteOptions { * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. */ rowLimit?: number + /** Request LZ4 compression for Arrow results. Omit to use the session default. */ + lz4Compression?: boolean /** * Positional parameters, in 1-based wire order. Index `i` in this * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. @@ -1166,6 +1180,14 @@ export interface ExecuteOptions { * typed parameters or combine named and positional markers. */ rawParams?: Array + /** + * Volume transfer settings. With them, executing a Volume PUT, GET or + * REMOVE also runs its file transfer, and a failed transfer fails the + * execution. Omitted ⇒ a Volume statement returns its instruction row + * and moves no file. Maps to `StatementSpec.volume`. No upload bytes + * can be passed, so `PUT '__input_stream__'` fails. + */ + volume?: VolumeExecuteOptions } /** @@ -1250,10 +1272,17 @@ export interface NamedTypedValueInput { * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see * [`build_auth_config`]. * + * `headerProvider` is required for, and only allowed with, `authMode` + * `External`. It is an async function returning `HeaderEntry[]` (usually an + * `Authorization` entry plus any extra headers), called once per + * authenticated request with no caching; the kernel's token-federation + * exchange does not run for it. A rejection fails that request. Conflicting + * token, OAuth, JWT, Azure, federation or token-cache options are rejected. + * * The JS-visible name is `openSession` (napi-rs converts snake_case * to camelCase for free functions). */ -export declare function openSession(options: ConnectionOptions): Promise +export declare function openSession(options: ConnectionOptions, headerProvider?: (() => Promise>) | undefined | null): Promise /** * Programmatic HTTP/HTTPS/SOCKS proxy configuration, mirroring the kernel's @@ -1336,3 +1365,14 @@ export interface TypedValueInput { * loaded?" probe for the JS-side loader's structured diagnostics. */ export declare function version(): string + +/** Volume transfer settings for one execution. */ +export interface VolumeExecuteOptions { + /** + * Local directories a PUT may read from and a GET may write to. The + * local path, with symlinks resolved, must be inside one of them. + */ + allowedPaths: Array + /** Report success when REMOVE targets an object that does not exist. */ + removeNotFoundIsSuccess?: boolean +} diff --git a/tests/unit/kernel/auth-external.test.ts b/tests/unit/kernel/auth-external.test.ts new file mode 100644 index 00000000..cea95428 --- /dev/null +++ b/tests/unit/kernel/auth-external.test.ts @@ -0,0 +1,286 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* eslint-disable no-await-in-loop */ +import { expect } from 'chai'; +import { Headers, HeadersInit } from 'node-fetch'; +import sinon from 'sinon'; +import DBSQLClient from '../../../lib/DBSQLClient'; +import ThriftBackend from '../../../lib/thrift-backend/ThriftBackend'; +import StatusError from '../../../lib/errors/StatusError'; +import reydenCache from '../../../lib/ReydenWarehouseCache'; +import { TStatusCode } from '../../../thrift/TCLIService_types'; +import * as KernelNativeLoader from '../../../lib/kernel/KernelNativeLoader'; +import KernelBackend from '../../../lib/kernel/KernelBackend'; +import { toKernelHeaderEntries } from '../../../lib/kernel/KernelAuth'; +import { KernelNativeBinding } from '../../../lib/kernel/KernelNativeLoader'; +import IAuthentication from '../../../lib/connection/contracts/IAuthentication'; +import IClientContext from '../../../lib/contracts/IClientContext'; +import AuthenticationError from '../../../lib/errors/AuthenticationError'; +import TokenProviderAuthenticator from '../../../lib/connection/auth/tokenProvider/TokenProviderAuthenticator'; +import CachedTokenProvider from '../../../lib/connection/auth/tokenProvider/CachedTokenProvider'; +import ExternalTokenProvider from '../../../lib/connection/auth/tokenProvider/ExternalTokenProvider'; +import { makeFakeContext } from './_helpers/fakeBinding'; + +type HeaderProvider = () => Promise>; + +function makeBinding() { + const calls: Array<{ options: Record; headerProvider?: HeaderProvider; argCount: number }> = []; + const binding = { + version: () => 'fake-binding', + async openSession(...args: [Record, HeaderProvider?]) { + calls.push({ options: args[0], headerProvider: args[1], argCount: args.length }); + return { sessionId: 'sess', close: async () => {} }; + }, + } as unknown as KernelNativeBinding; + return { binding, calls }; +} + +function contextWith(authProvider?: IAuthentication): IClientContext { + return { ...makeFakeContext(), getAuthProvider: () => authProvider } as IClientContext; +} + +const connection = { host: 'example.cloud.databricks.com', path: '/sql/1.0/warehouses/abc' }; + +describe('KernelBackend — External auth (custom, token-provider, external-token)', () => { + it('passes the client provider to openSession and calls it on every request', async () => { + let calls = 0; + const provider: IAuthentication = { + authenticate: async () => { + calls += 1; + return { Authorization: `Bearer tok-${calls}`, 'X-Probe': 'p' }; + }, + }; + for (const authType of ['custom', 'token-provider', 'external-token'] as const) { + calls = 0; + const { binding, calls: opens } = makeBinding(); + const backend = new KernelBackend({ context: contextWith(provider), nativeBinding: binding }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await backend.connect({ ...connection, authType } as any); + await backend.openSession({}); + + expect(opens[0].options.authMode, authType).to.equal('External'); + expect(calls, 'not called before the kernel asks').to.equal(0); + const headerProvider = opens[0].headerProvider as HeaderProvider; + expect(await headerProvider()).to.deep.equal([ + { name: 'Authorization', value: 'Bearer tok-1' }, + { name: 'X-Probe', value: 'p' }, + ]); + expect((await headerProvider())[0].value).to.equal('Bearer tok-2'); + } + }); + + it('keeps the token-provider cache: getToken() runs once while the token is valid', async () => { + let getTokenCalls = 0; + const chain = new TokenProviderAuthenticator( + new CachedTokenProvider( + new ExternalTokenProvider(async () => { + getTokenCalls += 1; + return 'opaque-token'; + }), + ), + makeFakeContext(), + ); + const { binding, calls: opens } = makeBinding(); + const backend = new KernelBackend({ context: contextWith(chain), nativeBinding: binding }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await backend.connect({ ...connection, authType: 'external-token', getToken: async () => 'unused' } as any); + await backend.openSession({}); + + const headerProvider = opens[0].headerProvider as HeaderProvider; + for (let i = 0; i < 3; i += 1) { + expect(await headerProvider()).to.deep.equal([{ name: 'Authorization', value: 'Bearer opaque-token' }]); + } + expect(getTokenCalls).to.equal(1); + }); + + it('surfaces a provider rejection unchanged to the kernel', async () => { + const failure = new Error('provider is down'); + const { binding, calls: opens } = makeBinding(); + const backend = new KernelBackend({ + context: contextWith({ authenticate: () => Promise.reject(failure) }), + nativeBinding: binding, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await backend.connect({ ...connection, authType: 'custom', provider: {} } as any); + await backend.openSession({}); + + let thrown: unknown; + try { + await (opens[0].headerProvider as HeaderProvider)(); + } catch (error) { + thrown = error; + } + expect(thrown).to.equal(failure); + }); + + it('passes an array-valued Authorization from a custom provider to the kernel', async () => { + const { binding, calls: opens } = makeBinding(); + const provider: IAuthentication = { authenticate: async () => ({ Authorization: ['Bearer fake-token'] }) }; + const backend = new KernelBackend({ context: contextWith(provider), nativeBinding: binding }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await backend.connect({ ...connection, authType: 'custom', provider } as any); + await backend.openSession({}); + + expect(await (opens[0].headerProvider as HeaderProvider)()).to.deep.equal([ + { name: 'Authorization', value: 'Bearer fake-token' }, + ]); + }); + + it('rejects at connect when the client has no provider', async () => { + const { binding } = makeBinding(); + const backend = new KernelBackend({ context: contextWith(undefined), nativeBinding: binding }); + let thrown: unknown; + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await backend.connect({ ...connection, authType: 'custom' } as any); + } catch (error) { + thrown = error; + } + expect(thrown).to.be.instanceOf(AuthenticationError); + expect((thrown as Error).message).to.match(/authType 'custom' requires its provider/); + }); + + it('opens other auth modes without a header provider', async () => { + const { binding, calls: opens } = makeBinding(); + const provider: IAuthentication = { authenticate: async () => ({}) }; + const backend = new KernelBackend({ context: contextWith(provider), nativeBinding: binding }); + await backend.connect({ ...connection, token: 'dapi-fake' }); + await backend.openSession({}); + + expect(opens[0].options.authMode).to.equal('Pat'); + expect(opens[0].argCount).to.equal(1); + }); +}); + +describe('DBSQLClient — injected authentication provider on the kernel', () => { + for (const fallback of [false, true]) { + for (const withPat of [false, true]) { + it(`uses the injected provider with ${withPat ? 'a PAT' : 'no authType'}${ + fallback ? ' after KP001' : '' + }`, async () => { + const { binding, calls: opens } = makeBinding(); + const sandbox = sinon.createSandbox(); + const client = new DBSQLClient(); + const authenticate = sandbox.stub().resolves({ Authorization: 'Bearer injected' }); + const provider: IAuthentication = { authenticate }; + const options = { + ...connection, + ...(withPat ? { authType: 'access-token' as const, token: 'dapi-other-principal' } : {}), + telemetryEnabled: false, + useKernel: !fallback, + }; + sandbox.stub(KernelNativeLoader, 'getKernelNative').returns(binding); + if (fallback) { + // Stub Thrift I/O but exercise real fallback and kernel auth routing. + sandbox.stub(client as any, 'createConnectionProvider').returns({ + getThriftConnection: async () => ({ on: () => {} }), + }); + sandbox.stub(ThriftBackend.prototype as any, 'openSessionWithThrift').rejects( + new StatusError({ + statusCode: TStatusCode.ERROR_STATUS, + errorMessage: 'Thrift rejected', + sqlState: 'KP001', + }), + ); + } + try { + await client.connect(options as any, provider); + await client.openSession(); + expect(opens).to.have.length(1); + expect(opens[0].options.authMode).to.equal('External'); + expect(opens[0].options).not.to.have.property('token'); + expect(authenticate.called).to.be.false; + expect(await (opens[0].headerProvider as HeaderProvider)()).to.deep.equal([ + { name: 'Authorization', value: 'Bearer injected' }, + ]); + expect(authenticate.calledOnce).to.be.true; + expect(options).not.to.have.property('provider'); + } finally { + await client.close(); + sandbox.restore(); + reydenCache.clear(); + } + }); + } + } +}); + +describe('toKernelHeaderEntries', () => { + it('accepts every HeadersInit shape', () => { + const expected = [ + { name: 'authorization', value: 'Bearer t' }, + { name: 'x-probe', value: 'p' }, + ]; + const shapes = [ + { authorization: 'Bearer t', 'x-probe': 'p' }, + [ + ['authorization', 'Bearer t'], + ['x-probe', 'p'], + ], + new Headers({ authorization: 'Bearer t', 'x-probe': 'p' }), + ]; + for (const shape of shapes) { + expect(toKernelHeaderEntries(shape)).to.deep.equal(expected); + } + expect(toKernelHeaderEntries({})).to.deep.equal([]); + }); + + it('keeps array-valued headers, as node-fetch sends them on Thrift', () => { + expect(toKernelHeaderEntries({ Authorization: ['Bearer fake-token'], 'X-Multi': ['a', 'b'] })).to.deep.equal([ + { name: 'Authorization', value: 'Bearer fake-token' }, + { name: 'X-Multi', value: 'a,b' }, + ]); + }); + + it('stringifies non-string values instead of dropping them', () => { + const headers = { Authorization: 'Bearer t', 'X-Num': 5, 'X-Bool': true } as unknown as HeadersInit; + expect(toKernelHeaderEntries(headers)).to.deep.equal([ + { name: 'Authorization', value: 'Bearer t' }, + { name: 'X-Num', value: '5' }, + { name: 'X-Bool', value: 'true' }, + ]); + const pairs = [ + ['Authorization', 'Bearer t'], + ['X-Num', 7], + ] as unknown as HeadersInit; + expect(toKernelHeaderEntries(pairs)).to.deep.equal([ + { name: 'Authorization', value: 'Bearer t' }, + { name: 'X-Num', value: '7' }, + ]); + }); + + it('combines a repeated name (any case) under the first name, as node-fetch does', () => { + expect( + toKernelHeaderEntries([ + ['X-P', 'one'], + ['x-p', 'two'], + ]), + ).to.deep.equal([{ name: 'X-P', value: 'one, two' }]); + expect(toKernelHeaderEntries({ 'X-A': '1', 'x-a': '2' })).to.deep.equal([{ name: 'X-A', value: '1, 2' }]); + }); + + it('skips undefined and null values', () => { + const headers = { Authorization: 'Bearer t', 'X-Undef': undefined, 'X-Null': null } as unknown as HeadersInit; + expect(toKernelHeaderEntries(headers)).to.deep.equal([{ name: 'Authorization', value: 'Bearer t' }]); + }); + + it('rejects a malformed header pair without echoing its contents', () => { + const pairs = [['Authorization', 'Bearer secret-value', 'extra']] as unknown as HeadersInit; + expect(() => toKernelHeaderEntries(pairs)) + .to.throw(TypeError, /header pair 0/) + .with.property('message') + .that.does.not.include('secret-value'); + }); +}); diff --git a/tests/unit/kernel/auth-pat.test.ts b/tests/unit/kernel/auth-pat.test.ts index 7d8b7b25..630f3b7f 100644 --- a/tests/unit/kernel/auth-pat.test.ts +++ b/tests/unit/kernel/auth-pat.test.ts @@ -96,33 +96,27 @@ describe('KernelAuth — PAT auth options builder', () => { expect(native.authMode).to.equal('OAuthU2m'); }); - it('rejects token-provider with a clear unsupported-mode error', () => { - const opts: ConnectionOptions = { - host: 'example.cloud.databricks.com', - path: '/sql/1.0/warehouses/abc', - authType: 'token-provider', - // eslint-disable-next-line @typescript-eslint/no-explicit-any - tokenProvider: { getToken: async () => 'tok' } as any, - }; - - expect(() => buildKernelConnectionOptions(opts)).to.throw( - HiveDriverError, - /unsupported auth mode 'token-provider'/, - ); - }); - - it('rejects external-token and custom auth modes', () => { - const authTypes = ['external-token', 'custom'] as const; - for (const authType of authTypes) { + it('maps custom, token-provider and external-token to External without a token or federation id', () => { + for (const authType of ['custom', 'token-provider', 'external-token'] as const) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const opts = { host: 'h', path: '/p', authType, + enableTokenFederation: true, + federationClientId: 'fed-client', } as any; - expect(() => buildKernelConnectionOptions(opts)).to.throw(HiveDriverError, /unsupported auth mode/); + const native = buildKernelConnectionOptions(opts); + expect(native.authMode, authType).to.equal('External'); + expect(native, authType).to.not.have.any.keys('token', 'identityFederationClientId'); } }); + + it('rejects an unknown auth mode with a clear unsupported-mode error', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const opts = { host: 'h', path: '/p', authType: 'bogus' } as any; + expect(() => buildKernelConnectionOptions(opts)).to.throw(HiveDriverError, /unsupported auth mode 'bogus'/); + }); }); // Note: KernelBackend.connect/openSession round-trip + error-path coverage diff --git a/tests/unit/kernel/execution.test.ts b/tests/unit/kernel/execution.test.ts index 9aae43f5..ccea5396 100644 --- a/tests/unit/kernel/execution.test.ts +++ b/tests/unit/kernel/execution.test.ts @@ -48,6 +48,8 @@ class FakeNativeStatement implements KernelStatement { // Mirrors the kernel `Statement.statementId` getter. public readonly statementId = '01ef-fake-statement-id'; + public readonly isVolumeOperation = false; + public async fetchNextBatch() { return null; } @@ -475,9 +477,9 @@ describe('KernelBackend', () => { // path (M0 was PAT-only, but the OAuth M2M+U2M feature on kernel-auth-u2m // accepts the full set of `databricks-oauth` variants). M2M/U2M flow- // dispatch coverage lives in auth-m2m.test.ts / auth-u2m.test.ts; - // out-of-scope auth modes are now whatever neither PAT nor - // `databricks-oauth` covers (e.g. `token-provider`, `external-token`). - it('connect() rejects unsupported auth modes (non-PAT, non-OAuth)', async () => { + // Provider modes map to External (auth-external.test.ts), so only an + // unknown authType is unsupported. + it('connect() rejects unsupported auth modes', async () => { const connection = new FakeNativeConnection(); const binding = makeBinding(connection); const backend = new KernelBackend({ context: makeContext(), nativeBinding: binding }); @@ -488,7 +490,7 @@ describe('KernelBackend', () => { host: 'example.databricks.com', path: '/sql/1.0/warehouses/abc', // eslint-disable-next-line @typescript-eslint/no-explicit-any - authType: 'token-provider', + authType: 'bogus', } as any); } catch (err) { thrown = err;