Skip to content
Draft
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
34 changes: 17 additions & 17 deletions lib/DBSQLClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,7 @@ import IDBSQLLogger, { LogLevel } from './contracts/IDBSQLLogger';
import DBSQLLogger from './DBSQLLogger';
import CloseableCollection from './utils/CloseableCollection';
import IConnectionProvider from './connection/contracts/IConnectionProvider';

function prependSlash(str: string): string {
if (str.length > 0 && str.charAt(0) !== '/') {
return `/${str}`;
}
return str;
}
import prependSlash from './utils/prependSlash';

export type ThriftLibrary = Pick<typeof thrift, 'createClient'>;

Expand Down Expand Up @@ -234,20 +228,26 @@ export default class DBSQLClient extends EventEmitter implements IDBSQLClient, I
this.config.userAgentEntry = options.userAgentEntry;
}

this.authProvider = this.createAuthProvider(options, authProvider);

this.connectionProvider = this.createConnectionProvider(options);

// M0: `useSEA` is consumed via a non-exported internal-options cast so it
// doesn't ship in the public `.d.ts`. Mirrors Python's `kwargs.get("use_sea")`
// pattern (see databricks-sql-python/src/databricks/sql/session.py).
const internalOptions = options as ConnectionOptions & InternalConnectionOptions;
this.backend = internalOptions.useSEA
? new SeaBackend()
: new ThriftBackend({
context: this,
onConnectionEvent: (event, payload) => this.forwardConnectionEvent(event, payload),
});

if (internalOptions.useSEA) {
// The SEA backend authenticates inside the native binding; the
// Thrift auth/connection providers are never read on this path, so
// we don't build them (avoids validating the PAT twice and
// constructing a throwaway OAuth provider for an OAuth+useSEA call).
this.logger.log(LogLevel.info, 'Connecting via the SEA (native) backend');
this.backend = new SeaBackend(undefined, this.logger);
} else {
this.authProvider = this.createAuthProvider(options, authProvider);
this.connectionProvider = this.createConnectionProvider(options);
this.backend = new ThriftBackend({
context: this,
onConnectionEvent: (event, payload) => this.forwardConnectionEvent(event, payload),
});
}

await this.backend.connect(options);

Expand Down
85 changes: 85 additions & 0 deletions lib/sea/SeaAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// 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.

import { ConnectionOptions } from '../contracts/IDBSQLClient';
import AuthenticationError from '../errors/AuthenticationError';
import HiveDriverError from '../errors/HiveDriverError';
import prependSlash from '../utils/prependSlash';
import { SeaConnectionOptions } from './SeaNativeLoader';

/**
* Shape consumed by the napi-binding's `openSession()`. M0 sends only the
* PAT triple, so we `Pick` those fields off the binding's generated
* `ConnectionOptions` (re-exported as `SeaConnectionOptions`) rather than
* re-declaring them — if the kernel renames `hostName`/`httpPath`/`token`
* this stops compiling instead of silently drifting.
*/
export type SeaNativeConnectionOptions = Pick<SeaConnectionOptions, 'hostName' | 'httpPath' | 'token'>;

