-
Notifications
You must be signed in to change notification settings - Fork 52
Add manual tenant sign-in fallback for Conditional Access tenants #1511
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
CoffeeKanzler
wants to merge
10
commits into
microsoft:main
Choose a base branch
from
CoffeeKanzler:issue-1332-azure-tenant-setting
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.
+308
−4
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
66a06aa
Add azure tenant setting for sign-in
CoffeeKanzler 451dc18
Use configured tenant for provider authentication
CoffeeKanzler 9567f03
Remove local asset ignore entries
CoffeeKanzler 7d46ce5
Address tenant auth review feedback
CoffeeKanzler 144eebe
Add manual tenant sign-in fallback
CoffeeKanzler 19bcdf8
Persist manual tenant for subscription discovery
CoffeeKanzler 793aa99
Address manual tenant sign-in review feedback
CoffeeKanzler 1cabd47
Potential fix for pull request finding
CoffeeKanzler 2cb8247
Sort tenant picks by label and test empty-discovery fallback
CoffeeKanzler 9cff715
Replace globalState persistence with azure.tenant setting
CoffeeKanzler 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
Some comments aren't visible on the classic Files Changed page.
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
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
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,54 @@ | ||
| /*--------------------------------------------------------------------------------------------- | ||
| * Copyright (c) Microsoft Corporation. All rights reserved. | ||
| * Licensed under the MIT License. See License.md in the project root for license information. | ||
| *--------------------------------------------------------------------------------------------*/ | ||
|
|
||
| import { AzureAccount, AzureSubscriptionProvider, isNotSignedInError, signInToTenant as signInToTenantFromAccounts, TenantIdAndAccount } from '@microsoft/vscode-azext-azureauth'; | ||
| import { IActionContext } from '@microsoft/vscode-azext-utils'; | ||
| import { setConfiguredAzureTenant } from '../../utils/azureTenantSetting'; | ||
| import { localize } from '../../utils/localize'; | ||
|
|
||
| /** | ||
| * Signs in to a specific tenant (directory). | ||
| * | ||
| * Delegates to the auth package's tenant picker, which lists unauthenticated tenants discovered for | ||
| * the signed-in accounts. When the user is not signed in to any account there are no tenants to | ||
| * enumerate, so this falls back to prompting for a tenant ID or domain. Manual entry is the only way | ||
| * to unblock users whose tenant enforces conditional access that prevents the initial common-endpoint | ||
| * sign-in: they have no authenticated account to enumerate tenants from, so they must direct the very | ||
| * first sign-in at their tenant (similar to `az login --tenant <tenant>`). The entered tenant is | ||
| * persisted to the `azure.tenant` setting so account-level tenant discovery can fall back to it on | ||
| * later reloads (see {@link getConfiguredTenantFallback}); otherwise the sign-in succeeds but no | ||
| * resources load. | ||
| * | ||
| * The `signInToTenantFromAccounts` parameter is injectable for testing; production callers use the | ||
| * auth package's implementation. | ||
| */ | ||
| export async function signInToTenant( | ||
| context: IActionContext, | ||
| subscriptionProvider: AzureSubscriptionProvider, | ||
| signInFromAccounts: (provider: AzureSubscriptionProvider, account?: AzureAccount) => Promise<void> = signInToTenantFromAccounts, | ||
| ): Promise<void> { | ||
| try { | ||
| await signInFromAccounts(subscriptionProvider); | ||
| return; | ||
| } catch (error) { | ||
| if (!isNotSignedInError(error)) { | ||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| const tenantId = (await context.ui.showInputBox({ | ||
| placeHolder: localize('enterTenantIdPlaceholder', 'Tenant ID or domain'), | ||
| prompt: localize('enterTenantIdPrompt', 'Enter the tenant ID or domain to sign in to.'), | ||
| validateInput: value => value?.trim() ? undefined : localize('enterTenantIdValidation', 'Enter a tenant ID or domain.'), | ||
| })).trim(); | ||
|
|
||
| // The account is filled in interactively during sign-in, so it is omitted here. | ||
| const signedIn = await subscriptionProvider.signIn({ tenantId } as TenantIdAndAccount); | ||
| if (signedIn) { | ||
| // Persist only after a successful sign-in so a typo'd or cancelled attempt doesn't leave a | ||
| // broken tenant in the user's settings that later tenant discovery would keep injecting. | ||
| await setConfiguredAzureTenant(tenantId); | ||
| } | ||
| } | ||
|
Comment on lines
+44
to
+54
|
||
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
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
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,41 @@ | ||
| /*--------------------------------------------------------------------------------------------- | ||
| * Copyright (c) Microsoft Corporation. All rights reserved. | ||
| * Licensed under the MIT License. See License.md in the project root for license information. | ||
| *--------------------------------------------------------------------------------------------*/ | ||
|
|
||
| import { AzureAccount, AzureTenant } from '@microsoft/vscode-azext-azureauth'; | ||
| import * as vscode from 'vscode'; | ||
|
|
||
| export const azureTenantSettingKey = 'azure.tenant'; | ||
|
|
||
| export function normalizeConfiguredTenant(tenant: string | undefined): string | undefined { | ||
| const trimmedTenant = tenant?.trim(); | ||
| return trimmedTenant ? trimmedTenant : undefined; | ||
| } | ||
|
|
||
| export function getConfiguredAzureTenant(): string | undefined { | ||
| return normalizeConfiguredTenant(vscode.workspace.getConfiguration().get<string>(azureTenantSettingKey)); | ||
| } | ||
|
|
||
| export async function setConfiguredAzureTenant(tenant: string | undefined): Promise<void> { | ||
| await vscode.workspace.getConfiguration().update(azureTenantSettingKey, normalizeConfiguredTenant(tenant), vscode.ConfigurationTarget.Global); | ||
| } | ||
|
|
||
| /** | ||
| * Returns the configured tenant as a synthetic {@link AzureTenant} for the given account, or | ||
| * `undefined` when no tenant is configured. | ||
| * | ||
| * This is the conditional-access bootstrap: when ARM tenant discovery returns nothing for an | ||
| * account (the account can't enumerate tenants because conditional access blocks the silent | ||
| * common-endpoint token), the configured tenant is injected so the normal per-tenant sign-in and | ||
| * subscription flow can run against the tenant's own session. | ||
| * | ||
| * `displayName` is set to the configured value because the Accounts & Tenants view renders every | ||
| * tenant through `TenantTreeItem`, which requires a non-null `displayName`; without one the view | ||
| * would throw and render empty. The real directory name isn't known (that's what discovery would | ||
| * have told us), so the entered ID/domain is the best label available. | ||
| */ | ||
| export function getConfiguredTenantFallback(account: AzureAccount, configuredTenant: string | undefined = getConfiguredAzureTenant()): AzureTenant | undefined { | ||
| const normalizedTenant = normalizeConfiguredTenant(configuredTenant); | ||
| return normalizedTenant ? { tenantId: normalizedTenant, displayName: normalizedTenant, account } : undefined; | ||
| } |
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,177 @@ | ||
| /*--------------------------------------------------------------------------------------------- | ||
| * Copyright (c) Microsoft Corporation. All rights reserved. | ||
| * Licensed under the MIT License. See License.md in the project root for license information. | ||
| *--------------------------------------------------------------------------------------------*/ | ||
|
|
||
| import assert from 'assert'; | ||
| import { AzureAccount, AzureSubscriptionProvider, NotSignedInError, TenantIdAndAccount, getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth'; | ||
| import { IActionContext } from '@microsoft/vscode-azext-utils'; | ||
| import { signInToTenant } from '../src/commands/accounts/signInToTenant'; | ||
| import { TenantTreeItem } from '../src/tree/tenants/TenantTreeItem'; | ||
| import { getConfiguredAzureTenant, getConfiguredTenantFallback, normalizeConfiguredTenant, setConfiguredAzureTenant } from '../src/utils/azureTenantSetting'; | ||
|
|
||
| suite('signInToTenant', () => { | ||
| teardown(async () => { | ||
| await setConfiguredAzureTenant(undefined); | ||
| }); | ||
|
|
||
| test('delegates to the auth package picker when an account is signed in', async () => { | ||
| let delegated = false; | ||
| let inputBoxShown = false; | ||
| let signInCalled = false; | ||
|
|
||
| const context = createTestActionContext({ | ||
| showInputBox: async () => { | ||
| inputBoxShown = true; | ||
| return 'should-not-be-used'; | ||
| }, | ||
| }); | ||
| const provider = createTestSubscriptionProvider({ | ||
| signIn: async () => { | ||
| signInCalled = true; | ||
| return true; | ||
| }, | ||
| }); | ||
|
|
||
| await signInToTenant(context, provider, async () => { | ||
| delegated = true; | ||
| }); | ||
|
|
||
| assert.strictEqual(delegated, true); | ||
| assert.strictEqual(inputBoxShown, false); | ||
| assert.strictEqual(signInCalled, false); | ||
| assert.strictEqual(getConfiguredAzureTenant(), undefined); | ||
| }); | ||
|
|
||
| test('falls back to manual entry and persists the tenant when not signed in', async () => { | ||
| let signedInTenantId: string | undefined; | ||
| let signedInAccount: AzureAccount | undefined; | ||
|
|
||
| const context = createTestActionContext({ | ||
| showInputBox: async () => ' contoso.onmicrosoft.com ', | ||
| }); | ||
| const provider = createTestSubscriptionProvider({ | ||
| signIn: async tenant => { | ||
| signedInTenantId = tenant?.tenantId; | ||
| signedInAccount = tenant?.account; | ||
| return true; | ||
| }, | ||
| }); | ||
|
|
||
| await signInToTenant(context, provider, async () => { | ||
| throw new NotSignedInError(); | ||
| }); | ||
|
|
||
| assert.strictEqual(signedInTenantId, 'contoso.onmicrosoft.com'); | ||
| assert.strictEqual(signedInAccount, undefined); | ||
| assert.strictEqual(getConfiguredAzureTenant(), 'contoso.onmicrosoft.com'); | ||
| }); | ||
|
|
||
| test('does not persist the tenant when the manual sign-in is not completed', async () => { | ||
| const context = createTestActionContext({ | ||
| showInputBox: async () => 'contoso.onmicrosoft.com', | ||
| }); | ||
| const provider = createTestSubscriptionProvider({ | ||
| signIn: async () => false, | ||
| }); | ||
|
|
||
| await signInToTenant(context, provider, async () => { | ||
| throw new NotSignedInError(); | ||
| }); | ||
|
|
||
| assert.strictEqual(getConfiguredAzureTenant(), undefined); | ||
| }); | ||
|
|
||
| test('rethrows non sign-in errors without prompting', async () => { | ||
| let inputBoxShown = false; | ||
|
|
||
| const context = createTestActionContext({ | ||
| showInputBox: async () => { | ||
| inputBoxShown = true; | ||
| return 'contoso.onmicrosoft.com'; | ||
| }, | ||
| }); | ||
| const provider = createTestSubscriptionProvider({ | ||
| signIn: async () => true, | ||
| }); | ||
|
|
||
| await assert.rejects( | ||
| signInToTenant(context, provider, async () => { | ||
| throw new Error('boom'); | ||
| }), | ||
| /boom/, | ||
| ); | ||
| assert.strictEqual(inputBoxShown, false); | ||
| assert.strictEqual(getConfiguredAzureTenant(), undefined); | ||
| }); | ||
| }); | ||
|
|
||
| suite('azureTenantSetting', () => { | ||
| teardown(async () => { | ||
| await setConfiguredAzureTenant(undefined); | ||
| }); | ||
|
|
||
| test('normalizeConfiguredTenant trims and treats blank as undefined', () => { | ||
| assert.strictEqual(normalizeConfiguredTenant(' contoso '), 'contoso'); | ||
| assert.strictEqual(normalizeConfiguredTenant(' '), undefined); | ||
| assert.strictEqual(normalizeConfiguredTenant(''), undefined); | ||
| assert.strictEqual(normalizeConfiguredTenant(undefined), undefined); | ||
| }); | ||
|
|
||
| test('setConfiguredAzureTenant round-trips through configuration', async () => { | ||
| await setConfiguredAzureTenant(' contoso.onmicrosoft.com '); | ||
| assert.strictEqual(getConfiguredAzureTenant(), 'contoso.onmicrosoft.com'); | ||
|
|
||
| await setConfiguredAzureTenant(undefined); | ||
| assert.strictEqual(getConfiguredAzureTenant(), undefined); | ||
| }); | ||
|
|
||
| test('getConfiguredTenantFallback injects a synthetic tenant only when configured', () => { | ||
| const account = createAccount(); | ||
|
|
||
| assert.deepStrictEqual(getConfiguredTenantFallback(account, 'contoso.onmicrosoft.com'), { | ||
| tenantId: 'contoso.onmicrosoft.com', | ||
| displayName: 'contoso.onmicrosoft.com', | ||
| account, | ||
| }); | ||
| assert.strictEqual(getConfiguredTenantFallback(account, ' '), undefined); | ||
| assert.strictEqual(getConfiguredTenantFallback(account, undefined), undefined); | ||
| }); | ||
|
|
||
| test('configured tenant fallback renders in the Tenants view without throwing', () => { | ||
| const account = createAccount(); | ||
| const fallback = getConfiguredTenantFallback(account, 'contoso.onmicrosoft.com'); | ||
| assert.ok(fallback); | ||
|
|
||
| // The Accounts & Tenants view builds a TenantTreeItem for every tenant, and that | ||
| // constructor requires a non-null displayName. A synthetic fallback without one would | ||
| // throw and collapse the whole view to empty. | ||
| assert.doesNotThrow(() => new TenantTreeItem(fallback, account)); | ||
| }); | ||
| }); | ||
|
|
||
| function createAccount(): AzureAccount { | ||
| return { | ||
| id: 'accountId', | ||
| label: 'Account', | ||
| environment: getConfiguredAzureEnv(), | ||
| }; | ||
| } | ||
|
|
||
| function createTestActionContext(options: { | ||
| showInputBox: () => Promise<string>; | ||
| }): IActionContext { | ||
| return { | ||
| ui: { | ||
| showInputBox: options.showInputBox, | ||
| }, | ||
| } as unknown as IActionContext; | ||
| } | ||
|
|
||
| function createTestSubscriptionProvider(options: { | ||
| signIn: (tenant?: Partial<TenantIdAndAccount>) => Promise<boolean>; | ||
| }): AzureSubscriptionProvider { | ||
| return { | ||
| signIn: options.signIn, | ||
| } as unknown as AzureSubscriptionProvider; | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should make the changes in the auth package in
microsoft/vscode-azuretoolsrather than duplicating the code there. Potentially we add a tenant or tenant ID arg to that function? @alexweininger thoughts?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@CoffeeKanzler thanks for opening the PR!
getPickshere duplicates the auth package's existing picker, can we instead just delegate to the auth package'ssignInToTenant(provider)and only fall back to the manual tenant input box when it throwsNotSignedInError? That avoids the duplication and any auth-package changes. Also, do we actually need themanualSignInTenantpersistence +getSubscriptionContextoverride?For example: main...alexweininger/sign-in-to-tenant-manual-entry
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Happy to refactor the picker to delegate to the auth package's signInToTenant(provider) with an input-box fallback on NotSignedInError, @alexweininger.
On whether we still need the manualSignInTenant persistence + getSubscriptionContext override: I tested exactly this. The manual sign-in itself succeeds, but resources never populate afterward.
The reason: subscription enumeration goes through getSubscriptionContext({ account, tenantId: undefined }) → listTenants(), and with tenantId undefined the silent token request hits the common/organizations
endpoint. So no subscriptions come back and the tree stays empty. The override re-injects the signed-in tenant into that account-level context, which scopes the silent token correctly and makes resources load.
It has to be persisted (not just in-memory) because the same enumeration re-runs on every reload.
@bwateratmsft — to your MSAL-stickiness question, that's what I was hoping too, but in practice the broker is only sticky for the interactive sign-in, not for the silent enumeration token. Without the persisted
tenant, a reload gives an empty tree.
So my proposal: Refactor the delegation (drop the duplicated picker) and keep the tenant persistence + context override (necessary for resources to actually load).
If you'd rather that re-scoping live in the auth package instead like e.g. a "default/sticky tenant" the provider applies to account-level requests then I'd need to further study the auth package after I am back.
Heads up on timing: I'm traveling in about an hour and won't be back until Friday at the earliest, so apologies in advance for the slow follow-up. I'll pick this up as soon as I'm back.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry to go back and forth on it, but now that we know we need to persist that value, then I think it's best kept as a setting like your original design.
manualSignInTenantglobalState, use an advanced setting instead.getTenantsForAccount(we already override it, and it gets theaccount): when ARM/tenantsreturns empty/throws for a conditional-access user, injectAzureTenant { tenantId: <setting>, account }. The normal per-tenant flow then lists subscriptions via that tenant's session, so we can drop thegetSubscriptionContextoverride entirely.signIn({ tenantId }).summary: one setting + the existing public override, no globalState, no internal coupling. Clients consume our discovered subscriptions via the Resources API, so this covers the whole extension family too.