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
3
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 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
72 changes: 72 additions & 0 deletions
72
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,72 @@ | ||
| 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<string> { | ||
| const base = (host.includes('://') ? host : `https://${host}`).replace(/\/+$/, ''); | ||
| 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) { | ||
| throw new AuthenticationError( | ||
| `Azure tenant discovery: ${base}/aad/auth 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
115 changes: 115 additions & 0 deletions
115
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,115 @@ | ||
| 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 () => { | ||
| await new Promise<void>((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('wraps a network failure with the azureTenantId hint', async () => { | ||
| const closed = http.createServer(); | ||
| await new Promise<void>((resolve) => { | ||
| closed.listen(0, '127.0.0.1', resolve); | ||
| }); | ||
| const { port } = closed.address() as AddressInfo; | ||
| await new Promise<void>((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' }); | ||
| res.end(); | ||
| }; | ||
| await expectAuthError(discoverAzureTenantId(base), 'Microsoft login host'); | ||
| }); | ||
| }); |
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
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.