/**
* Validate that the user-supplied `ConnectionOptions` describe a PAT auth
* configuration and build the napi-binding's connection-options shape.
*
* M0 SCOPE: PAT only.
* - Accepts `authType: 'access-token'` and the undefined-authType default
* (which already means PAT throughout the existing driver — see
* `DBSQLClient.createAuthProvider`).
* - Rejects every other `authType` discriminant with a clear
* "M0 supports only PAT" message so callers know OAuth / Federation /
* custom providers land in M1.
*
* Throws:
* - `AuthenticationError` when the auth mode is PAT but `token` is missing
* or empty.
* - `HiveDriverError` when the auth mode is anything other than PAT.
*/
export function buildSeaConnectionOptions(options: ConnectionOptions): SeaNativeConnectionOptions {
const { authType } = options as { authType?: string };

if (authType !== undefined && authType !== 'access-token') {
throw new HiveDriverError(
`SEA backend (M0) supports only PAT auth (authType: 'access-token'); ` +
`got authType: '${authType}'. Other auth modes (databricks-oauth, ` +
`token-provider, external-token, static-token, custom) will land in M1.`,
);
}

// PAT path — at this point `options` is structurally the access-token branch
// of `AuthOptions`, which guarantees a `token` field at the type level. We
// still defensively re-check because the public ConnectionOptions type
// permits `authType: undefined` with no token at runtime.
const { token } = options as { token?: string };
if (typeof token !== 'string' || token.length === 0) {
throw new AuthenticationError(
'SEA backend: a non-empty PAT must be supplied via `token` when using `authType: \'access-token\'`.',
);
}
// Reject whitespace / control characters in the PAT. The kernel's
// reqwest `HeaderValue` already hard-rejects CR/LF/NUL at build time so
// this isn't a header-injection fix — it's parity with the Python
// driver (auth_bridge.py rejects `[\x00-\x20\x7f]`) and catches
// copy-paste whitespace before a confusing downstream failure.
// eslint-disable-next-line no-control-regex
if (/[\x00-\x20\x7f]/.test(token)) {
throw new AuthenticationError(
'SEA backend: the PAT supplied via `token` must not contain whitespace or control characters.',
);
}

return {
hostName: options.host,
httpPath: prependSlash(options.path),
token,
};
}
193 changes: 183 additions & 10 deletions lib/sea/SeaBackend.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,196 @@
// 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.

import IBackend from '../contracts/IBackend';
import ISessionBackend from '../contracts/ISessionBackend';
import IOperationBackend from '../contracts/IOperationBackend';
import { ConnectionOptions, OpenSessionRequest } from '../contracts/IDBSQLClient';
import {
ExecuteStatementOptions,
TypeInfoRequest,
CatalogsRequest,
SchemasRequest,
TablesRequest,
TableTypesRequest,
ColumnsRequest,
FunctionsRequest,
PrimaryKeysRequest,
CrossReferenceRequest,
} from '../contracts/IDBSQLSession';
import Status from '../dto/Status';
import InfoValue from '../dto/InfoValue';
import HiveDriverError from '../errors/HiveDriverError';
import IDBSQLLogger, { LogLevel } from '../contracts/IDBSQLLogger';
import { getSeaNative, SeaNativeBinding } from './SeaNativeLoader';
import { buildSeaConnectionOptions, SeaNativeConnectionOptions } from './SeaAuth';

const NOT_IMPLEMENTED_SESSION =
'SEA session backend: method not implemented in sea-auth (M0); lands in sea-execution/sea-operation.';

/**
* Opaque handle to the napi binding's `Connection` class. The exact
* shape lives in `native/sea/index.d.ts` (auto-generated). We type it as
* a structural minimum here so the loader's pass-through typing doesn't
* leak into every call site.
*/
interface NativeConnection {
/** Server-issued session id (kernel `Connection.sessionId` getter). */
readonly sessionId: string;
close(): Promise<void>;
}

