@microsoft/vscode-azext-azureauth 4.2.2 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/cjs/src/AzureDevOpsSubscriptionProvider.js +215 -0
  3. package/dist/cjs/src/NotSignedInError.js +63 -0
  4. package/dist/cjs/src/VSCodeAzureSubscriptionProvider.js +385 -0
  5. package/dist/cjs/src/getSessionFromVSCode.js +108 -0
  6. package/{out → dist/cjs}/src/index.js +2 -1
  7. package/dist/cjs/src/signInToTenant.js +79 -0
  8. package/dist/cjs/src/utils/configuredAzureEnv.js +128 -0
  9. package/dist/cjs/src/utils/getUnauthenticatedTenants.js +23 -0
  10. package/dist/cjs/src/utils/isGetSubscriptionsFilter.js +27 -0
  11. package/{out → dist/esm}/src/AzureAuthentication.d.ts +2 -2
  12. package/dist/esm/src/AzureAuthentication.js +6 -0
  13. package/{out → dist/esm}/src/AzureDevOpsSubscriptionProvider.d.ts +6 -6
  14. package/dist/esm/src/AzureDevOpsSubscriptionProvider.js +210 -0
  15. package/{out → dist/esm}/src/AzureSubscription.d.ts +2 -2
  16. package/dist/esm/src/AzureSubscription.js +6 -0
  17. package/dist/esm/src/AzureSubscriptionProvider.js +6 -0
  18. package/{out → dist/esm}/src/AzureTenant.d.ts +2 -2
  19. package/dist/esm/src/AzureTenant.js +6 -0
  20. package/{out → dist/esm}/src/NotSignedInError.js +4 -9
  21. package/{out → dist/esm}/src/VSCodeAzureSubscriptionProvider.d.ts +8 -13
  22. package/dist/esm/src/VSCodeAzureSubscriptionProvider.js +348 -0
  23. package/{out → dist/esm}/src/getSessionFromVSCode.d.ts +3 -3
  24. package/dist/esm/src/getSessionFromVSCode.js +72 -0
  25. package/{out → dist/esm}/src/index.d.ts +2 -1
  26. package/dist/esm/src/index.js +16 -0
  27. package/dist/esm/src/signInToTenant.js +43 -0
  28. package/dist/esm/src/utils/configuredAzureEnv.js +90 -0
  29. package/dist/esm/src/utils/getUnauthenticatedTenants.d.ts +9 -0
  30. package/dist/esm/src/utils/getUnauthenticatedTenants.js +20 -0
  31. package/dist/esm/src/utils/isAuthenticationWwwAuthenticateRequest.js +12 -0
  32. package/dist/esm/src/utils/isGetSubscriptionsFilter.d.ts +14 -0
  33. package/dist/esm/src/utils/isGetSubscriptionsFilter.js +23 -0
  34. package/package.json +13 -12
  35. package/out/src/AzureDevOpsSubscriptionProvider.js +0 -252
  36. package/out/src/VSCodeAzureSubscriptionProvider.js +0 -384
  37. package/out/src/getSessionFromVSCode.js +0 -76
  38. package/out/src/signInToTenant.js +0 -64
  39. package/out/src/utils/configuredAzureEnv.js +0 -94
  40. package/out/src/utils/getUnauthenticatedTenants.d.ts +0 -6
  41. package/out/src/utils/getUnauthenticatedTenants.js +0 -52
  42. /package/{out → dist/cjs}/src/AzureAuthentication.js +0 -0
  43. /package/{out → dist/cjs}/src/AzureSubscription.js +0 -0
  44. /package/{out → dist/cjs}/src/AzureSubscriptionProvider.js +0 -0
  45. /package/{out → dist/cjs}/src/AzureTenant.js +0 -0
  46. /package/{out → dist/cjs}/src/utils/isAuthenticationWwwAuthenticateRequest.js +0 -0
  47. /package/{out → dist/esm}/src/AzureSubscriptionProvider.d.ts +0 -0
  48. /package/{out → dist/esm}/src/NotSignedInError.d.ts +0 -0
  49. /package/{out → dist/esm}/src/signInToTenant.d.ts +0 -0
  50. /package/{out → dist/esm}/src/utils/configuredAzureEnv.d.ts +0 -0
  51. /package/{out → dist/esm}/src/utils/isAuthenticationWwwAuthenticateRequest.d.ts +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Change Log
