Repository navigation
fix: discover the Azure tenant for Thrift service-principal M2M #606
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vuanhphung
wants to merge
7
commits into
main
Choose a base branch
from
fix/azure-m2m-tenant-discovery
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
25ea610
fix: discover the Azure tenant for Thrift service-principal M2M
vuanhphung 2d50b8e
fix: keep the azureTenantId hint when tenant discovery cannot connect
vuanhphung 0190605
fix: drain the /aad/auth redirect body during tenant discovery
vuanhphung 8dcfba5
docs: cite #606 in the changelog and update the tenant fallback comment
vuanhphung dd96d96
test: pin discovery for a blank azureTenantId and the 3xx status check
vuanhphung 420504f
fix: abort tenant discovery when the redirect body stalls or fails
vuanhphung de79aa1
refactor: read the tenant from the headers and abort tenant discovery
vuanhphung File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
lib/connection/auth/DatabricksOAuth/AzureTenantDiscovery.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import http from 'http'; | ||
| 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']; | ||
|
|
||
| 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<string> { | ||
| const url = `${(host.includes('://') ? host : `https://${host}`).replace(/\/+$/, '')}/aad/auth`; | ||
| const controller = new AbortController(); | ||
| 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: ${url} returned HTTP ${response.status} without a redirect; pass azureTenantId explicitly`, | ||
| ); | ||
| } | ||
| return tenantFromLoginUrl(location); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
147 changes: 147 additions & 0 deletions
147
tests/unit/connection/auth/DatabricksOAuth/AzureTenantDiscovery.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| 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<unknown>, contains: string): Promise<void> { | ||
| 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<string | undefined> = []; | ||
|
|
||
| before(async () => { | ||
| server = http.createServer((req, res) => { | ||
| paths.push(req.url); | ||
| respond(req, res); | ||
| }); | ||
| await new Promise<void>((resolve) => { | ||
| server.listen(0, '127.0.0.1', resolve); | ||
| }); | ||
| base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; | ||
| }); | ||
|
|
||
| after(async () => { | ||
| server.closeAllConnections(); | ||
| await new Promise<void>((resolve) => { | ||
| server.close(() => resolve()); | ||
| }); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| 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<void> { | ||
| 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<void>, agent: http.Agent): Promise<void> { | ||
| 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' }); | ||
| res.end(); | ||
| }; | ||
| expect(await discoverAzureTenantId(`${base}/`)).to.equal('tenant-xyz'); | ||
| expect(paths).to.deep.equal(['/aad/auth']); | ||
| }); | ||
|
|
||
| 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'); | ||
| }; | ||
| 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('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 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('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'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.