/**
* Minimal `ISessionBackend` that wraps the napi-binding's `Connection`.
*
* For M0 (sea-auth) only `id` and `close()` are functional — they're the
* subset required to round-trip a connect-open-close cycle. Every other
* method throws a clear "not implemented in M0" `HiveDriverError`.
*
* `id` is the server-issued session id read straight off the kernel
* `Connection` (its `sessionId` getter, readable even after close()), so
* the value logged by `DBSQLSession` correlates with kernel / server logs
* rather than being a process-local synthetic counter.
*/
export class SeaSessionBackend implements ISessionBackend {
public readonly id: string;

private readonly connection: NativeConnection;

private readonly logger?: IDBSQLLogger;

constructor(connection: NativeConnection, logger?: IDBSQLLogger) {
this.connection = connection;
this.logger = logger;
this.id = connection.sessionId;
}

/* eslint-disable @typescript-eslint/no-unused-vars */
public async getInfo(_infoType: number): Promise<InfoValue> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async executeStatement(
_statement: string,
_options: ExecuteStatementOptions,
): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async getTypeInfo(_request: TypeInfoRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async getCatalogs(_request: CatalogsRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async getSchemas(_request: SchemasRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async getTables(_request: TablesRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

const NOT_IMPLEMENTED = 'SEA backend not implemented yet — wired in sea-napi-binding feature';
public async getTableTypes(_request: TableTypesRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async getColumns(_request: ColumnsRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async getFunctions(_request: FunctionsRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async getPrimaryKeys(_request: PrimaryKeysRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}

public async getCrossReference(_request: CrossReferenceRequest): Promise<IOperationBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED_SESSION);
}
/* eslint-enable @typescript-eslint/no-unused-vars */

public async close(): Promise<Status> {
this.logger?.log(LogLevel.debug, `SEA session closing with id: ${this.id}`);
await this.connection.close();
return Status.success();
}
}

/**
* M0 SeaBackend — wires PAT auth + napi `openSession` end-to-end.
*
* Connect is a no-op at this layer (the napi binding has no notion of a
* standalone "connect"; a session is opened directly). We capture the
* validated PAT options and hand them to `openSession()` on demand.
*
* Subsequent milestones (`sea-execution`, `sea-operation`) replace the
* stubbed `ISessionBackend` / `IOperationBackend` methods with real
* napi-binding calls.
*/
export default class SeaBackend implements IBackend {
// eslint-disable-next-line @typescript-eslint/no-unused-vars, class-methods-use-this
private nativeOptions?: SeaNativeConnectionOptions;

private readonly injectedNative?: SeaNativeBinding;

private cachedNative?: SeaNativeBinding;

private readonly logger?: IDBSQLLogger;

// `native` is injectable (tests pass a fake); production leaves it
// undefined and the binding is resolved lazily on first use so that
// constructing a SeaBackend never throws on a platform without the
// optional `.node` — the clearer auth/option validation in connect()
// runs first.
constructor(native?: SeaNativeBinding, logger?: IDBSQLLogger) {
this.injectedNative = native;
this.logger = logger;
}

private get native(): SeaNativeBinding {
if (!this.cachedNative) {
this.cachedNative = this.injectedNative ?? getSeaNative();
}
return this.cachedNative;
}

public async connect(options: ConnectionOptions): Promise<void> {
throw new HiveDriverError(NOT_IMPLEMENTED);
// Validate PAT auth + capture the napi-binding option shape. Any
// non-PAT mode (or a missing token) throws here, before we ever touch
// the native binding. NOTE: unlike Thrift, this performs no network
// round-trip — the session is opened lazily in openSession(), so a
// resolved connect() does not by itself prove the endpoint is
// reachable or the credential is valid.
this.nativeOptions = buildSeaConnectionOptions(options);
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars, class-methods-use-this
public async openSession(request: OpenSessionRequest): Promise<ISessionBackend> {
throw new HiveDriverError(NOT_IMPLEMENTED);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async openSession(_request: OpenSessionRequest): Promise<ISessionBackend> {
if (!this.nativeOptions) {
throw new HiveDriverError('SeaBackend: connect() must be called before openSession().');
}
const connection = (await this.native.openSession(this.nativeOptions)) as NativeConnection;
const session = new SeaSessionBackend(connection, this.logger);
this.logger?.log(LogLevel.info, `SEA session opened with id: ${session.id}`);
return session;
}

// No-op so DBSQLClient.close() can finish its state-clearing block after a
// failed useSEA: true connect. Real teardown lands with the M1 SEA impl.
// eslint-disable-next-line @typescript-eslint/no-empty-function, class-methods-use-this
public async close(): Promise<void> {}
public async close(): Promise<void> {
// Connection-level resources are owned by the session wrapper. No-op here.
this.nativeOptions = undefined;
}
}
25 changes: 25 additions & 0 deletions lib/utils/prependSlash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// 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.

/**
* Normalise an HTTP path to a leading-slash form. Empty strings are left
* untouched. Shared by the Thrift connect path (`DBSQLClient`) and the
* SEA auth adapter (`SeaAuth`) so the two can't drift.
*/
export default function prependSlash(str: string): string {
if (str.length > 0 && str.charAt(0) !== '/') {
return `/${str}`;
}
return str;
}
Loading
Loading