2
2
 
3
+ ## 5.1.0 - 2025-10-27
4
+
5
+ * [#2102](https://github.com/microsoft/vscode-azuretools/pull/2102) Fixes an issue causing infinite event loops especially in https://vscode.dev/azure
6
+ * [#2110](https://github.com/microsoft/vscode-azuretools/pull/2110) `vscode.authentication.onDidChangeSessions()` is no longer subscribed to unless the caller calls `AzureSubscriptionProvider.onDidSignIn()` or `AzureSubscriptionProvider.onDidSignOut()`.
7
+
8
+ ## 5.0.0 - 2025-10-07
9
+
10
+ * [#2092](https://github.com/microsoft/vscode-azuretools/pull/2092) Converts from CJS only to CJS+ESM
11
+ * Adopts finalized auth challenges API
12
+
3
13
  ## 4.2.2 - 2025-09-10
4
14
 
5
15
  * [#2073](https://github.com/microsoft/vscode-azuretools/pull/2073) Changes to adjust to proposed API changes
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Microsoft Corporation. All rights reserved.
4
+ * Licensed under the MIT License. See License.txt in the project root for license information.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.AzureDevOpsSubscriptionProvider = void 0;
8
+ exports.createAzureDevOpsSubscriptionProviderFactory = createAzureDevOpsSubscriptionProviderFactory;
9
+ const configuredAzureEnv_1 = require("./utils/configuredAzureEnv");
10
+ let azureDevOpsSubscriptionProvider;
11
+ function createAzureDevOpsSubscriptionProviderFactory(initializer) {
12
+ return async () => {
13
+ azureDevOpsSubscriptionProvider ??= new AzureDevOpsSubscriptionProvider(initializer);
14
+ return azureDevOpsSubscriptionProvider;
15
+ };
16
+ }
17
+ /**
18
+ * AzureSubscriptionProvider implemented to authenticate via federated DevOps service connection, using workflow identity federation
19
+ * To learn how to configure your DevOps environment to use this provider, refer to the README.md
20
+ * NOTE: This provider is only available when running in an Azure DevOps pipeline
21
+ * Reference: https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation
22
+ */
23
+ class AzureDevOpsSubscriptionProvider {
24
+ _tokenCredential;
25
+ /**
26
+ * The resource ID of the Azure DevOps federated service connection,
27
+ * which can be found on the `resourceId` field of the URL at the address bar
28
+ * when viewing the service connection in the Azure DevOps portal
29
+ */
30
+ _SERVICE_CONNECTION_ID;
31
+ /**
32
+ * The `Tenant ID` field of the service connection properties
33
+ */
34
+ _DOMAIN;
35
+ /**
36
+ * The `Service Principal Id` field of the service connection properties
37
+ */
38
+ _CLIENT_ID;
39
+ constructor({ serviceConnectionId, domain, clientId }) {
40
+ if (!serviceConnectionId || !domain || !clientId) {
41
+ throw new Error(`Missing initializer values to identify Azure DevOps federated service connection\n
42
+ Values provided:\n
43
+ serviceConnectionId: ${serviceConnectionId ? "✅" : "❌"}\n
44
+ domain: ${domain ? "✅" : "❌"}\n
45
+ clientId: ${clientId ? "✅" : "❌"}\n
46
+ `);
47
+ }
48
+ this._SERVICE_CONNECTION_ID = serviceConnectionId;
49
+ this._DOMAIN = domain;
50
+ this._CLIENT_ID = clientId;
51
+ }
52
+ async getSubscriptions(_filter) {
53
+ // ignore the filter setting because not every consumer of this provider will use the Resources extension
54
+ const results = [];
55
+ for (const tenant of await this.getTenants()) {
56
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
57
+ const tenantId = tenant.tenantId;
58
+ results.push(...await this.getSubscriptionsForTenant(tenantId));
59
+ }
60
+ const sortSubscriptions = (subscriptions) => subscriptions.sort((a, b) => a.name.localeCompare(b.name));
61
+ return sortSubscriptions(results);
62
+ }
63
+ async isSignedIn() {
64
+ return !!this._tokenCredential;
65
+ }
66
+ async signIn() {
67
+ this._tokenCredential = await getTokenCredential(this._SERVICE_CONNECTION_ID, this._DOMAIN, this._CLIENT_ID);
68
+ return !!this._tokenCredential;
69
+ }
70
+ async signOut() {
71
+ this._tokenCredential = undefined;
72
+ }
73
+ async getTenants() {
74
+ return [{
75
+ tenantId: this._tokenCredential?.tenantId,
76
+ account: {
77
+ id: "test-account-id",
78
+ label: "test-account",
79
+ }
80
+ }];
81
+ }
82
+ /**
83
+ * Gets the subscriptions for a given tenant.
84
+ *
85
+ * @param tenantId The tenant ID to get subscriptions for.
86
+ *
87
+ * @returns The list of subscriptions for the tenant.
88
+ */
89
+ async getSubscriptionsForTenant(tenantId) {
90
+ const { client, credential, authentication } = await this.getSubscriptionClient(tenantId);
91
+ const environment = (0, configuredAzureEnv_1.getConfiguredAzureEnv)();
92
+ const subscriptions = [];
93
+ for await (const subscription of client.subscriptions.list()) {
94
+ subscriptions.push({
95
+ authentication,
96
+ environment: environment,
97
+ credential: credential,
98
+ isCustomCloud: environment.isCustomCloud,
99
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
100
+ name: subscription.displayName,
101
+ subscriptionId: subscription.subscriptionId,
102
+ /* eslint-enable @typescript-eslint/no-non-null-assertion */
103
+ tenantId,
104
+ account: {
105
+ id: "test-account-id",
106
+ label: "test-account",
107
+ },
108
+ });
109
+ }
110
+ return subscriptions;
111
+ }
112
+ /**
113
+ * Gets a fully-configured subscription client for a given tenant ID
114
+ *
115
+ * @param tenantId (Optional) The tenant ID to get a client for
116
+ *
117
+ * @returns A client, the credential used by the client, and the authentication function
118
+ */
119
+ async getSubscriptionClient(_tenantId, scopes) {
120
+ const armSubs = await import('@azure/arm-resources-subscriptions');
121
+ if (!this._tokenCredential) {
122
+ throw new Error('Not signed in');
123
+ }
124
+ const accessToken = (await this._tokenCredential?.getToken("https://management.azure.com/.default"))?.token || '';
125
+ const getSession = () => {
126
+ return {
127
+ accessToken,
128
+ id: this._tokenCredential?.tenantId || '',
129
+ account: {
130
+ id: this._tokenCredential?.tenantId || '',
131
+ label: this._tokenCredential?.tenantId || '',
132
+ },
133
+ tenantId: this._tokenCredential?.tenantId || '',
134
+ scopes: scopes || [],
135
+ };
136
+ };
137
+ return {
138
+ client: new armSubs.SubscriptionClient(this._tokenCredential),
139
+ credential: this._tokenCredential,
140
+ authentication: {
141
+ getSession,
142
+ getSessionWithScopes: getSession,
143
+ }
144
+ };
145
+ }
146
+ onDidSignIn = () => { return { dispose() { } }; };
147
+ onDidSignOut = () => { return { dispose() { } }; };
148
+ }
149
+ exports.AzureDevOpsSubscriptionProvider = AzureDevOpsSubscriptionProvider;
150
+ /*
151
+ * @param serviceConnectionId The resource ID of the Azure DevOps federated service connection,
152
+ * which can be found on the `resourceId` field of the URL at the address bar when viewing the service connection in the Azure DevOps portal
153
+ * @param domain The `Tenant ID` field of the service connection properties
154
+ * @param clientId The `Service Principal Id` field of the service connection properties
155
+ */
156
+ async function getTokenCredential(serviceConnectionId, domain, clientId) {
157
+ if (!process.env.AGENT_BUILDDIRECTORY) {
158
+ // Assume that AGENT_BUILDDIRECTORY is set if running in an Azure DevOps pipeline.
159
+ // So when not running in an Azure DevOps pipeline, throw an error since we cannot use the DevOps federated service connection credential.
160
+ throw new Error(`Cannot create DevOps federated service connection credential outside of an Azure DevOps pipeline.`);
161
+ }
162
+ else {
163
+ console.log(`Creating DevOps federated service connection credential for service connection..`);
164
+ // Pre-defined DevOps variable reference: https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops
165
+ const systemAccessToken = process.env.SYSTEM_ACCESSTOKEN;
166
+ const teamFoundationCollectionUri = process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI;
167
+ const teamProjectId = process.env.SYSTEM_TEAMPROJECTID;
168
+ const planId = process.env.SYSTEM_PLANID;
169
+ const jobId = process.env.SYSTEM_JOBID;
170
+ if (!systemAccessToken || !teamFoundationCollectionUri || !teamProjectId || !planId || !jobId) {
171
+ throw new Error(`Azure DevOps environment variables are not set.\n
172
+ process.env.SYSTEM_ACCESSTOKEN: ${process.env.SYSTEM_ACCESSTOKEN ? "✅" : "❌"}\n
173
+ process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI: ${process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI ? "✅" : "❌"}\n
174
+ process.env.SYSTEM_TEAMPROJECTID: ${process.env.SYSTEM_TEAMPROJECTID ? "✅" : "❌"}\n
175
+ process.env.SYSTEM_PLANID: ${process.env.SYSTEM_PLANID ? "✅" : "❌"}\n
176
+ process.env.SYSTEM_JOBID: ${process.env.SYSTEM_JOBID ? "✅" : "❌"}\n
177
+ REMEMBER: process.env.SYSTEM_ACCESSTOKEN must be explicitly mapped!\n
178
+ https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#systemaccesstoken
179
+ `);
180
+ }
181
+ const oidcRequestUrl = `${teamFoundationCollectionUri}${teamProjectId}/_apis/distributedtask/hubs/build/plans/${planId}/jobs/${jobId}/oidctoken?api-version=7.1-preview.1&serviceConnectionId=${serviceConnectionId}`;
182
+ const { ClientAssertionCredential } = await import("@azure/identity");
183
+ return new ClientAssertionCredential(domain, clientId, async () => await requestOidcToken(oidcRequestUrl, systemAccessToken));
184
+ }
185
+ }
186
+ /**
187
+ * API reference: https://learn.microsoft.com/en-us/rest/api/azure/devops/distributedtask/oidctoken/create
188
+ */
189
+ async function requestOidcToken(oidcRequestUrl, systemAccessToken) {
190
+ const { ServiceClient } = await import('@azure/core-client');
191
+ const { createHttpHeaders, createPipelineRequest } = await import('@azure/core-rest-pipeline');
192
+ const genericClient = new ServiceClient();
193
+ const request = createPipelineRequest({
194
+ url: oidcRequestUrl,
195
+ method: "POST",
196
+ headers: createHttpHeaders({
197
+ "Content-Type": "application/json",
198
+ "Authorization": `Bearer ${systemAccessToken}`
199
+ })
200
+ });
201
+ const response = await genericClient.sendRequest(request);
202
+ const body = response.bodyAsText?.toString() || "";
203
+ if (response.status !== 200) {
204
+ throw new Error(`Failed to get OIDC token:\n
205
+ Response status: ${response.status}\n
206
+ Response body: ${body}\n
207
+ Response headers: ${JSON.stringify(response.headers.toJSON())}
208
+ `);
209
+ }
210
+ else {
211
+ console.log(`Successfully got OIDC token with status ${response.status}`);
212
+ }
213
+ return JSON.parse(body).oidcToken;
214
+ }
215
+ //# sourceMappingURL=AzureDevOpsSubscriptionProvider.js.map
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Microsoft Corporation. All rights reserved.
4
+ * Licensed under the MIT License. See License.txt in the project root for license information.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.NotSignedInError = void 0;
41
+ exports.isNotSignedInError = isNotSignedInError;
42
+ const vscode = __importStar(require("vscode"));
43
+ /**
44
+ * An error indicating the user is not signed in.
45
+ */
46
+ class NotSignedInError extends Error {
47
+ isNotSignedInError = true;
48
+ constructor() {
49
+ super(vscode.l10n.t('You are not signed in to an Azure account. Please sign in.'));
50
+ }
51
+ }
52
+ exports.NotSignedInError = NotSignedInError;
53
+ /**
54
+ * Tests if an object is a `NotSignedInError`. This should be used instead of `instanceof`.
55
+ *
56
+ * @param error The object to test
57
+ *
58
+ * @returns True if the object is a NotSignedInError, false otherwise
59
+ */
60
+ function isNotSignedInError(error) {
61
+ return !!error && typeof error === 'object' && error.isNotSignedInError === true;
62
+ }
63
+ //# sourceMappingURL=NotSignedInError.js.map
@@ -0,0 +1,385 @@
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Microsoft Corporation. All rights reserved.
4
+ * Licensed under the MIT License. See License.txt in the project root for license information.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.VSCodeAzureSubscriptionProvider = void 0;
41
+ const vscode = __importStar(require("vscode"));
42
+ const getSessionFromVSCode_1 = require("./getSessionFromVSCode");
43
+ const NotSignedInError_1 = require("./NotSignedInError");
44
+ const configuredAzureEnv_1 = require("./utils/configuredAzureEnv");
45
+ const isAuthenticationWwwAuthenticateRequest_1 = require("./utils/isAuthenticationWwwAuthenticateRequest");
46
+ const isGetSubscriptionsFilter_1 = require("./utils/isGetSubscriptionsFilter");
47
+ const EventDebounce = 5 * 1000; // 5 seconds
48
+ let armSubs;
49
+ /**
50
+ * A class for obtaining Azure subscription information using VSCode's built-in authentication
51
+ * provider.
52
+ */
53
+ class VSCodeAzureSubscriptionProvider {
54
+ logger;
55
+ lastSignInEventFired = 0;
56
+ suppressSignInEvents = false;
57
+ lastSignOutEventFired = 0;
58
+ priorAccounts;
59
+ // So that customers can easily share logs, try to only log PII using trace level
60
+ constructor(logger) {
61
+ this.logger = logger;
62
+ // Load accounts initially, then onDidChangeSessions can compare against them
63
+ void vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)()).then(accounts => {
64
+ this.priorAccounts = Array.from(accounts); // The Array.from is to get rid of the readonly marker on the array returned by the API
65
+ });
66
+ }
67
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
68
+ onDidSignIn(callback, thisArg, disposables) {
69
+ return this.onDidChangeSessions(true, callback, thisArg, disposables);
70
+ }
71
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ onDidSignOut(callback, thisArg, disposables) {
73
+ return this.onDidChangeSessions(false, callback, thisArg, disposables);
74
+ }
75
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
76
+ onDidChangeSessions(signIn, callback, thisArg, disposables) {
77
+ const isASignInEvent = async () => {
78
+ const currentAccounts = Array.from(await vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)())); // The Array.from is to get rid of the readonly marker on the array returned by the API
79
+ const priorAccountCount = this.priorAccounts?.length ?? 0;
80
+ this.priorAccounts = currentAccounts;
81
+ // The only way a sign out happens is if an account is removed entirely from the list of accounts
82
+ if (currentAccounts.length === 0 || currentAccounts.length < priorAccountCount) {
83
+ return false;
84
+ }
85
+ return true;
86
+ };
87
+ const wrappedCallback = () => {
88
+ const immediate = setImmediate(() => {
89
+ clearImmediate(immediate);
90
+ void callback.call(thisArg);
91
+ });
92
+ };
93
+ const disposable = vscode.authentication.onDidChangeSessions(async (e) => {
94
+ // Ignore any sign in that isn't for the configured auth provider
95
+ if (e.provider.id !== (0, configuredAzureEnv_1.getConfiguredAuthProviderId)()) {
96
+ return;
97
+ }
98
+ if (signIn) {
99
+ if (this.suppressSignInEvents || Date.now() < this.lastSignInEventFired + EventDebounce) {
100
+ return;
101
+ }
102
+ else if (await isASignInEvent()) {
103
+ this.lastSignInEventFired = Date.now();
104
+ wrappedCallback();
105
+ }
106
+ }
107
+ else {
108
+ if (Date.now() < this.lastSignOutEventFired + EventDebounce) {
109
+ return;
110
+ }
111
+ else if (!await isASignInEvent()) {
112
+ this.lastSignOutEventFired = Date.now();
113
+ wrappedCallback();
114
+ }
115
+ }
116
+ });
117
+ disposables?.push(disposable);
118
+ return disposable;
119
+ }
120
+ dispose() {
121
+ // No-op, this class no longer has disposables
122
+ }
123
+ /**
124
+ * Gets a list of tenants available to the user.
125
+ * Use {@link isSignedIn} to check if the user is signed in to a particular tenant.
126
+ *
127
+ * @param account (Optional) A specific account to get tenants for. If not provided, all accounts will be used.
128
+ *
129
+ * @returns A list of tenants.
130
+ */
131
+ async getTenants(account) {
132
+ const startTimeMs = Date.now();
133
+ const results = [];
134
+ for await (account of account ? [account] : await vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)())) {
135
+ // Added check. Without this the getSubscriptionClient function throws the NotSignedInError
136
+ if (await this.isSignedIn(undefined, account)) {
137
+ const { client } = await this.getSubscriptionClient(account, undefined, undefined);
138
+ for await (const tenant of client.tenants.list()) {
139
+ results.push({ ...tenant, account });
140
+ }
141
+ }
142
+ }
143
+ const endTimeMs = Date.now();
144
+ this.logger?.debug(`auth: Got ${results.length} tenants for account "${account?.label}" in ${endTimeMs - startTimeMs}ms`);
145
+ return results;
146
+ }
147
+ /**
148
+ * Gets a list of Azure subscriptions available to the user.
149
+ *
150
+ * @param filter - Whether to filter the list returned. When:
151
+ * - `true`: according to the list returned by `getTenantFilters()` and `getSubscriptionFilters()`.
152
+ * - `false`: return all subscriptions.
153
+ * - `GetSubscriptionsFilter`: according to the values in the filter.
154
+ *
155
+ * Optional, default true.
156
+ *
157
+ * @returns A list of Azure subscriptions. The list is sorted by subscription name.
158
+ * The list can contain duplicate subscriptions if they come from different accounts.
159
+ *
160
+ * @throws A {@link NotSignedInError} If the user is not signed in to Azure.
161
+ * Use {@link isSignedIn} and/or {@link signIn} before this method to ensure
162
+ * the user is signed in.
163
+ */
164
+ async getSubscriptions(filter = true) {
165
+ this.logger?.debug('auth: Loading subscriptions...');
166
+ const startTime = Date.now();
167
+ let tenantIdsToFilterBy;
168
+ if ((0, isGetSubscriptionsFilter_1.isGetSubscriptionsTenantFilter)(filter)) {
169
+ // Only filter by the tenant ID option if it is provided
170
+ tenantIdsToFilterBy = [filter.tenantId];
171
+ }
172
+ else if (filter === true) {
173
+ // Only filter by the configured filter if `filter` is true AND there are tenants in the configured filter
174
+ const configuredTenantFilter = await this.getTenantFilters();
175
+ if (configuredTenantFilter.length > 0) {
176
+ tenantIdsToFilterBy = configuredTenantFilter;
177
+ }
178
+ }
179
+ const allSubscriptions = [];
180
+ let accountCount; // only used for logging
181
+ try {
182
+ this.suppressSignInEvents = true;
183
+ // Get the list of tenants from each account (filtered or all)
184
+ const accounts = (0, isGetSubscriptionsFilter_1.isGetSubscriptionsAccountFilter)(filter) ? [filter.account] : await vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)());
185
+ accountCount = accounts.length;
186
+ for (const account of accounts) {
187
+ const tenantIds = (0, isGetSubscriptionsFilter_1.isGetSubscriptionsTenantFilter)(filter) ? [filter.tenantId] : (await this.getTenants(account)).map(t => t.tenantId);
188
+ for (const tenantId of tenantIds) {
189
+ if (tenantIdsToFilterBy?.includes(tenantId) === false) {
190
+ continue;
191
+ }
192
+ // For each tenant, get the list of subscriptions
193
+ allSubscriptions.push(...await this.getSubscriptionsForTenant(account, tenantId));
194
+ }
195
+ // list subscriptions for the home tenant
196
+ allSubscriptions.push(...await this.getSubscriptionsForTenant(account));
197
+ }
198
+ }
199
+ finally {
200
+ this.suppressSignInEvents = false;
201
+ }
202
+ // It's possible that by listing subscriptions in all tenants and the "home" tenant there could be duplicate subscriptions
203
+ // Thus, we remove duplicate subscriptions. However, if multiple accounts have the same subscription, we keep them.
204
+ // There are also cases where the same subscription could appear in different tenants under the same account so we also need to keep those
205
+ const subscriptionMap = new Map();
206
+ allSubscriptions.forEach(sub => subscriptionMap.set(`${sub.account.id}/${sub.tenantId}/${sub.subscriptionId}`, sub));
207
+ const uniqueSubscriptions = Array.from(subscriptionMap.values());
208
+ const endTime = Date.now();
209
+ this.logger?.debug(`auth: Got ${uniqueSubscriptions.length} subscriptions from ${accountCount} accounts in ${endTime - startTime}ms`);
210
+ const sortSubscriptions = (subscriptions) => subscriptions.sort((a, b) => a.name.localeCompare(b.name));
211
+ const subscriptionIds = await this.getSubscriptionFilters();
212
+ if (filter === true && !!subscriptionIds.length) { // If the list is empty it is treated as "no filter"
213
+ return sortSubscriptions(uniqueSubscriptions.filter(sub => subscriptionIds.includes(sub.subscriptionId)));
214
+ }
215
+ return sortSubscriptions(uniqueSubscriptions);
216
+ }
217
+ /**
218
+ * Checks to see if a user is signed in.
219
+ *
220
+ * @param tenantId (Optional) Provide to check if a user is signed in to a specific tenant.
221
+ * @param account (Optional) Provide to check if a user is signed in to a specific account.
222
+ *
223
+ * @returns True if the user is signed in, false otherwise.
224
+ *
225
+ * If no tenant or account is provided, then
226
+ * checks all accounts for a session.
227
+ */
228
+ async isSignedIn(tenantId, account) {
229
+ async function silentlyCheckForSession(tenantId, account) {
230
+ return !!await (0, getSessionFromVSCode_1.getSessionFromVSCode)([], tenantId, { createIfNone: false, silent: true, account });
231
+ }
232
+ const innerIsSignedIn = async () => {
233
+ // If no tenant or account is provided, then check all accounts for a session
234
+ if (!account && !tenantId) {
235
+ const accounts = await vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)());
236
+ if (accounts.length === 0) {
237
+ return false;
238
+ }
239
+ for (const account of accounts) {
240
+ if (await silentlyCheckForSession(tenantId, account)) {
241
+ // If any account has a session, then return true because the user is signed in
242
+ return true;
243
+ }
244
+ }
245
+ }
246
+ return silentlyCheckForSession(tenantId, account);
247
+ };
248
+ const result = await innerIsSignedIn();
249
+ this.logger?.trace(`auth: isSignedIn returned ${result} (account="${account?.label ?? 'none'}") (tenantId="${tenantId ?? 'none'}")`);
250
+ return result;
251
+ }
252
+ /**
253
+ * Asks the user to sign in or pick an account to use.
254
+ *
255
+ * @param tenantId (Optional) Provide to sign in to a specific tenant.
256
+ * @param account (Optional) Provide to sign in to a specific account.
257
+ *
258
+ * @returns True if the user is signed in, false otherwise.
259
+ */
260
+ async signIn(tenantId, account) {
261
+ this.logger?.debug(`auth: Signing in (account="${account?.label ?? 'none'}") (tenantId="${tenantId ?? 'none'}")`);
262
+ try {
263
+ this.suppressSignInEvents = true;
264
+ const session = await (0, getSessionFromVSCode_1.getSessionFromVSCode)([], tenantId, {
265
+ createIfNone: true,
266
+ // If no account is provided, then clear the session preference which tells VS Code to show the account picker
267
+ clearSessionPreference: !account,
268
+ account,
269
+ });
270
+ return !!session;
271
+ }
272
+ finally {
273
+ this.suppressSignInEvents = false;
274
+ }
275
+ }
276
+ /**
277
+ * Signs the user out
278
+ *
279
+ * @deprecated Not currently supported by VS Code auth providers
280
+ */
281
+ signOut() {
282
+ throw new Error(vscode.l10n.t('Signing out programmatically is not supported. You must sign out by selecting the account in the Accounts menu and choosing Sign Out.'));
283
+ }
284
+ /**
285
+ * Gets the tenant filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
286
+ * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
287
+ * and/or `getTenantFilters()` overridden.
288
+ *
289
+ * If no values are returned by `getTenantFilters()`, then all tenants will be scanned for subscriptions.
290
+ *
291
+ * @returns A list of tenant IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
292
+ */
293
+ async getTenantFilters() {
294
+ const config = vscode.workspace.getConfiguration('azureResourceGroups');
295
+ const fullSubscriptionIds = config.get('selectedSubscriptions', []);
296
+ return fullSubscriptionIds.map(id => id.split('/')[0]);
297
+ }
298
+ /**
299
+ * Gets the subscription filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
300
+ * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
301
+ * and/or `getTenantFilters()` overridden.
302
+ *
303
+ * If no values are returned by `getSubscriptionFilters()`, then all subscriptions will be returned.
304
+ *
305
+ * @returns A list of subscription IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
306
+ */
307
+ async getSubscriptionFilters() {
308
+ const config = vscode.workspace.getConfiguration('azureResourceGroups');
309
+ const fullSubscriptionIds = config.get('selectedSubscriptions', []);
310
+ return fullSubscriptionIds.map(id => id.split('/')[1]);
311
+ }
312
+ /**
313
+ * Gets the subscriptions for a given tenant.
314
+ *
315
+ * @param tenantId The tenant ID to get subscriptions for.
316
+ * @param account The account to get the subscriptions for.
317
+ *
318
+ * @returns The list of subscriptions for the tenant.
319
+ */
320
+ async getSubscriptionsForTenant(account, tenantId) {
321
+ // If the user is not signed in to this tenant or account, then return an empty list
322
+ // This is to prevent the NotSignedInError from being thrown in getSubscriptionClient
323
+ if (!await this.isSignedIn(tenantId, account)) {
324
+ return [];
325
+ }
326
+ const { client, credential, authentication } = await this.getSubscriptionClient(account, tenantId, undefined);
327
+ const environment = (0, configuredAzureEnv_1.getConfiguredAzureEnv)();
328
+ const subscriptions = [];
329
+ for await (const subscription of client.subscriptions.list()) {
330
+ subscriptions.push({
331
+ authentication: authentication,
332
+ environment: environment,
333
+ credential: credential,
334
+ isCustomCloud: environment.isCustomCloud,
335
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
336
+ name: subscription.displayName,
337
+ subscriptionId: subscription.subscriptionId,
338
+ tenantId: tenantId ?? subscription.tenantId,
339
+ /* eslint-enable @typescript-eslint/no-non-null-assertion */
340
+ account: account
341
+ });
342
+ }
343
+ return subscriptions;
344
+ }
345
+ /**
346
+ * Gets a fully-configured subscription client for a given tenant ID
347
+ *
348
+ * @param tenantId (Optional) The tenant ID to get a client for
349
+ * @param account The account that you would like to get the session for
350
+ *
351
+ * @returns A client, the credential used by the client, and the authentication function
352
+ */
353
+ async getSubscriptionClient(account, tenantId, scopes) {
354
+ armSubs ||= await import('@azure/arm-resources-subscriptions');
355
+ const session = await (0, getSessionFromVSCode_1.getSessionFromVSCode)(scopes, tenantId, { createIfNone: false, silent: true, account });
356
+ if (!session) {
357
+ throw new NotSignedInError_1.NotSignedInError();
358
+ }
359
+ const credential = {
360
+ getToken: async () => {
361
+ return {
362
+ token: session.accessToken,
363
+ expiresOnTimestamp: 0
364
+ };
365
+ }
366
+ };
367
+ const configuredAzureEnv = (0, configuredAzureEnv_1.getConfiguredAzureEnv)();
368
+ const endpoint = configuredAzureEnv.resourceManagerEndpointUrl;
369
+ return {
370
+ client: new armSubs.SubscriptionClient(credential, { endpoint }),
371
+ credential: credential,
372
+ authentication: {
373
+ getSession: () => session,
374
+ getSessionWithScopes: (scopeListOrRequest) => {
375
+ // in order to handle a challenge, we must enable createIfNone so
376
+ // that we can prompt the user to step-up their session with MFA
377
+ // otherwise, never prompt the user
378
+ return (0, getSessionFromVSCode_1.getSessionFromVSCode)(scopeListOrRequest, tenantId, { ...((0, isAuthenticationWwwAuthenticateRequest_1.isAuthenticationWwwAuthenticateRequest)(scopeListOrRequest) ? { createIfNone: true } : { silent: true }), account });
379
+ },
380
+ }
381
+ };
382
+ }
383
+ }
384
+ exports.VSCodeAzureSubscriptionProvider = VSCodeAzureSubscriptionProvider;
385
+ //# sourceMappingURL=VSCodeAzureSubscriptionProvider.js.map