-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathSeaAuth.ts
More file actions
386 lines (364 loc) · 16.2 KB
/
Copy pathSeaAuth.ts
File metadata and controls
386 lines (364 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// 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';
/**
* Default local listener port for the U2M authorization-code callback.
* Hardcoded here so the override of the kernel default (8020) to the
* thrift default (8030) is invariant for SEA callers — preserving parity
* with the existing Node driver. Not exposed on the public
* `ConnectionOptions` (thrift hides `callbackPorts` from its public
* surface too — see nodejs-thrift-expert survey §B.2).
*/
const U2M_DEFAULT_REDIRECT_PORT = 8030;
/**
* Shape consumed by the napi-binding's `openSession()` (see
* `native/sea/index.d.ts`). Mirrors `ConnectionOptions` in the binding's
* `.d.ts`; declared locally to avoid coupling the JS-side adapter to the
* auto-generated TS file.
*
* Discriminated by `authMode`:
* - `'Pat'` → `token` is the PAT.
* - `'OAuthM2m'` → `oauthClientId` + `oauthClientSecret` drive a
* kernel-side client_credentials exchange.
* - `'OAuthU2m'` → `oauthRedirectPort` overrides the kernel default;
* everything else (client_id, scopes, callback timeout,
* token_url_override) uses kernel defaults.
*
* The `authMode` string literals MUST match the napi-emitted `AuthMode`
* variant names verbatim (`'Pat'`, `'OAuthM2m'`, `'OAuthU2m'` — napi-rs's
* `#[napi(string_enum)]` without an explicit case option emits the
* Rust variant identifier as-is). We duplicate the values here instead
* of importing `AuthMode` from `native/sea/index.d.ts` because that
* file declares `AuthMode` as `export const enum`, which is
* incompatible with `isolatedModules` and a runtime-coupling hazard.
* The Rust source of truth lives at `native/sea/src/database.rs`.
*/
/**
* Session-level defaults shared across all auth-mode variants.
*
* Mirrors `ConnectionOptions.catalog` / `.schema` / `.sessionConf` on
* the napi binding (kernel `Session::builder().defaults(DefaultOpts)`
* and `.session_conf(HashMap)` — the routes that actually populate SEA
* `CreateSession.catalog` / `.schema` / `.session_confs`).
*
* Per-statement overrides do not exist on the kernel surface; both
* pyo3 and napi expose catalog / schema / sessionConf only at session
* creation. Mirror that here so the adapter doesn't promise a
* capability the binding can't honour.
*/
export interface SeaSessionDefaults {
catalog?: string;
schema?: string;
sessionConf?: Record<string, string>;
/**
* Render `INTERVAL` / `DURATION` result columns as strings
* (kernel `ResultConfig.intervals_as_string`). The kernel default is
* native Arrow `month_interval` / `duration[us]`, but the NodeJS
* Thrift driver surfaces intervals as strings — so the SEA path sets
* this `true` so its result shape is a byte-compatible drop-in for the
* Thrift backend. Omitting it falls back to the kernel's native types.
*/
intervalsAsString?: boolean;
/**
* Render complex (`ARRAY` / `MAP` / `STRUCT` / `VARIANT`) result
* columns as JSON strings (kernel `ResultConfig.complex_types_as_json`).
* Left unset on the SEA path: native Arrow nested types already decode
* identically to the Thrift backend through the shared Arrow converter,
* so forcing JSON here would *introduce* a divergence rather than
* remove one.
*/
complexTypesAsJson?: boolean;
}
/**
* TLS options shared across all auth-mode variants. Mirror the napi
* binding's `ConnectionOptions.checkServerCertificate` / `.customCaCert`
* (kernel `Session::builder().tls(TlsConfig)`).
*
* The napi shape takes `customCaCert` as a `Buffer` only; the public
* `ConnectionOptions` additionally accepts a PEM string, which
* `buildSeaConnectionOptions` normalises to a `Buffer` before crossing
* the FFI boundary.
*/
export interface SeaTlsOptions {
/**
* Verify the server cert. Omitted ⇒ napi default (secure: strict chain
* + hostname validation). Set `false` to disable (thrift-parity
* insecure). See `ConnectionOptions.checkServerCertificate`.
*/
checkServerCertificate?: boolean;
/** PEM-encoded CA bytes to add to the trust store. */
customCaCert?: Buffer;
}
export type SeaNativeConnectionOptions = SeaSessionDefaults &
SeaTlsOptions &
(
| {
hostName: string;
httpPath: string;
authMode: 'Pat';
token: string;
}
| {
hostName: string;
httpPath: string;
authMode: 'OAuthM2m';
oauthClientId: string;
oauthClientSecret: string;
}
| {
hostName: string;
httpPath: string;
authMode: 'OAuthU2m';
oauthRedirectPort: number;
}
);
function prependSlash(str: string): string {
if (str.length > 0 && str.charAt(0) !== '/') {
return `/${str}`;
}
return str;
}
/**
* Reject inputs that pass `typeof === 'string' && length > 0` but are
* structurally useless as credentials: whitespace-only strings, and the
* literal strings `'undefined'` / `'null'` (case-insensitive) that buggy
* shell exports (e.g. `export FOO="$UNSET_VAR"`) produce. Surfacing
* these here means an OAuth flow's `invalid_client` from the workspace
* is always a real credential mismatch, never a malformed-input passthrough.
*
* Exported so the integration-test env-gate can reuse the same predicate
* and stay in lockstep with production (B-3 fix).
*/
export function isBlankOrReserved(s: string): boolean {
const normalized = s.trim().toLowerCase();
return normalized.length === 0 || normalized === 'undefined' || normalized === 'null';
}
/**
* Normalise the public TLS options (`checkServerCertificate` /
* `customCaCert`) into the napi shape.
*
* - `checkServerCertificate` passes through verbatim (only when set; an
* absent value leaves the napi default, which is secure — strict chain +
* hostname validation. Set `false` to opt out for thrift parity).
* - `customCaCert` accepts a PEM string or `Buffer` on the public
* surface; we convert a string to a `Buffer` here and do a light PEM
* sanity check. The bytes are NOT parsed in JS — the kernel returns a
* meaningful error if the PEM is malformed.
*
* Throws `HiveDriverError` when `customCaCert` is supplied but empty or
* (for strings) lacks a PEM certificate header.
*/
export function buildSeaTlsOptions(options: ConnectionOptions): SeaTlsOptions {
const { checkServerCertificate, customCaCert } = options as {
checkServerCertificate?: boolean;
customCaCert?: Buffer | string;
};
const tls: SeaTlsOptions = {};
if (checkServerCertificate !== undefined) {
tls.checkServerCertificate = checkServerCertificate;
}
if (customCaCert !== undefined) {
if (typeof customCaCert === 'string') {
if (!customCaCert.includes('-----BEGIN CERTIFICATE-----')) {
throw new HiveDriverError(
'SEA backend: `customCaCert` string does not look like a PEM certificate ' +
"(missing '-----BEGIN CERTIFICATE-----'). Pass PEM text or a Buffer of PEM bytes.",
);
}
tls.customCaCert = Buffer.from(customCaCert, 'utf8');
} else if (Buffer.isBuffer(customCaCert)) {
if (customCaCert.length === 0) {
throw new HiveDriverError('SEA backend: `customCaCert` Buffer is empty.');
}
tls.customCaCert = customCaCert;
} else {
throw new HiveDriverError('SEA backend: `customCaCert` must be a PEM string or a Buffer.');
}
}
return tls;
}
/**
* Validate the user-supplied `ConnectionOptions` and build the
* napi-binding's connection-options shape.
*
* Supported auth modes:
* - PAT: `authType: 'access-token'` (or undefined, which already means
* PAT throughout the existing driver — see
* `DBSQLClient.createAuthProvider`).
* - OAuth M2M: `authType: 'databricks-oauth'` + `oauthClientId` +
* `oauthClientSecret`. Kernel handles OIDC discovery, client_credentials
* exchange, and re-auth on expiry internally.
* - OAuth U2M: `authType: 'databricks-oauth'` + NO `oauthClientId` and
* NO `oauthClientSecret`. Kernel runs the PKCE auth-code dance (opens
* a browser, listens on localhost:8030, exchanges the code, persists
* to `~/.config/databricks-sql-kernel/oauth/{sha256}.json`). The flow
* selector keys off `oauthClientId` presence: present → M2M, absent →
* U2M. (Round-4 NF3-2 fix; previously secret-keyed — that variant
* routed a typo'd-secret M2M call to the U2M arm and swallowed the
* actionable error.) Mirrors thrift's intent at `DBSQLClient.ts:143`.
*
* Out of scope on the OAuth paths (rejected with a clear error):
* - `azureTenantId` / `useDatabricksOAuthInAzure` → Microsoft Entra
* direct flow. The kernel uses workspace-OIDC discovery (which works
* against Azure workspaces too — they serve `/oidc/.well-known/...`)
* and does not implement the Entra-direct scope-rewrite path.
* - `persistence` on M2M → M2M tokens are not cached (re-issuing is
* cheap; no refresh token).
* - `persistence` on U2M → custom token store is a parity gap;
* requires kernel-side `AuthConfig::External` plumbing. The kernel's
* auto-disk-cache works for the standard flow today.
*
* Ambiguity:
* - PAT path: rejects when OAuth fields (`oauthClientId` /
* `oauthClientSecret`) are simultaneously set.
* - OAuth path: rejects when `token` is set alongside OAuth fields.
*
* Throws:
* - `AuthenticationError` for missing/blank required credentials.
* - `HiveDriverError` for unsupported auth modes / Azure-direct /
* custom persistence / ambiguous combinations.
*/
export function buildSeaConnectionOptions(options: ConnectionOptions): SeaNativeConnectionOptions {
const { authType } = options as { authType?: string };
const base = {
hostName: options.host,
httpPath: prependSlash(options.path),
// Match the NodeJS Thrift driver, which surfaces INTERVAL columns as
// strings. The kernel defaults to native Arrow interval/duration
// types; forcing the string rendering here keeps the SEA path a
// byte-compatible drop-in. Complex types are intentionally left at
// the kernel default (native Arrow) — they already decode identically
// to Thrift via the shared Arrow converter.
intervalsAsString: true,
// TLS knobs (server-cert verification toggle + custom CA). Validated
// and normalised (string PEM → Buffer) here so the napi shape only
// ever sees a Buffer.
...buildSeaTlsOptions(options),
};
const oauth = options as {
oauthClientId?: string;
oauthClientSecret?: string;
azureTenantId?: string;
useDatabricksOAuthInAzure?: boolean;
persistence?: unknown;
};
if (authType === undefined || authType === 'access-token') {
const { token } = options as { token?: string };
if (typeof token !== 'string' || isBlankOrReserved(token)) {
throw new AuthenticationError(
"SEA backend: a non-empty PAT must be supplied via `token` when using `authType: 'access-token'`.",
);
}
if (oauth.oauthClientId !== undefined || oauth.oauthClientSecret !== undefined) {
throw new HiveDriverError(
'SEA backend: cannot supply both `token` and `oauthClientId`/`oauthClientSecret` ' +
"on the same connection. Pick one: 'access-token' (PAT) uses `token`; " +
"'databricks-oauth' uses the OAuth fields.",
);
}
return { ...base, authMode: 'Pat', token };
}
if (authType === 'databricks-oauth') {
if ((options as { token?: string }).token !== undefined) {
throw new HiveDriverError(
"SEA backend: cannot supply `token` alongside `authType: 'databricks-oauth'`. " +
"Use `authType: 'access-token'` for PAT, or omit `token` to use OAuth.",
);
}
if (oauth.azureTenantId !== undefined || oauth.useDatabricksOAuthInAzure === true) {
throw new HiveDriverError(
'SEA backend: Azure-direct OAuth (azureTenantId / useDatabricksOAuthInAzure) ' +
'is not supported. The workspace-OIDC discovery path handles Azure workspaces ' +
'today without these options.',
);
}
// Flow selector mirrors thrift's `DBSQLClient.createAuthProvider`
// (`DBSQLClient.ts:143`): presence of `oauthClientId` indicates M2M
// intent, otherwise U2M. Routing decision is based on `oauthClientId`
// (the "do I have an id?" signal) rather than the secret, so a
// user who set an id but typoed/forgot the secret gets the M2M
// "secret is required" error instead of a U2M error that hides
// their actual intent. The U2M arm still defends against an id
// sneaking through: fires only when `oauthClientId` is provided as
// a blank-reserved literal (e.g., whitespace, `"null"`, `"undefined"`)
// alongside an absent/blank secret — both `idIsBlank` and
// `secretIsBlank` are true so U2M wins routing, but the caller's
// intent to use U2M with a partially-set id is ambiguous and
// rejected explicitly.
const idIsBlank =
oauth.oauthClientId === undefined ||
(typeof oauth.oauthClientId === 'string' && isBlankOrReserved(oauth.oauthClientId));
const secretIsBlank =
oauth.oauthClientSecret === undefined ||
(typeof oauth.oauthClientSecret === 'string' && isBlankOrReserved(oauth.oauthClientSecret));
if (idIsBlank && secretIsBlank) {
// U2M — neither id nor secret supplied.
if (oauth.oauthClientId !== undefined) {
// Defense-in-depth: id was set but blank/reserved literal.
// The kernel hardcodes `client_id = "databricks-cli"` for U2M;
// there's no JS-side override knob.
throw new HiveDriverError(
'SEA backend: `oauthClientId` is not supported on the OAuth U2M flow; ' +
"the kernel uses the built-in 'databricks-cli' client. " +
'Omit `oauthClientId` for U2M, or supply `oauthClientSecret` for the M2M flow.',
);
}
if (oauth.persistence !== undefined) {
throw new HiveDriverError(
'SEA backend: `persistence` (custom OAuth token store) is not yet wired through ' +
'to the kernel — requires `AuthConfig::External` plumbing. ' +
'Today the kernel auto-persists U2M tokens to ' +
'`~/.config/databricks-sql-kernel/oauth/` which works for the standard flow; ' +
"the JS-supplied hook (matching thrift's `OAuthPersistence` interface) lands " +
'when the kernel exposes it.',
);
}
return {
...base,
authMode: 'OAuthU2m',
oauthRedirectPort: U2M_DEFAULT_REDIRECT_PORT,
};
}
// M2M.
if (typeof oauth.oauthClientId !== 'string' || isBlankOrReserved(oauth.oauthClientId)) {
throw new AuthenticationError(
'SEA backend: `oauthClientId` is required (non-empty, non-whitespace) for OAuth M2M.',
);
}
if (typeof oauth.oauthClientSecret !== 'string' || isBlankOrReserved(oauth.oauthClientSecret)) {
throw new AuthenticationError(
'SEA backend: `oauthClientSecret` must be a non-empty non-whitespace string for OAuth M2M.',
);
}
if (oauth.persistence !== undefined) {
throw new HiveDriverError(
'SEA backend: `persistence` is not supported on OAuth M2M ' +
'(M2M tokens have no refresh token; the kernel re-issues on expiry).',
);
}
return {
...base,
authMode: 'OAuthM2m',
oauthClientId: oauth.oauthClientId,
oauthClientSecret: oauth.oauthClientSecret,
};
}
throw new HiveDriverError(
`SEA backend: unsupported auth mode '${authType}'. ` +
"Supported modes on the SEA backend today: 'access-token' (PAT) and 'databricks-oauth' " +
'(M2M with oauthClientId+oauthClientSecret, or U2M with neither).',
);
}