From 25ea610ec208c62f4fac2d08c0f4dec0a1763db8 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 08:24:40 +0000 Subject: [PATCH 1/7] fix: discover the Azure tenant for Thrift service-principal M2M Thrift Azure service-principal M2M without `azureTenantId` sent the client-credentials grant to the `/organizations` authority, which Entra rejects for that grant, so the connection could not authenticate. Discover the tenant from the workspace's `/aad/auth` redirect first, as the kernel backend and the Python connector do. An explicit `azureTenantId` skips discovery, and U2M is unchanged. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- CHANGELOG.md | 1 + .../DatabricksOAuth/AzureTenantDiscovery.ts | 61 +++++++++++ .../auth/DatabricksOAuth/OAuthManager.ts | 16 ++- .../AzureTenantDiscovery.test.ts | 100 ++++++++++++++++++ .../auth/DatabricksOAuth/OAuthManager.test.ts | 90 ++++++++++++++++ 5 files changed, 267 insertions(+), 1 deletion(-) create mode 100644 lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts create mode 100644 tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index cd6726b5..8b6a6c8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Thrift Azure service-principal M2M (`oauthClientSecret` on an Azure host) now discovers the workspace's Entra tenant from the `/aad/auth` redirect when `azureTenantId` is not set, as the kernel backend and the Python connector do. Previously the client-credentials grant went to the `/organizations` authority, which Entra rejects for that grant, so the connection failed unless `azureTenantId` was passed. An explicit `azureTenantId` still skips discovery; U2M is unchanged. - The Thrift token federation exchange (`enableTokenFederation`) now goes through the connection's agent, so `proxy`, `checkServerCertificate`, `customCaCert` and `clientCert`/`clientKey` apply to it. Previously it connected directly with Node's default agent, so behind a required proxy the exchange failed and the driver fell back to the original token. (#611) - Kernel backend: a failed status poll while waiting for a statement (a `runAsync: true` statement, or a default execution that outlives the server's inline wait) and a failed result fetch in `hasMoreRows()` now throw the mapped driver error, such as `HiveDriverError: HTTP 500: Internal Server Error` once retries on HTTP 5xx run out, instead of a raw `Error` whose message is the internal `__databricks_error__:{...}` envelope. As in `fetchChunk()`, a failed fetch in `hasMoreRows()` also closes the statement. (#608) - Reduce result chunking and `fetchAll()` overhead for large query results. diff --git a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts new file mode 100644 index 00000000..afcfdde4 --- /dev/null +++ b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts @@ -0,0 +1,61 @@ +import http from 'http'; +import fetch from 'node-fetch'; +import AuthenticationError from '../../../errors/AuthenticationError'; + +// Microsoft Entra login authorities (commercial, US Government, China). Matched as host suffixes, +// so a look-alike such as `login.microsoftonline.com.attacker.example` is rejected. +const MICROSOFT_LOGIN_HOST_SUFFIXES = ['.microsoftonline.com', '.microsoftonline.us', '.chinacloudapi.cn']; + +const DISCOVERY_TIMEOUT_MS = 30000; + +/** + * Returns the tenant id from the Entra login URL that a workspace's `/aad/auth` redirects to + * (`https://login.microsoftonline.com/{tenant}/oauth2/authorize?...`): its first path segment. + */ +export function tenantFromLoginUrl(location: string): string { + let url: URL; + try { + url = new URL(location); + } catch { + throw new AuthenticationError( + `Azure tenant discovery: /aad/auth redirected to an invalid URL; pass azureTenantId explicitly`, + ); + } + + const host = url.hostname.toLowerCase(); + if (!MICROSOFT_LOGIN_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) { + throw new AuthenticationError( + `Azure tenant discovery: /aad/auth did not redirect to a Microsoft login host (got ${host}); pass azureTenantId explicitly`, + ); + } + + const tenant = url.pathname.split('/')[1]; + if (!tenant) { + throw new AuthenticationError( + 'Azure tenant discovery: could not read a tenant id from the /aad/auth redirect; pass azureTenantId explicitly', + ); + } + return tenant; +} + +/** + * Discovers the workspace's Entra tenant from the first redirect of `{host}/aad/auth`, as the + * Python connector and the SQL kernel do. + */ +export async function discoverAzureTenantId(host: string, agent?: http.Agent): Promise { + const base = (host.includes('://') ? host : `https://${host}`).replace(/\/+$/, ''); + const response = await fetch(`${base}/aad/auth`, { + method: 'GET', + redirect: 'manual', + agent, + timeout: DISCOVERY_TIMEOUT_MS, + }); + + const location = response.headers.get('location'); + if (response.status < 300 || response.status >= 400 || !location) { + throw new AuthenticationError( + `Azure tenant discovery: ${base}/aad/auth returned HTTP ${response.status} without a redirect; pass azureTenantId explicitly`, + ); + } + return tenantFromLoginUrl(location); +} diff --git a/lib/connection/auth/DatabricksOAuth/OAuthManager.ts b/lib/connection/auth/DatabricksOAuth/OAuthManager.ts index 40ff80ae..58d15601 100644 --- a/lib/connection/auth/DatabricksOAuth/OAuthManager.ts +++ b/lib/connection/auth/DatabricksOAuth/OAuthManager.ts @@ -6,6 +6,7 @@ import OAuthToken from './OAuthToken'; import AuthorizationCode from './AuthorizationCode'; import { OAuthScope, OAuthScopes, defaultOAuthScopes, scopeDelimiter } from './OAuthScope'; import IClientContext from '../../../contracts/IClientContext'; +import { discoverAzureTenantId } from './AzureTenantDiscovery'; export enum OAuthFlow { U2M = 'U2M', @@ -289,10 +290,23 @@ export class AzureOAuthManager extends OAuthManager { public static datatricksAzureApp = '2ff814a6-3304-4ab8-85cb-cd0e6f879c1d'; + private discoveredTenantId?: string; + + protected async getClient(): Promise { + // Entra rejects the client-credentials grant on the multi-tenant `/organizations` authority, + // so M2M without an explicit tenant discovers the workspace's tenant first. + if (this.options.flow === OAuthFlow.M2M && !this.options.azureTenantId?.trim() && !this.discoveredTenantId) { + const connectionProvider = await this.context.getConnectionProvider(); + const agent = await connectionProvider.getAgent('https:'); + this.discoveredTenantId = await discoverAzureTenantId(this.options.host, agent); + } + return super.getClient(); + } + protected getOIDCConfigUrl(): string { // Use logical OR so empty / whitespace-only azureTenantId also falls back to /organizations/ // (`??` only substitutes for null/undefined, leaving `''` to produce a malformed `//v2.0/...` URL). - const tenantPath = this.options.azureTenantId?.trim() || 'organizations'; + const tenantPath = this.options.azureTenantId?.trim() || this.discoveredTenantId || 'organizations'; return `https://login.microsoftonline.com/${tenantPath}/v2.0/.well-known/openid-configuration`; } diff --git a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts new file mode 100644 index 00000000..33b3e7eb --- /dev/null +++ b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts @@ -0,0 +1,100 @@ +import { expect, AssertionError } from 'chai'; +import http from 'http'; +import { AddressInfo } from 'net'; +import { + discoverAzureTenantId, + tenantFromLoginUrl, +} from '../../../../../lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery'; +import AuthenticationError from '../../../../../lib/errors/AuthenticationError'; + +async function expectAuthError(promise: Promise, contains: string): Promise { + try { + await promise; + expect.fail('It should throw an error'); + } catch (error) { + if (error instanceof AssertionError) throw error; + expect(error).to.be.instanceOf(AuthenticationError); + expect((error as Error).message).to.contain(contains); + } +} + +describe('tenantFromLoginUrl', () => { + it('reads the tenant from the first path segment of the Entra login URL', () => { + expect(tenantFromLoginUrl('https://login.microsoftonline.com/tenant-123/oauth2/authorize?client_id=x')).to.equal( + 'tenant-123', + ); + }); + + it('accepts the sovereign Microsoft login hosts', () => { + for (const host of ['login.microsoftonline.us', 'login.chinacloudapi.cn']) { + expect(tenantFromLoginUrl(`https://${host}/tenant-abc/oauth2/authorize`)).to.equal('tenant-abc'); + } + }); + + it('rejects a redirect to a non-Microsoft or look-alike host', () => { + for (const location of [ + 'https://evil.example.com/tenant-abc/oauth2/authorize', + 'https://login.microsoftonline.com.attacker.example/tenant-abc/oauth2/authorize', + ]) { + expect(() => tenantFromLoginUrl(location)).to.throw(AuthenticationError, 'Microsoft login host'); + } + }); + + it('rejects a URL without a tenant segment or an invalid URL', () => { + expect(() => tenantFromLoginUrl('https://login.microsoftonline.com/')).to.throw(AuthenticationError, 'tenant id'); + expect(() => tenantFromLoginUrl('not a url')).to.throw(AuthenticationError, 'invalid URL'); + }); +}); + +describe('discoverAzureTenantId', () => { + let server: http.Server; + let base: string; + let respond: (req: http.IncomingMessage, res: http.ServerResponse) => void; + const paths: Array = []; + + before(async () => { + server = http.createServer((req, res) => { + paths.push(req.url); + respond(req, res); + }); + await new Promise((resolve) => { + server.listen(0, '127.0.0.1', resolve); + }); + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + + after(async () => { + await new Promise((resolve) => { + server.close(() => resolve()); + }); + }); + + beforeEach(() => { + paths.length = 0; + }); + + it('reads the tenant from the first /aad/auth redirect without following it', async () => { + respond = (req, res) => { + res.writeHead(302, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize?client_id=x' }); + res.end(); + }; + expect(await discoverAzureTenantId(`${base}/`)).to.equal('tenant-xyz'); + expect(paths).to.deep.equal(['/aad/auth']); + }); + + it('fails when /aad/auth does not redirect', async () => { + respond = (req, res) => { + res.writeHead(200); + res.end(); + }; + await expectAuthError(discoverAzureTenantId(base), 'HTTP 200 without a redirect'); + }); + + it('fails when the redirect is not to a Microsoft login host', async () => { + respond = (req, res) => { + res.writeHead(302, { Location: 'https://idp.example.com/tenant-xyz/authorize' }); + res.end(); + }; + await expectAuthError(discoverAzureTenantId(base), 'Microsoft login host'); + }); +}); diff --git a/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts b/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts index 179f6e28..a72f9f82 100644 --- a/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts +++ b/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts @@ -5,6 +5,8 @@ import { Issuer, BaseClient, TokenSet, GrantBody, IssuerMetadata, ClientMetadata import openidClientLib from 'openid-client'; // Import the whole module to stub its default export import * as AuthorizationCodeModule from '../../../../../lib/connection/auth/DatabricksOAuth/AuthorizationCode'; +import * as AzureTenantDiscoveryModule from '../../../../../lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery'; +import AuthenticationError from '../../../../../lib/errors/AuthenticationError'; import { AzureOAuthManager, @@ -155,9 +157,12 @@ class OpenIDClientStub implements BaseClient { afterEach(() => { (openidClientLib.Issuer as unknown as SinonStub).restore?.(); (AuthorizationCodeModule.default as unknown as SinonStub).restore?.(); + (AzureTenantDiscoveryModule.discoverAzureTenantId as unknown as SinonStub).restore?.(); }); function prepareTestInstances(options: Partial) { + // Azure M2M without a tenant discovers it over HTTP; keep these tests offline. + sinon.stub(AzureTenantDiscoveryModule, 'discoverAzureTenantId').resolves('test-tenant'); const oauthClient = sinon.spy(new OpenIDClientStub()); oauthClient.expectedClientId = options?.clientId; @@ -594,6 +599,91 @@ describe('AzureOAuthManager (tenant awareness)', () => { }); }); +describe('AzureOAuthManager tenant discovery', () => { + let discoverStub: SinonStub; + let oidcConfigUrls: string[]; + + beforeEach(() => { + oidcConfigUrls = []; + const oauthClient = new OpenIDClientStub(); + const issuer: Issuer = { + Client: class extends OpenIDClientStub { + constructor(clientOptions: ClientMetadata) { + super(); + oauthClient.clientOptions = clientOptions; + return oauthClient; + } + }, + FAPI1Client: OpenIDClientStub, + metadata: { issuer: 'test' }, + [custom.http_options]: () => ({}), + discover: async () => issuer, + }; + sinon.stub(openidClientLib, 'Issuer').returns(issuer); + openidClientLib.Issuer.discover = async (url: string) => { + oidcConfigUrls.push(url); + return issuer; + }; + discoverStub = sinon.stub(AzureTenantDiscoveryModule, 'discoverAzureTenantId').resolves('discovered-tenant'); + }); + + afterEach(() => { + (openidClientLib.Issuer as unknown as SinonStub).restore?.(); + discoverStub.restore(); + }); + + function makeManager(overrides: Partial = {}) { + return new AzureOAuthManager({ + host: 'adb-1234567890123456.1.azuredatabricks.net', + flow: OAuthFlow.M2M, + clientId: 'test_client_id', + clientSecret: 'test_client_secret', + context: new ClientContextStub(), + ...overrides, + }); + } + + it('discovers the tenant once for M2M without azureTenantId and uses it for the token request', async () => { + const mgr = makeManager(); + await mgr.getToken(); + await mgr.getToken(); + expect(discoverStub.calledOnce).to.be.true; + expect(discoverStub.firstCall.args[0]).to.equal('adb-1234567890123456.1.azuredatabricks.net'); + expect(oidcConfigUrls).to.deep.equal([ + 'https://login.microsoftonline.com/discovered-tenant/v2.0/.well-known/openid-configuration', + ]); + }); + + it('uses an explicit azureTenantId without discovery', async () => { + await makeManager({ azureTenantId: 'explicit-tenant' }).getToken(); + expect(discoverStub.called).to.be.false; + expect(oidcConfigUrls).to.deep.equal([ + 'https://login.microsoftonline.com/explicit-tenant/v2.0/.well-known/openid-configuration', + ]); + }); + + it('keeps /organizations for U2M', async () => { + const mgr = makeManager({ flow: OAuthFlow.U2M, clientSecret: undefined }); + await (mgr as unknown as { getClient(): Promise }).getClient(); + expect(discoverStub.called).to.be.false; + expect(oidcConfigUrls).to.deep.equal([ + 'https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration', + ]); + }); + + it('surfaces a discovery failure instead of falling back to /organizations', async () => { + discoverStub.rejects(new AuthenticationError('Azure tenant discovery: no redirect')); + try { + await makeManager().getToken(); + expect.fail('It should throw an error'); + } catch (error) { + if (error instanceof AssertionError) throw error; + expect((error as Error).message).to.contain('Azure tenant discovery'); + } + expect(oidcConfigUrls).to.deep.equal([]); + }); +}); + describe('DatabricksOAuthManager.getScopes (AUTH-017)', () => { function makeManager(flow: OAuthFlow) { return new DatabricksOAuthManager({ host: 'example.cloud.databricks.com', flow, context: new ClientContextStub() }); From 2d50b8efc98a47d38d2e2b47b9fe24683b25c205 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 09:01:53 +0000 Subject: [PATCH 2/7] fix: keep the azureTenantId hint when tenant discovery cannot connect A network failure during `/aad/auth` discovery (DNS, proxy or TLS error, timeout) escaped as a raw node-fetch error without the hint that setting `azureTenantId` avoids the request. Wrap it in an AuthenticationError that names only the error code or type. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- .../DatabricksOAuth/AzureTenantDiscovery.ts | 23 ++++++++++++++----- .../AzureTenantDiscovery.test.ts | 15 ++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts index afcfdde4..ddc235c4 100644 --- a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts +++ b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts @@ -44,12 +44,23 @@ export function tenantFromLoginUrl(location: string): string { */ export async function discoverAzureTenantId(host: string, agent?: http.Agent): Promise { const base = (host.includes('://') ? host : `https://${host}`).replace(/\/+$/, ''); - const response = await fetch(`${base}/aad/auth`, { - method: 'GET', - redirect: 'manual', - agent, - timeout: DISCOVERY_TIMEOUT_MS, - }); + let response; + try { + response = await fetch(`${base}/aad/auth`, { + method: 'GET', + redirect: 'manual', + agent, + timeout: DISCOVERY_TIMEOUT_MS, + }); + } catch (error) { + // Report only the code/type: a network error's message can carry request details. + const { code, type } = error as { code?: string; type?: string }; + throw new AuthenticationError( + `Azure tenant discovery: ${base}/aad/auth failed (${ + code ?? type ?? 'network error' + }); pass azureTenantId explicitly`, + ); + } const location = response.headers.get('location'); if (response.status < 300 || response.status >= 400 || !location) { diff --git a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts index 33b3e7eb..648a52f5 100644 --- a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts +++ b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts @@ -90,6 +90,21 @@ describe('discoverAzureTenantId', () => { await expectAuthError(discoverAzureTenantId(base), 'HTTP 200 without a redirect'); }); + it('wraps a network failure with the azureTenantId hint', async () => { + const closed = http.createServer(); + await new Promise((resolve) => { + closed.listen(0, '127.0.0.1', resolve); + }); + const { port } = closed.address() as AddressInfo; + await new Promise((resolve) => { + closed.close(() => resolve()); + }); + await expectAuthError( + discoverAzureTenantId(`http://127.0.0.1:${port}`), + 'failed (ECONNREFUSED); pass azureTenantId', + ); + }); + it('fails when the redirect is not to a Microsoft login host', async () => { respond = (req, res) => { res.writeHead(302, { Location: 'https://idp.example.com/tenant-xyz/authorize' }); From 0190605668deeb27d341bbe3341a545dafa6a05c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 09:33:11 +0000 Subject: [PATCH 3/7] fix: drain the /aad/auth redirect body during tenant discovery The redirect response body was never read, so on the connection's keep-alive agent a large body could hold the socket. Drain it before reading the Location header. Also assert that discovery uses the connection's https agent (proxy and TLS options), and rename the pre-discovery tests. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- .../DatabricksOAuth/AzureTenantDiscovery.ts | 2 ++ .../AzureTenantDiscovery.test.ts | 22 +++++++++++++++++++ .../auth/DatabricksOAuth/OAuthManager.test.ts | 15 ++++++++++--- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts index ddc235c4..33977aa7 100644 --- a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts +++ b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts @@ -62,6 +62,8 @@ export async function discoverAzureTenantId(host: string, agent?: http.Agent): P ); } + // Drain the (small) body so the keep-alive agent can reuse the socket. + await response.text().catch(() => undefined); const location = response.headers.get('location'); if (response.status < 300 || response.status >= 400 || !location) { throw new AuthenticationError( diff --git a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts index 648a52f5..0c55e015 100644 --- a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts +++ b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts @@ -82,6 +82,28 @@ describe('discoverAzureTenantId', () => { expect(paths).to.deep.equal(['/aad/auth']); }); + it('drains the redirect body so a keep-alive agent reuses the socket', async () => { + respond = (req, res) => { + res.writeHead(302, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize' }); + // Larger than the stream buffers, so an undrained body would hold the only socket. + res.end('x'.repeat(1024 * 1024)); + }; + let connections = 0; + const onConnection = () => { + connections += 1; + }; + server.on('connection', onConnection); + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); + try { + expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); + expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); + expect(connections).to.equal(1); + } finally { + server.off('connection', onConnection); + agent.destroy(); + } + }); + it('fails when /aad/auth does not redirect', async () => { respond = (req, res) => { res.writeHead(200); diff --git a/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts b/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts index a72f9f82..0d0edbcc 100644 --- a/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts +++ b/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts @@ -1,4 +1,5 @@ import { AssertionError, expect } from 'chai'; +import https from 'https'; import sinon, { SinonStub } from 'sinon'; import { Issuer, BaseClient, TokenSet, GrantBody, IssuerMetadata, ClientMetadata, custom } from 'openid-client'; // Import the whole module once more - to stub some of its exports @@ -540,7 +541,7 @@ describe('AzureOAuthManager (tenant awareness)', () => { (mgr as unknown as Record T>)[name](...args); describe('getOIDCConfigUrl', () => { - it('falls back to /organizations/ when azureTenantId is not set (baseline-compatible)', () => { + it('uses /organizations/ when azureTenantId is not set and no tenant was discovered yet', () => { const mgr = makeAzure(); const url = call(mgr, 'getOIDCConfigUrl'); expect(url).to.equal('https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration'); @@ -553,7 +554,7 @@ describe('AzureOAuthManager (tenant awareness)', () => { expect(url).to.equal(`https://login.microsoftonline.com/${tenant}/v2.0/.well-known/openid-configuration`); }); - it('falls back to /organizations/ when azureTenantId is empty or whitespace', () => { + it('uses /organizations/ before discovery when azureTenantId is empty or whitespace', () => { for (const tenant of ['', ' ']) { const mgr = makeAzure({ azureTenantId: tenant }); const url = call(mgr, 'getOIDCConfigUrl'); @@ -632,13 +633,19 @@ describe('AzureOAuthManager tenant discovery', () => { discoverStub.restore(); }); + const httpsAgent = new https.Agent(); + function makeManager(overrides: Partial = {}) { + const context = new ClientContextStub(); + sinon + .stub(context.connectionProvider, 'getAgent') + .callsFake(async (url?: string | URL) => (url === 'https:' ? httpsAgent : undefined)); return new AzureOAuthManager({ host: 'adb-1234567890123456.1.azuredatabricks.net', flow: OAuthFlow.M2M, clientId: 'test_client_id', clientSecret: 'test_client_secret', - context: new ClientContextStub(), + context, ...overrides, }); } @@ -649,6 +656,8 @@ describe('AzureOAuthManager tenant discovery', () => { await mgr.getToken(); expect(discoverStub.calledOnce).to.be.true; expect(discoverStub.firstCall.args[0]).to.equal('adb-1234567890123456.1.azuredatabricks.net'); + // The connection's https agent carries the proxy and TLS options. + expect(discoverStub.firstCall.args[1]).to.equal(httpsAgent); expect(oidcConfigUrls).to.deep.equal([ 'https://login.microsoftonline.com/discovered-tenant/v2.0/.well-known/openid-configuration', ]); From 8dcfba5240307307f1ea21d2923913d21cd2856c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 07:09:42 +0000 Subject: [PATCH 4/7] docs: cite #606 in the changelog and update the tenant fallback comment getOIDCConfigUrl now falls back to the discovered tenant (M2M) before /organizations; say so in its comment. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- CHANGELOG.md | 2 +- lib/connection/auth/DatabricksOAuth/OAuthManager.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b6a6c8f..b8c67e51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- Thrift Azure service-principal M2M (`oauthClientSecret` on an Azure host) now discovers the workspace's Entra tenant from the `/aad/auth` redirect when `azureTenantId` is not set, as the kernel backend and the Python connector do. Previously the client-credentials grant went to the `/organizations` authority, which Entra rejects for that grant, so the connection failed unless `azureTenantId` was passed. An explicit `azureTenantId` still skips discovery; U2M is unchanged. +- Thrift Azure service-principal M2M (`oauthClientSecret` on an Azure host) now discovers the workspace's Entra tenant from the `/aad/auth` redirect when `azureTenantId` is not set, as the kernel backend and the Python connector do. Previously the client-credentials grant went to the `/organizations` authority, which Entra rejects for that grant, so the connection failed unless `azureTenantId` was passed. An explicit `azureTenantId` still skips discovery; U2M is unchanged. (#606) - The Thrift token federation exchange (`enableTokenFederation`) now goes through the connection's agent, so `proxy`, `checkServerCertificate`, `customCaCert` and `clientCert`/`clientKey` apply to it. Previously it connected directly with Node's default agent, so behind a required proxy the exchange failed and the driver fell back to the original token. (#611) - Kernel backend: a failed status poll while waiting for a statement (a `runAsync: true` statement, or a default execution that outlives the server's inline wait) and a failed result fetch in `hasMoreRows()` now throw the mapped driver error, such as `HiveDriverError: HTTP 500: Internal Server Error` once retries on HTTP 5xx run out, instead of a raw `Error` whose message is the internal `__databricks_error__:{...}` envelope. As in `fetchChunk()`, a failed fetch in `hasMoreRows()` also closes the statement. (#608) - Reduce result chunking and `fetchAll()` overhead for large query results. diff --git a/lib/connection/auth/DatabricksOAuth/OAuthManager.ts b/lib/connection/auth/DatabricksOAuth/OAuthManager.ts index 58d15601..09c24c7a 100644 --- a/lib/connection/auth/DatabricksOAuth/OAuthManager.ts +++ b/lib/connection/auth/DatabricksOAuth/OAuthManager.ts @@ -304,8 +304,8 @@ export class AzureOAuthManager extends OAuthManager { } protected getOIDCConfigUrl(): string { - // Use logical OR so empty / whitespace-only azureTenantId also falls back to /organizations/ - // (`??` only substitutes for null/undefined, leaving `''` to produce a malformed `//v2.0/...` URL). + // Use logical OR so an empty / whitespace-only azureTenantId also falls back to the discovered tenant + // (M2M), then /organizations/ (`??` would keep `''` and produce a malformed `//v2.0/...` URL). const tenantPath = this.options.azureTenantId?.trim() || this.discoveredTenantId || 'organizations'; return `https://login.microsoftonline.com/${tenantPath}/v2.0/.well-known/openid-configuration`; } From dd96d96cc0668946fafb0a391545726bb1abe7b2 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 07:47:03 +0000 Subject: [PATCH 5/7] test: pin discovery for a blank azureTenantId and the 3xx status check A blank or whitespace azureTenantId on M2M must still discover the tenant, and a non-redirect response with a Location header must be rejected. Both mutants (dropping .trim() in the guard, dropping the status check) passed the suite before. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- .../DatabricksOAuth/AzureTenantDiscovery.test.ts | 8 ++++++++ .../auth/DatabricksOAuth/OAuthManager.test.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts index 0c55e015..6130e3dc 100644 --- a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts +++ b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts @@ -112,6 +112,14 @@ describe('discoverAzureTenantId', () => { await expectAuthError(discoverAzureTenantId(base), 'HTTP 200 without a redirect'); }); + it('fails when a non-redirect response carries a Location header', async () => { + respond = (req, res) => { + res.writeHead(200, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize' }); + res.end(); + }; + await expectAuthError(discoverAzureTenantId(base), 'HTTP 200 without a redirect'); + }); + it('wraps a network failure with the azureTenantId hint', async () => { const closed = http.createServer(); await new Promise((resolve) => { diff --git a/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts b/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts index 0d0edbcc..1d2121f9 100644 --- a/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts +++ b/tests/unit/connection/auth/DatabricksOAuth/OAuthManager.test.ts @@ -671,6 +671,18 @@ describe('AzureOAuthManager tenant discovery', () => { ]); }); + it('discovers the tenant when azureTenantId is empty or whitespace', async () => { + for (const azureTenantId of ['', ' ']) { + discoverStub.resetHistory(); + oidcConfigUrls.length = 0; + await makeManager({ azureTenantId }).getToken(); + expect(discoverStub.calledOnce).to.be.true; + expect(oidcConfigUrls).to.deep.equal([ + 'https://login.microsoftonline.com/discovered-tenant/v2.0/.well-known/openid-configuration', + ]); + } + }); + it('keeps /organizations for U2M', async () => { const mgr = makeManager({ flow: OAuthFlow.U2M, clientSecret: undefined }); await (mgr as unknown as { getClient(): Promise }).getClient(); From 420504f826f529354f1167ac2fe81300919c6446 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 16 Nov 2026 01:19:19 +0000 Subject: [PATCH 6/7] fix: abort tenant discovery when the redirect body stalls or fails node-fetch's timeout option rejects a stalled body read without closing the request, so a redirect whose body never finished made discovery wait the full 30 s and kept the socket open afterwards. Use an AbortController instead: 30 s until the headers arrive, then 1 s to drain the body (the tenant is already known from the headers). A drain that fails or runs out aborts the request, which destroys the socket; discovery still returns the tenant. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- .../DatabricksOAuth/AzureTenantDiscovery.ts | 70 +++++++++------ .../AzureTenantDiscovery.test.ts | 90 +++++++++++++++++++ 2 files changed, 134 insertions(+), 26 deletions(-) diff --git a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts index 33977aa7..128c96e2 100644 --- a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts +++ b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts @@ -1,13 +1,17 @@ import http from 'http'; -import fetch from 'node-fetch'; +import fetch, { RequestInit, Response } from 'node-fetch'; import AuthenticationError from '../../../errors/AuthenticationError'; // Microsoft Entra login authorities (commercial, US Government, China). Matched as host suffixes, // so a look-alike such as `login.microsoftonline.com.attacker.example` is rejected. const MICROSOFT_LOGIN_HOST_SUFFIXES = ['.microsoftonline.com', '.microsoftonline.us', '.chinacloudapi.cn']; +// Until the response headers arrive. const DISCOVERY_TIMEOUT_MS = 30000; +// For the redirect body after the headers (the tenant is already known by then). +const BODY_DRAIN_TIMEOUT_MS = 1000; + /** * Returns the tenant id from the Entra login URL that a workspace's `/aad/auth` redirects to * (`https://login.microsoftonline.com/{tenant}/oauth2/authorize?...`): its first path segment. @@ -42,33 +46,47 @@ export function tenantFromLoginUrl(location: string): string { * Discovers the workspace's Entra tenant from the first redirect of `{host}/aad/auth`, as the * Python connector and the SQL kernel do. */ -export async function discoverAzureTenantId(host: string, agent?: http.Agent): Promise { +export async function discoverAzureTenantId( + host: string, + agent?: http.Agent, + timeoutsMs = { headers: DISCOVERY_TIMEOUT_MS, bodyDrain: BODY_DRAIN_TIMEOUT_MS }, +): Promise { const base = (host.includes('://') ? host : `https://${host}`).replace(/\/+$/, ''); - let response; + // node-fetch's `timeout` rejects a stalled body without closing the request; aborting destroys the socket. + const controller = new AbortController(); + let timer = setTimeout(() => controller.abort(), timeoutsMs.headers); try { - response = await fetch(`${base}/aad/auth`, { - method: 'GET', - redirect: 'manual', - agent, - timeout: DISCOVERY_TIMEOUT_MS, - }); - } catch (error) { - // Report only the code/type: a network error's message can carry request details. - const { code, type } = error as { code?: string; type?: string }; - throw new AuthenticationError( - `Azure tenant discovery: ${base}/aad/auth failed (${ - code ?? type ?? 'network error' - }); pass azureTenantId explicitly`, - ); - } + let response: Response; + try { + response = await fetch(`${base}/aad/auth`, { + method: 'GET', + redirect: 'manual', + agent, + signal: controller.signal as unknown as RequestInit['signal'], + }); + } catch (error) { + // Report only the code/type: a network error's message can carry request details. + const { code, type } = error as { code?: string; type?: string }; + const reason = type === 'aborted' ? 'timed out' : code ?? type ?? 'network error'; + throw new AuthenticationError( + `Azure tenant discovery: ${base}/aad/auth failed (${reason}); pass azureTenantId explicitly`, + ); + } - // Drain the (small) body so the keep-alive agent can reuse the socket. - await response.text().catch(() => undefined); - const location = response.headers.get('location'); - if (response.status < 300 || response.status >= 400 || !location) { - throw new AuthenticationError( - `Azure tenant discovery: ${base}/aad/auth returned HTTP ${response.status} without a redirect; pass azureTenantId explicitly`, - ); + // The tenant comes from the headers. Drain the body only so the keep-alive agent can reuse the + // socket, and abort if that fails or doesn't finish promptly. + clearTimeout(timer); + timer = setTimeout(() => controller.abort(), timeoutsMs.bodyDrain); + await response.text().catch(() => controller.abort()); + + const location = response.headers.get('location'); + if (response.status < 300 || response.status >= 400 || !location) { + throw new AuthenticationError( + `Azure tenant discovery: ${base}/aad/auth returned HTTP ${response.status} without a redirect; pass azureTenantId explicitly`, + ); + } + return tenantFromLoginUrl(location); + } finally { + clearTimeout(timer); } - return tenantFromLoginUrl(location); } diff --git a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts index 6130e3dc..d4f28ff9 100644 --- a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts +++ b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts @@ -64,6 +64,7 @@ describe('discoverAzureTenantId', () => { }); after(async () => { + server.closeAllConnections(); await new Promise((resolve) => { server.close(() => resolve()); }); @@ -73,6 +74,29 @@ describe('discoverAzureTenantId', () => { paths.length = 0; }); + // Resolves when the server side of the next connection closes; the responses below never end on + // their own, so only the client destroying its socket closes it. + function nextConnectionClosed(): Promise { + return new Promise((resolve) => { + server.once('connection', (socket) => socket.once('close', () => resolve())); + }); + } + + function agentSocketCount(agent: http.Agent): number { + return [agent.sockets, agent.freeSockets].reduce( + (count, pool) => count + Object.values(pool).reduce((n, sockets) => n + (sockets?.length ?? 0), 0), + 0, + ); + } + + async function expectSocketReleased(closed: Promise, agent: http.Agent): Promise { + await closed; + await new Promise((resolve) => { + setImmediate(resolve); + }); + expect(agentSocketCount(agent)).to.equal(0); + } + it('reads the tenant from the first /aad/auth redirect without following it', async () => { respond = (req, res) => { res.writeHead(302, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize?client_id=x' }); @@ -104,6 +128,72 @@ describe('discoverAzureTenantId', () => { } }); + it('aborts a stalled redirect body and returns the tenant from the headers', async function () { + // The body drain is bounded at 1 s; without the abort, discovery waits 30 s and keeps the socket. + this.timeout(10000); + respond = (req, res) => { + res.writeHead(302, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize' }); + res.write('x'); + }; + const closed = nextConnectionClosed(); + const agent = new http.Agent({ keepAlive: true }); + try { + expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); + await expectSocketReleased(closed, agent); + } finally { + agent.destroy(); + } + }); + + it('returns the tenant and releases the socket when the redirect body fails mid-stream', async () => { + respond = (req, res) => { + res.writeHead(302, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize' }); + res.write('x', () => res.socket?.destroy()); + }; + const closed = nextConnectionClosed(); + const agent = new http.Agent({ keepAlive: true }); + try { + expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); + await expectSocketReleased(closed, agent); + } finally { + agent.destroy(); + } + }); + + it('aborts when the redirect body cannot be decoded', async () => { + // node-fetch rejects the body read without closing the request, so the drain must abort it. + respond = (req, res) => { + res.writeHead(302, { + Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize', + 'Content-Encoding': 'gzip', + }); + res.write('not gzip'); + }; + const closed = nextConnectionClosed(); + const agent = new http.Agent({ keepAlive: true }); + try { + expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); + await expectSocketReleased(closed, agent); + } finally { + agent.destroy(); + } + }); + + it('aborts with the azureTenantId hint when the response headers never arrive', async () => { + respond = () => {}; + const closed = nextConnectionClosed(); + const agent = new http.Agent({ keepAlive: true }); + try { + await expectAuthError( + discoverAzureTenantId(base, agent, { headers: 100, bodyDrain: 100 }), + 'failed (timed out); pass azureTenantId', + ); + await expectSocketReleased(closed, agent); + } finally { + agent.destroy(); + } + }); + it('fails when /aad/auth does not redirect', async () => { respond = (req, res) => { res.writeHead(200); From de79aa1af3832c21580e44086231cdf4552a51c7 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 16 Nov 2026 01:57:56 +0000 Subject: [PATCH 7/7] refactor: read the tenant from the headers and abort tenant discovery Discovery only needs the redirect headers, so abort the request as soon as they arrive instead of draining the body under a second timer: a stalled or broken body can no longer delay discovery or hold the socket. node-fetch's timeout bounds the wait for the headers. Network errors now propagate unwrapped, like the driver's other OAuth requests. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- .../DatabricksOAuth/AzureTenantDiscovery.ts | 62 ++++--------- .../AzureTenantDiscovery.test.ts | 90 +------------------ 2 files changed, 18 insertions(+), 134 deletions(-) diff --git a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts index 128c96e2..0756563e 100644 --- a/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts +++ b/lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts @@ -1,17 +1,13 @@ import http from 'http'; -import fetch, { RequestInit, Response } from 'node-fetch'; +import fetch, { RequestInit } from 'node-fetch'; import AuthenticationError from '../../../errors/AuthenticationError'; // Microsoft Entra login authorities (commercial, US Government, China). Matched as host suffixes, // so a look-alike such as `login.microsoftonline.com.attacker.example` is rejected. const MICROSOFT_LOGIN_HOST_SUFFIXES = ['.microsoftonline.com', '.microsoftonline.us', '.chinacloudapi.cn']; -// Until the response headers arrive. const DISCOVERY_TIMEOUT_MS = 30000; -// For the redirect body after the headers (the tenant is already known by then). -const BODY_DRAIN_TIMEOUT_MS = 1000; - /** * Returns the tenant id from the Entra login URL that a workspace's `/aad/auth` redirects to * (`https://login.microsoftonline.com/{tenant}/oauth2/authorize?...`): its first path segment. @@ -46,47 +42,23 @@ export function tenantFromLoginUrl(location: string): string { * Discovers the workspace's Entra tenant from the first redirect of `{host}/aad/auth`, as the * Python connector and the SQL kernel do. */ -export async function discoverAzureTenantId( - host: string, - agent?: http.Agent, - timeoutsMs = { headers: DISCOVERY_TIMEOUT_MS, bodyDrain: BODY_DRAIN_TIMEOUT_MS }, -): Promise { - const base = (host.includes('://') ? host : `https://${host}`).replace(/\/+$/, ''); - // node-fetch's `timeout` rejects a stalled body without closing the request; aborting destroys the socket. +export async function discoverAzureTenantId(host: string, agent?: http.Agent): Promise { + const url = `${(host.includes('://') ? host : `https://${host}`).replace(/\/+$/, '')}/aad/auth`; const controller = new AbortController(); - let timer = setTimeout(() => controller.abort(), timeoutsMs.headers); - try { - let response: Response; - try { - response = await fetch(`${base}/aad/auth`, { - method: 'GET', - redirect: 'manual', - agent, - signal: controller.signal as unknown as RequestInit['signal'], - }); - } catch (error) { - // Report only the code/type: a network error's message can carry request details. - const { code, type } = error as { code?: string; type?: string }; - const reason = type === 'aborted' ? 'timed out' : code ?? type ?? 'network error'; - throw new AuthenticationError( - `Azure tenant discovery: ${base}/aad/auth failed (${reason}); pass azureTenantId explicitly`, - ); - } - - // The tenant comes from the headers. Drain the body only so the keep-alive agent can reuse the - // socket, and abort if that fails or doesn't finish promptly. - clearTimeout(timer); - timer = setTimeout(() => controller.abort(), timeoutsMs.bodyDrain); - await response.text().catch(() => controller.abort()); + const response = await fetch(url, { + redirect: 'manual', + agent, + timeout: DISCOVERY_TIMEOUT_MS, + signal: controller.signal as unknown as RequestInit['signal'], + }); + // Only the headers are needed; aborting releases the socket instead of leaving the body unread. + controller.abort(); - const location = response.headers.get('location'); - if (response.status < 300 || response.status >= 400 || !location) { - throw new AuthenticationError( - `Azure tenant discovery: ${base}/aad/auth returned HTTP ${response.status} without a redirect; pass azureTenantId explicitly`, - ); - } - return tenantFromLoginUrl(location); - } finally { - clearTimeout(timer); + const location = response.headers.get('location'); + if (response.status < 300 || response.status >= 400 || !location) { + throw new AuthenticationError( + `Azure tenant discovery: ${url} returned HTTP ${response.status} without a redirect; pass azureTenantId explicitly`, + ); } + return tenantFromLoginUrl(location); } diff --git a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts index d4f28ff9..868e13c4 100644 --- a/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts +++ b/tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts @@ -106,31 +106,7 @@ describe('discoverAzureTenantId', () => { expect(paths).to.deep.equal(['/aad/auth']); }); - it('drains the redirect body so a keep-alive agent reuses the socket', async () => { - respond = (req, res) => { - res.writeHead(302, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize' }); - // Larger than the stream buffers, so an undrained body would hold the only socket. - res.end('x'.repeat(1024 * 1024)); - }; - let connections = 0; - const onConnection = () => { - connections += 1; - }; - server.on('connection', onConnection); - const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); - try { - expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); - expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); - expect(connections).to.equal(1); - } finally { - server.off('connection', onConnection); - agent.destroy(); - } - }); - - it('aborts a stalled redirect body and returns the tenant from the headers', async function () { - // The body drain is bounded at 1 s; without the abort, discovery waits 30 s and keeps the socket. - this.timeout(10000); + it('returns the tenant from the headers of a stalled redirect and releases the socket', async () => { respond = (req, res) => { res.writeHead(302, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize' }); res.write('x'); @@ -145,55 +121,6 @@ describe('discoverAzureTenantId', () => { } }); - it('returns the tenant and releases the socket when the redirect body fails mid-stream', async () => { - respond = (req, res) => { - res.writeHead(302, { Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize' }); - res.write('x', () => res.socket?.destroy()); - }; - const closed = nextConnectionClosed(); - const agent = new http.Agent({ keepAlive: true }); - try { - expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); - await expectSocketReleased(closed, agent); - } finally { - agent.destroy(); - } - }); - - it('aborts when the redirect body cannot be decoded', async () => { - // node-fetch rejects the body read without closing the request, so the drain must abort it. - respond = (req, res) => { - res.writeHead(302, { - Location: 'https://login.microsoftonline.com/tenant-xyz/oauth2/authorize', - 'Content-Encoding': 'gzip', - }); - res.write('not gzip'); - }; - const closed = nextConnectionClosed(); - const agent = new http.Agent({ keepAlive: true }); - try { - expect(await discoverAzureTenantId(base, agent)).to.equal('tenant-xyz'); - await expectSocketReleased(closed, agent); - } finally { - agent.destroy(); - } - }); - - it('aborts with the azureTenantId hint when the response headers never arrive', async () => { - respond = () => {}; - const closed = nextConnectionClosed(); - const agent = new http.Agent({ keepAlive: true }); - try { - await expectAuthError( - discoverAzureTenantId(base, agent, { headers: 100, bodyDrain: 100 }), - 'failed (timed out); pass azureTenantId', - ); - await expectSocketReleased(closed, agent); - } finally { - agent.destroy(); - } - }); - it('fails when /aad/auth does not redirect', async () => { respond = (req, res) => { res.writeHead(200); @@ -210,21 +137,6 @@ describe('discoverAzureTenantId', () => { await expectAuthError(discoverAzureTenantId(base), 'HTTP 200 without a redirect'); }); - it('wraps a network failure with the azureTenantId hint', async () => { - const closed = http.createServer(); - await new Promise((resolve) => { - closed.listen(0, '127.0.0.1', resolve); - }); - const { port } = closed.address() as AddressInfo; - await new Promise((resolve) => { - closed.close(() => resolve()); - }); - await expectAuthError( - discoverAzureTenantId(`http://127.0.0.1:${port}`), - 'failed (ECONNREFUSED); pass azureTenantId', - ); - }); - it('fails when the redirect is not to a Microsoft login host', async () => { respond = (req, res) => { res.writeHead(302, { Location: 'https://idp.example.com/tenant-xyz/authorize' });