@microsoft/vscode-azext-azureauth 4.0.3 → 4.1.1

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.
@@ -1,387 +1,395 @@
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
- return new (P || (P = Promise))(function (resolve, reject) {
9
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
- step((generator = generator.apply(thisArg, _arguments || [])).next());
13
- });
14
- };
15
- var __asyncValues = (this && this.__asyncValues) || function (o) {
16
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
17
- var m = o[Symbol.asyncIterator], i;
18
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
19
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
20
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
21
- };
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.VSCodeAzureSubscriptionProvider = void 0;
24
- const vscode = require("vscode");
25
- const getSessionFromVSCode_1 = require("./getSessionFromVSCode");
26
- const NotSignedInError_1 = require("./NotSignedInError");
27
- const configuredAzureEnv_1 = require("./utils/configuredAzureEnv");
28
- const EventDebounce = 5 * 1000; // 5 seconds
29
- /**
30
- * A class for obtaining Azure subscription information using VSCode's built-in authentication
31
- * provider.
32
- */
33
- class VSCodeAzureSubscriptionProvider extends vscode.Disposable {
34
- // So that customers can easily share logs, try to only log PII using trace level
35
- constructor(logger) {
36
- const disposable = vscode.authentication.onDidChangeSessions((e) => __awaiter(this, void 0, void 0, function* () {
37
- // Ignore any sign in that isn't for the configured auth provider
38
- if (e.provider.id !== (0, configuredAzureEnv_1.getConfiguredAuthProviderId)()) {
39
- return;
40
- }
41
- if (yield this.isSignedIn()) {
42
- if (!this.suppressSignInEvents && Date.now() > this.lastSignInEventFired + EventDebounce) {
43
- this.lastSignInEventFired = Date.now();
44
- this.onDidSignInEmitter.fire();
45
- }
46
- }
47
- else if (Date.now() > this.lastSignOutEventFired + EventDebounce) {
48
- this.lastSignOutEventFired = Date.now();
49
- this.onDidSignOutEmitter.fire();
50
- }
51
- }));
52
- super(() => {
53
- this.onDidSignInEmitter.dispose();
54
- this.onDidSignOutEmitter.dispose();
55
- disposable.dispose();
56
- });
57
- this.logger = logger;
58
- this.onDidSignInEmitter = new vscode.EventEmitter();
59
- this.lastSignInEventFired = 0;
60
- this.suppressSignInEvents = false;
61
- this.onDidSignOutEmitter = new vscode.EventEmitter();
62
- this.lastSignOutEventFired = 0;
63
- /**
64
- * An event that is fired when the user signs in. Debounced to fire at most once every 5 seconds.
65
- */
66
- this.onDidSignIn = this.onDidSignInEmitter.event;
67
- /**
68
- * An event that is fired when the user signs out. Debounced to fire at most once every 5 seconds.
69
- */
70
- this.onDidSignOut = this.onDidSignOutEmitter.event;
71
- }
72
- /**
73
- * Gets a list of tenants available to the user.
74
- * Use {@link isSignedIn} to check if the user is signed in to a particular tenant.
75
- *
76
- * @param account (Optional) A specific account to get tenants for. If not provided, all accounts will be used.
77
- *
78
- * @returns A list of tenants.
79
- */
80
- getTenants(account) {
81
- var _a, e_1, _b, _c, _d, e_2, _e, _f;
82
- var _g;
83
- return __awaiter(this, void 0, void 0, function* () {
84
- const startTimeMs = Date.now();
85
- const results = [];
86
- try {
87
- for (var _h = true, _j = __asyncValues(account ? [account] : yield vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)())), _k; _k = yield _j.next(), _a = _k.done, !_a;) {
88
- _c = _k.value;
89
- _h = false;
90
- try {
91
- account = _c;
92
- // Added check. Without this the getSubscriptionClient function throws the NotSignedInError
93
- if (yield this.isSignedIn(undefined, account)) {
94
- const { client } = yield this.getSubscriptionClient(account, undefined, undefined);
95
- try {
96
- for (var _l = true, _m = (e_2 = void 0, __asyncValues(client.tenants.list())), _o; _o = yield _m.next(), _d = _o.done, !_d;) {
97
- _f = _o.value;
98
- _l = false;
99
- try {
100
- const tenant = _f;
101
- results.push(Object.assign(Object.assign({}, tenant), { account }));
102
- }
103
- finally {
104
- _l = true;
105
- }
106
- }
107
- }
108
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
109
- finally {
110
- try {
111
- if (!_l && !_d && (_e = _m.return)) yield _e.call(_m);
112
- }
113
- finally { if (e_2) throw e_2.error; }
114
- }
115
- }
116
- }
117
- finally {
118
- _h = true;
119
- }
120
- }
121
- }
122
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
123
- finally {
124
- try {
125
- if (!_h && !_a && (_b = _j.return)) yield _b.call(_j);
126
- }
127
- finally { if (e_1) throw e_1.error; }
128
- }
129
- const endTimeMs = Date.now();
130
- (_g = this.logger) === null || _g === void 0 ? void 0 : _g.debug(`auth: Got ${results.length} tenants for account "${account === null || account === void 0 ? void 0 : account.label}" in ${endTimeMs - startTimeMs}ms`);
131
- return results;
132
- });
133
- }
134
- /**
135
- * Gets a list of Azure subscriptions available to the user.
136
- *
137
- * @param filter - Whether to filter the list returned, according to the list returned
138
- * by `getTenantFilters()` and `getSubscriptionFilters()`. Optional, default true.
139
- *
140
- * @returns A list of Azure subscriptions. The list is sorted by subscription name.
141
- * The list can contain duplicate subscriptions if they come from different accounts.
142
- *
143
- * @throws A {@link NotSignedInError} If the user is not signed in to Azure.
144
- * Use {@link isSignedIn} and/or {@link signIn} before this method to ensure
145
- * the user is signed in.
146
- */
147
- getSubscriptions(filter = true) {
148
- var _a, _b;
149
- return __awaiter(this, void 0, void 0, function* () {
150
- (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug('auth: Loading subscriptions...');
151
- const startTime = Date.now();
152
- const tenantIds = yield this.getTenantFilters();
153
- const shouldFilterTenants = filter && !!tenantIds.length; // If the list is empty it is treated as "no filter"
154
- const allSubscriptions = [];
155
- let accountCount; // only used for logging
156
- try {
157
- this.suppressSignInEvents = true;
158
- // Get the list of tenants from each account
159
- const accounts = yield vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)());
160
- accountCount = accounts.length;
161
- for (const account of accounts) {
162
- for (const tenant of yield this.getTenants(account)) {
163
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
164
- const tenantId = tenant.tenantId;
165
- // If filtering is enabled, and the current tenant is not in that list, then skip it
166
- if (shouldFilterTenants && !tenantIds.includes(tenantId)) {
167
- continue;
168
- }
169
- // For each tenant, get the list of subscriptions
170
- allSubscriptions.push(...yield this.getSubscriptionsForTenant(account, tenantId));
171
- }
172
- // list subscriptions for the home tenant
173
- allSubscriptions.push(...yield this.getSubscriptionsForTenant(account));
174
- }
175
- }
176
- finally {
177
- this.suppressSignInEvents = false;
178
- }
179
- // It's possible that by listing subscriptions in all tenants and the "home" tenant there could be duplicate subscriptions
180
- // Thus, we remove duplicate subscriptions. However, if multiple accounts have the same subscription, we keep them.
181
- const subscriptionMap = new Map();
182
- allSubscriptions.forEach(sub => subscriptionMap.set(`${sub.account.id}/${sub.subscriptionId}`, sub));
183
- const uniqueSubscriptions = Array.from(subscriptionMap.values());
184
- const endTime = Date.now();
185
- (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(`auth: Got ${uniqueSubscriptions.length} subscriptions from ${accountCount} accounts in ${endTime - startTime}ms`);
186
- const sortSubscriptions = (subscriptions) => subscriptions.sort((a, b) => a.name.localeCompare(b.name));
187
- const subscriptionIds = yield this.getSubscriptionFilters();
188
- if (filter && !!subscriptionIds.length) { // If the list is empty it is treated as "no filter"
189
- return sortSubscriptions(uniqueSubscriptions.filter(sub => subscriptionIds.includes(sub.subscriptionId)));
190
- }
191
- return sortSubscriptions(uniqueSubscriptions);
192
- });
193
- }
194
- /**
195
- * Checks to see if a user is signed in.
196
- *
197
- * @param tenantId (Optional) Provide to check if a user is signed in to a specific tenant.
198
- * @param account (Optional) Provide to check if a user is signed in to a specific account.
199
- *
200
- * @returns True if the user is signed in, false otherwise.
201
- *
202
- * If no tenant or account is provided, then
203
- * checks all accounts for a session.
204
- */
205
- isSignedIn(tenantId, account) {
206
- var _a, _b;
207
- return __awaiter(this, void 0, void 0, function* () {
208
- function silentlyCheckForSession(tenantId, account) {
209
- return __awaiter(this, void 0, void 0, function* () {
210
- return !!(yield (0, getSessionFromVSCode_1.getSessionFromVSCode)([], tenantId, { createIfNone: false, silent: true, account }));
211
- });
212
- }
213
- const innerIsSignedIn = () => __awaiter(this, void 0, void 0, function* () {
214
- // If no tenant or account is provided, then check all accounts for a session
215
- if (!account && !tenantId) {
216
- const accounts = yield vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)());
217
- if (accounts.length === 0) {
218
- return false;
219
- }
220
- for (const account of accounts) {
221
- if (yield silentlyCheckForSession(tenantId, account)) {
222
- // If any account has a session, then return true because the user is signed in
223
- return true;
224
- }
225
- }
226
- }
227
- return silentlyCheckForSession(tenantId, account);
228
- });
229
- const result = yield innerIsSignedIn();
230
- (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`auth: isSignedIn returned ${result} (account="${(_b = account === null || account === void 0 ? void 0 : account.label) !== null && _b !== void 0 ? _b : 'none'}") (tenantId="${tenantId !== null && tenantId !== void 0 ? tenantId : 'none'}")`);
231
- return result;
232
- });
233
- }
234
- /**
235
- * Asks the user to sign in or pick an account to use.
236
- *
237
- * @param tenantId (Optional) Provide to sign in to a specific tenant.
238
- * @param account (Optional) Provide to sign in to a specific account.
239
- *
240
- * @returns True if the user is signed in, false otherwise.
241
- */
242
- signIn(tenantId, account) {
243
- var _a, _b;
244
- return __awaiter(this, void 0, void 0, function* () {
245
- (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`auth: Signing in (account="${(_b = account === null || account === void 0 ? void 0 : account.label) !== null && _b !== void 0 ? _b : 'none'}") (tenantId="${tenantId !== null && tenantId !== void 0 ? tenantId : 'none'}")`);
246
- const session = yield (0, getSessionFromVSCode_1.getSessionFromVSCode)([], tenantId, {
247
- createIfNone: true,
248
- // If no account is provided, then clear the session preference which tells VS Code to show the account picker
249
- clearSessionPreference: !account,
250
- account,
251
- });
252
- return !!session;
253
- });
254
- }
255
- /**
256
- * Signs the user out
257
- *
258
- * @deprecated Not currently supported by VS Code auth providers
259
- */
260
- signOut() {
261
- 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.'));
262
- }
263
- /**
264
- * Gets the tenant filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
265
- * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
266
- * and/or `getTenantFilters()` overridden.
267
- *
268
- * If no values are returned by `getTenantFilters()`, then all tenants will be scanned for subscriptions.
269
- *
270
- * @returns A list of tenant IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
271
- */
272
- getTenantFilters() {
273
- return __awaiter(this, void 0, void 0, function* () {
274
- const config = vscode.workspace.getConfiguration('azureResourceGroups');
275
- const fullSubscriptionIds = config.get('selectedSubscriptions', []);
276
- return fullSubscriptionIds.map(id => id.split('/')[0]);
277
- });
278
- }
279
- /**
280
- * Gets the subscription filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
281
- * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
282
- * and/or `getTenantFilters()` overridden.
283
- *
284
- * If no values are returned by `getSubscriptionFilters()`, then all subscriptions will be returned.
285
- *
286
- * @returns A list of subscription IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
287
- */
288
- getSubscriptionFilters() {
289
- return __awaiter(this, void 0, void 0, function* () {
290
- const config = vscode.workspace.getConfiguration('azureResourceGroups');
291
- const fullSubscriptionIds = config.get('selectedSubscriptions', []);
292
- return fullSubscriptionIds.map(id => id.split('/')[1]);
293
- });
294
- }
295
- /**
296
- * Gets the subscriptions for a given tenant.
297
- *
298
- * @param tenantId The tenant ID to get subscriptions for.
299
- * @param account The account to get the subscriptions for.
300
- *
301
- * @returns The list of subscriptions for the tenant.
302
- */
303
- getSubscriptionsForTenant(account, tenantId) {
304
- var _a, e_3, _b, _c;
305
- return __awaiter(this, void 0, void 0, function* () {
306
- // If the user is not signed in to this tenant or account, then return an empty list
307
- // This is to prevent the NotSignedInError from being thrown in getSubscriptionClient
308
- if (!(yield this.isSignedIn(tenantId, account))) {
309
- return [];
310
- }
311
- const { client, credential, authentication } = yield this.getSubscriptionClient(account, tenantId, undefined);
312
- const environment = (0, configuredAzureEnv_1.getConfiguredAzureEnv)();
313
- const subscriptions = [];
314
- try {
315
- for (var _d = true, _e = __asyncValues(client.subscriptions.list()), _f; _f = yield _e.next(), _a = _f.done, !_a;) {
316
- _c = _f.value;
317
- _d = false;
318
- try {
319
- const subscription = _c;
320
- subscriptions.push({
321
- authentication: authentication,
322
- environment: environment,
323
- credential: credential,
324
- isCustomCloud: environment.isCustomCloud,
325
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
326
- name: subscription.displayName,
327
- subscriptionId: subscription.subscriptionId,
328
- tenantId: tenantId !== null && tenantId !== void 0 ? tenantId : subscription.tenantId,
329
- /* eslint-enable @typescript-eslint/no-non-null-assertion */
330
- account: account
331
- });
332
- }
333
- finally {
334
- _d = true;
335
- }
336
- }
337
- }
338
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
339
- finally {
340
- try {
341
- if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
342
- }
343
- finally { if (e_3) throw e_3.error; }
344
- }
345
- return subscriptions;
346
- });
347
- }
348
- /**
349
- * Gets a fully-configured subscription client for a given tenant ID
350
- *
351
- * @param tenantId (Optional) The tenant ID to get a client for
352
- * @param account The account that you would like to get the session for
353
- *
354
- * @returns A client, the credential used by the client, and the authentication function
355
- */
356
- getSubscriptionClient(account, tenantId, scopes) {
357
- return __awaiter(this, void 0, void 0, function* () {
358
- const armSubs = yield Promise.resolve().then(() => require('@azure/arm-resources-subscriptions'));
359
- const session = yield (0, getSessionFromVSCode_1.getSessionFromVSCode)(scopes, tenantId, { createIfNone: false, silent: true, account });
360
- if (!session) {
361
- throw new NotSignedInError_1.NotSignedInError();
362
- }
363
- const credential = {
364
- getToken: () => __awaiter(this, void 0, void 0, function* () {
365
- return {
366
- token: session.accessToken,
367
- expiresOnTimestamp: 0
368
- };
369
- })
370
- };
371
- const configuredAzureEnv = (0, configuredAzureEnv_1.getConfiguredAzureEnv)();
372
- const endpoint = configuredAzureEnv.resourceManagerEndpointUrl;
373
- return {
374
- client: new armSubs.SubscriptionClient(credential, { endpoint }),
375
- credential: credential,
376
- authentication: {
377
- getSession: () => session,
378
- getSessionWithScopes: (scopes) => {
379
- return (0, getSessionFromVSCode_1.getSessionFromVSCode)(scopes, tenantId, { createIfNone: false, silent: true, account });
380
- },
381
- }
382
- };
383
- });
384
- }
385
- }
386
- exports.VSCodeAzureSubscriptionProvider = VSCodeAzureSubscriptionProvider;
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
16
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
17
+ var m = o[Symbol.asyncIterator], i;
18
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
19
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
20
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.VSCodeAzureSubscriptionProvider = void 0;
24
+ const vscode = require("vscode");
25
+ const getSessionFromVSCode_1 = require("./getSessionFromVSCode");
26
+ const NotSignedInError_1 = require("./NotSignedInError");
27
+ const configuredAzureEnv_1 = require("./utils/configuredAzureEnv");
28
+ const EventDebounce = 5 * 1000; // 5 seconds
29
+ /**
30
+ * A class for obtaining Azure subscription information using VSCode's built-in authentication
31
+ * provider.
32
+ */
33
+ class VSCodeAzureSubscriptionProvider extends vscode.Disposable {
34
+ // So that customers can easily share logs, try to only log PII using trace level
35
+ constructor(logger) {
36
+ const disposable = vscode.authentication.onDidChangeSessions((e) => __awaiter(this, void 0, void 0, function* () {
37
+ // Ignore any sign in that isn't for the configured auth provider
38
+ if (e.provider.id !== (0, configuredAzureEnv_1.getConfiguredAuthProviderId)()) {
39
+ return;
40
+ }
41
+ if (yield this.isSignedIn()) {
42
+ if (!this.suppressSignInEvents && Date.now() > this.lastSignInEventFired + EventDebounce) {
43
+ this.lastSignInEventFired = Date.now();
44
+ this.onDidSignInEmitter.fire();
45
+ }
46
+ }
47
+ else if (Date.now() > this.lastSignOutEventFired + EventDebounce) {
48
+ this.lastSignOutEventFired = Date.now();
49
+ this.onDidSignOutEmitter.fire();
50
+ }
51
+ }));
52
+ super(() => {
53
+ this.onDidSignInEmitter.dispose();
54
+ this.onDidSignOutEmitter.dispose();
55
+ disposable.dispose();
56
+ });
57
+ this.logger = logger;
58
+ this.onDidSignInEmitter = new vscode.EventEmitter();
59
+ this.lastSignInEventFired = 0;
60
+ this.suppressSignInEvents = false;
61
+ this.onDidSignOutEmitter = new vscode.EventEmitter();
62
+ this.lastSignOutEventFired = 0;
63
+ /**
64
+ * An event that is fired when the user signs in. Debounced to fire at most once every 5 seconds.
65
+ */
66
+ this.onDidSignIn = this.onDidSignInEmitter.event;
67
+ /**
68
+ * An event that is fired when the user signs out. Debounced to fire at most once every 5 seconds.
69
+ */
70
+ this.onDidSignOut = this.onDidSignOutEmitter.event;
71
+ }
72
+ /**
73
+ * Gets a list of tenants available to the user.
74
+ * Use {@link isSignedIn} to check if the user is signed in to a particular tenant.
75
+ *
76
+ * @param account (Optional) A specific account to get tenants for. If not provided, all accounts will be used.
77
+ *
78
+ * @returns A list of tenants.
79
+ */
80
+ getTenants(account) {
81
+ var _a, e_1, _b, _c, _d, e_2, _e, _f;
82
+ var _g;
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ const startTimeMs = Date.now();
85
+ const results = [];
86
+ try {
87
+ for (var _h = true, _j = __asyncValues(account ? [account] : yield vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)())), _k; _k = yield _j.next(), _a = _k.done, !_a;) {
88
+ _c = _k.value;
89
+ _h = false;
90
+ try {
91
+ account = _c;
92
+ // Added check. Without this the getSubscriptionClient function throws the NotSignedInError
93
+ if (yield this.isSignedIn(undefined, account)) {
94
+ const { client } = yield this.getSubscriptionClient(account, undefined, undefined);
95
+ try {
96
+ for (var _l = true, _m = (e_2 = void 0, __asyncValues(client.tenants.list())), _o; _o = yield _m.next(), _d = _o.done, !_d;) {
97
+ _f = _o.value;
98
+ _l = false;
99
+ try {
100
+ const tenant = _f;
101
+ results.push(Object.assign(Object.assign({}, tenant), { account }));
102
+ }
103
+ finally {
104
+ _l = true;
105
+ }
106
+ }
107
+ }
108
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
109
+ finally {
110
+ try {
111
+ if (!_l && !_d && (_e = _m.return)) yield _e.call(_m);
112
+ }
113
+ finally { if (e_2) throw e_2.error; }
114
+ }
115
+ }
116
+ }
117
+ finally {
118
+ _h = true;
119
+ }
120
+ }
121
+ }
122
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
123
+ finally {
124
+ try {
125
+ if (!_h && !_a && (_b = _j.return)) yield _b.call(_j);
126
+ }
127
+ finally { if (e_1) throw e_1.error; }
128
+ }
129
+ const endTimeMs = Date.now();
130
+ (_g = this.logger) === null || _g === void 0 ? void 0 : _g.debug(`auth: Got ${results.length} tenants for account "${account === null || account === void 0 ? void 0 : account.label}" in ${endTimeMs - startTimeMs}ms`);
131
+ return results;
132
+ });
133
+ }
134
+ /**
135
+ * Gets a list of Azure subscriptions available to the user.
136
+ *
137
+ * @param filter - Whether to filter the list returned. When:
138
+ * - `true`: according to the list returned by `getTenantFilters()` and `getSubscriptionFilters()`.
139
+ * - `false`: return all subscriptions.
140
+ * - `GetSubscriptionsFilter`: according to the values in the filter.
141
+ *
142
+ * Optional, default true.
143
+ *
144
+ * @returns A list of Azure subscriptions. The list is sorted by subscription name.
145
+ * The list can contain duplicate subscriptions if they come from different accounts.
146
+ *
147
+ * @throws A {@link NotSignedInError} If the user is not signed in to Azure.
148
+ * Use {@link isSignedIn} and/or {@link signIn} before this method to ensure
149
+ * the user is signed in.
150
+ */
151
+ getSubscriptions(filter = true) {
152
+ var _a, _b;
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug('auth: Loading subscriptions...');
155
+ const startTime = Date.now();
156
+ const configuredTenantFilter = yield this.getTenantFilters();
157
+ const tenantIdsToFilterBy =
158
+ // Only filter by the tenant ID option if it is provided
159
+ (typeof filter === 'object' && filter.tenantId ? [filter.tenantId] :
160
+ // Only filter by the configured filter if `filter` is true AND there are tenants in the configured filter
161
+ filter === true && configuredTenantFilter.length > 0 ? configuredTenantFilter :
162
+ undefined);
163
+ const allSubscriptions = [];
164
+ let accountCount; // only used for logging
165
+ try {
166
+ this.suppressSignInEvents = true;
167
+ // Get the list of tenants from each account (filtered or all)
168
+ const accounts = typeof filter === 'object' && filter.account ? [filter.account] : yield vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)());
169
+ accountCount = accounts.length;
170
+ for (const account of accounts) {
171
+ for (const tenant of yield this.getTenants(account)) {
172
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
173
+ const tenantId = tenant.tenantId;
174
+ if ((tenantIdsToFilterBy === null || tenantIdsToFilterBy === void 0 ? void 0 : tenantIdsToFilterBy.includes(tenantId)) === false) {
175
+ continue;
176
+ }
177
+ // For each tenant, get the list of subscriptions
178
+ allSubscriptions.push(...yield this.getSubscriptionsForTenant(account, tenantId));
179
+ }
180
+ // list subscriptions for the home tenant
181
+ allSubscriptions.push(...yield this.getSubscriptionsForTenant(account));
182
+ }
183
+ }
184
+ finally {
185
+ this.suppressSignInEvents = false;
186
+ }
187
+ // It's possible that by listing subscriptions in all tenants and the "home" tenant there could be duplicate subscriptions
188
+ // Thus, we remove duplicate subscriptions. However, if multiple accounts have the same subscription, we keep them.
189
+ const subscriptionMap = new Map();
190
+ allSubscriptions.forEach(sub => subscriptionMap.set(`${sub.account.id}/${sub.subscriptionId}`, sub));
191
+ const uniqueSubscriptions = Array.from(subscriptionMap.values());
192
+ const endTime = Date.now();
193
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(`auth: Got ${uniqueSubscriptions.length} subscriptions from ${accountCount} accounts in ${endTime - startTime}ms`);
194
+ const sortSubscriptions = (subscriptions) => subscriptions.sort((a, b) => a.name.localeCompare(b.name));
195
+ const subscriptionIds = yield this.getSubscriptionFilters();
196
+ if (filter === true && !!subscriptionIds.length) { // If the list is empty it is treated as "no filter"
197
+ return sortSubscriptions(uniqueSubscriptions.filter(sub => subscriptionIds.includes(sub.subscriptionId)));
198
+ }
199
+ return sortSubscriptions(uniqueSubscriptions);
200
+ });
201
+ }
202
+ /**
203
+ * Checks to see if a user is signed in.
204
+ *
205
+ * @param tenantId (Optional) Provide to check if a user is signed in to a specific tenant.
206
+ * @param account (Optional) Provide to check if a user is signed in to a specific account.
207
+ *
208
+ * @returns True if the user is signed in, false otherwise.
209
+ *
210
+ * If no tenant or account is provided, then
211
+ * checks all accounts for a session.
212
+ */
213
+ isSignedIn(tenantId, account) {
214
+ var _a, _b;
215
+ return __awaiter(this, void 0, void 0, function* () {
216
+ function silentlyCheckForSession(tenantId, account) {
217
+ return __awaiter(this, void 0, void 0, function* () {
218
+ return !!(yield (0, getSessionFromVSCode_1.getSessionFromVSCode)([], tenantId, { createIfNone: false, silent: true, account }));
219
+ });
220
+ }
221
+ const innerIsSignedIn = () => __awaiter(this, void 0, void 0, function* () {
222
+ // If no tenant or account is provided, then check all accounts for a session
223
+ if (!account && !tenantId) {
224
+ const accounts = yield vscode.authentication.getAccounts((0, configuredAzureEnv_1.getConfiguredAuthProviderId)());
225
+ if (accounts.length === 0) {
226
+ return false;
227
+ }
228
+ for (const account of accounts) {
229
+ if (yield silentlyCheckForSession(tenantId, account)) {
230
+ // If any account has a session, then return true because the user is signed in
231
+ return true;
232
+ }
233
+ }
234
+ }
235
+ return silentlyCheckForSession(tenantId, account);
236
+ });
237
+ const result = yield innerIsSignedIn();
238
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`auth: isSignedIn returned ${result} (account="${(_b = account === null || account === void 0 ? void 0 : account.label) !== null && _b !== void 0 ? _b : 'none'}") (tenantId="${tenantId !== null && tenantId !== void 0 ? tenantId : 'none'}")`);
239
+ return result;
240
+ });
241
+ }
242
+ /**
243
+ * Asks the user to sign in or pick an account to use.
244
+ *
245
+ * @param tenantId (Optional) Provide to sign in to a specific tenant.
246
+ * @param account (Optional) Provide to sign in to a specific account.
247
+ *
248
+ * @returns True if the user is signed in, false otherwise.
249
+ */
250
+ signIn(tenantId, account) {
251
+ var _a, _b;
252
+ return __awaiter(this, void 0, void 0, function* () {
253
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`auth: Signing in (account="${(_b = account === null || account === void 0 ? void 0 : account.label) !== null && _b !== void 0 ? _b : 'none'}") (tenantId="${tenantId !== null && tenantId !== void 0 ? tenantId : 'none'}")`);
254
+ const session = yield (0, getSessionFromVSCode_1.getSessionFromVSCode)([], tenantId, {
255
+ createIfNone: true,
256
+ // If no account is provided, then clear the session preference which tells VS Code to show the account picker
257
+ clearSessionPreference: !account,
258
+ account,
259
+ });
260
+ return !!session;
261
+ });
262
+ }
263
+ /**
264
+ * Signs the user out
265
+ *
266
+ * @deprecated Not currently supported by VS Code auth providers
267
+ */
268
+ signOut() {
269
+ 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.'));
270
+ }
271
+ /**
272
+ * Gets the tenant filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
273
+ * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
274
+ * and/or `getTenantFilters()` overridden.
275
+ *
276
+ * If no values are returned by `getTenantFilters()`, then all tenants will be scanned for subscriptions.
277
+ *
278
+ * @returns A list of tenant IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
279
+ */
280
+ getTenantFilters() {
281
+ return __awaiter(this, void 0, void 0, function* () {
282
+ const config = vscode.workspace.getConfiguration('azureResourceGroups');
283
+ const fullSubscriptionIds = config.get('selectedSubscriptions', []);
284
+ return fullSubscriptionIds.map(id => id.split('/')[0]);
285
+ });
286
+ }
287
+ /**
288
+ * Gets the subscription filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
289
+ * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
290
+ * and/or `getTenantFilters()` overridden.
291
+ *
292
+ * If no values are returned by `getSubscriptionFilters()`, then all subscriptions will be returned.
293
+ *
294
+ * @returns A list of subscription IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
295
+ */
296
+ getSubscriptionFilters() {
297
+ return __awaiter(this, void 0, void 0, function* () {
298
+ const config = vscode.workspace.getConfiguration('azureResourceGroups');
299
+ const fullSubscriptionIds = config.get('selectedSubscriptions', []);
300
+ return fullSubscriptionIds.map(id => id.split('/')[1]);
301
+ });
302
+ }
303
+ /**
304
+ * Gets the subscriptions for a given tenant.
305
+ *
306
+ * @param tenantId The tenant ID to get subscriptions for.
307
+ * @param account The account to get the subscriptions for.
308
+ *
309
+ * @returns The list of subscriptions for the tenant.
310
+ */
311
+ getSubscriptionsForTenant(account, tenantId) {
312
+ var _a, e_3, _b, _c;
313
+ return __awaiter(this, void 0, void 0, function* () {
314
+ // If the user is not signed in to this tenant or account, then return an empty list
315
+ // This is to prevent the NotSignedInError from being thrown in getSubscriptionClient
316
+ if (!(yield this.isSignedIn(tenantId, account))) {
317
+ return [];
318
+ }
319
+ const { client, credential, authentication } = yield this.getSubscriptionClient(account, tenantId, undefined);
320
+ const environment = (0, configuredAzureEnv_1.getConfiguredAzureEnv)();
321
+ const subscriptions = [];
322
+ try {
323
+ for (var _d = true, _e = __asyncValues(client.subscriptions.list()), _f; _f = yield _e.next(), _a = _f.done, !_a;) {
324
+ _c = _f.value;
325
+ _d = false;
326
+ try {
327
+ const subscription = _c;
328
+ subscriptions.push({
329
+ authentication: authentication,
330
+ environment: environment,
331
+ credential: credential,
332
+ isCustomCloud: environment.isCustomCloud,
333
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
334
+ name: subscription.displayName,
335
+ subscriptionId: subscription.subscriptionId,
336
+ tenantId: tenantId !== null && tenantId !== void 0 ? tenantId : subscription.tenantId,
337
+ /* eslint-enable @typescript-eslint/no-non-null-assertion */
338
+ account: account
339
+ });
340
+ }
341
+ finally {
342
+ _d = true;
343
+ }
344
+ }
345
+ }
346
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
347
+ finally {
348
+ try {
349
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
350
+ }
351
+ finally { if (e_3) throw e_3.error; }
352
+ }
353
+ return subscriptions;
354
+ });
355
+ }
356
+ /**
357
+ * Gets a fully-configured subscription client for a given tenant ID
358
+ *
359
+ * @param tenantId (Optional) The tenant ID to get a client for
360
+ * @param account The account that you would like to get the session for
361
+ *
362
+ * @returns A client, the credential used by the client, and the authentication function
363
+ */
364
+ getSubscriptionClient(account, tenantId, scopes) {
365
+ return __awaiter(this, void 0, void 0, function* () {
366
+ const armSubs = yield Promise.resolve().then(() => require('@azure/arm-resources-subscriptions'));
367
+ const session = yield (0, getSessionFromVSCode_1.getSessionFromVSCode)(scopes, tenantId, { createIfNone: false, silent: true, account });
368
+ if (!session) {
369
+ throw new NotSignedInError_1.NotSignedInError();
370
+ }
371
+ const credential = {
372
+ getToken: () => __awaiter(this, void 0, void 0, function* () {
373
+ return {
374
+ token: session.accessToken,
375
+ expiresOnTimestamp: 0
376
+ };
377
+ })
378
+ };
379
+ const configuredAzureEnv = (0, configuredAzureEnv_1.getConfiguredAzureEnv)();
380
+ const endpoint = configuredAzureEnv.resourceManagerEndpointUrl;
381
+ return {
382
+ client: new armSubs.SubscriptionClient(credential, { endpoint }),
383
+ credential: credential,
384
+ authentication: {
385
+ getSession: () => session,
386
+ getSessionWithScopes: (scopes) => {
387
+ return (0, getSessionFromVSCode_1.getSessionFromVSCode)(scopes, tenantId, { createIfNone: false, silent: true, account });
388
+ },
389
+ }
390
+ };
391
+ });
392
+ }
393
+ }
394
+ exports.VSCodeAzureSubscriptionProvider = VSCodeAzureSubscriptionProvider;
387
395
  //# sourceMappingURL=VSCodeAzureSubscriptionProvider.js.map