@microsoft/vscode-azext-azureauth 1.0.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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation. All rights reserved.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # VSCode Azure SDK for Node.js - Azure Auth
2
+
3
+ [![Build Status](https://dev.azure.com/ms-azuretools/AzCode/_apis/build/status/vscode-azuretools)](https://dev.azure.com/ms-azuretools/AzCode/_build/latest?definitionId=17)
4
+
5
+ This package provides a simple way to authenticate to Azure and receive Azure subscription information.
6
+
7
+ ## Azure Subscription Provider
8
+
9
+ The `AzureSubscriptionProvider` interface describes the functions of this package.
10
+
11
+ ```typescript
12
+ /**
13
+ * An interface for obtaining Azure subscription information
14
+ */
15
+ export interface AzureSubscriptionProvider {
16
+ /**
17
+ * Gets a list of Azure subscriptions available to the user.
18
+ *
19
+ * @param filter - Whether to filter the list returned, according to the list returned
20
+ * by `getTenantFilters()` and `getSubscriptionFilters()`. Optional, default true.
21
+ *
22
+ * @returns A list of Azure subscriptions.
23
+ *
24
+ * @throws A {@link NotSignedInError} If the user is not signed in to Azure.
25
+ * Use {@link isSignedIn} and/or {@link signIn} before this method to ensure
26
+ * the user is signed in.
27
+ */
28
+ getSubscriptions(filter: boolean): Promise<AzureSubscription[]>;
29
+
30
+ /**
31
+ * Checks to see if a user is signed in.
32
+ *
33
+ * @returns True if the user is signed in, false otherwise.
34
+ */
35
+ isSignedIn(): Promise<boolean>;
36
+
37
+ /**
38
+ * Asks the user to sign in or pick an account to use.
39
+ *
40
+ * @returns True if the user is signed in, false otherwise.
41
+ */
42
+ signIn(): Promise<boolean>;
43
+
44
+ /**
45
+ * An event that is fired when the user signs in. Debounced to fire at most once every 5 seconds.
46
+ */
47
+ onDidSignIn: vscode.Event<void>;
48
+
49
+ /**
50
+ * Signs the user out
51
+ *
52
+ * @deprecated Not currently supported by VS Code auth providers
53
+ *
54
+ * @throws Throws an {@link Error} every time
55
+ */
56
+ signOut(): Promise<void>;
57
+
58
+ /**
59
+ * An event that is fired when the user signs out. Debounced to fire at most once every 5 seconds.
60
+ */
61
+ onDidSignOut: vscode.Event<void>;
62
+ }
63
+ ```
64
+
65
+ If the caller calls `getSubscriptions()` when the user is not signed in, a `NotSignedInError` will be thrown. You can check to see if a caught error is an instance of this error with `isNotSignedInError()`.
66
+
67
+ ## Azure Cloud Configuration
68
+ Two methods are available for controlling the VSCode settings that determine what cloud is connected to when enumerating subscriptions.
69
+
70
+ ```typescript
71
+ /**
72
+ * Gets the configured Azure environment.
73
+ *
74
+ * @returns The configured Azure environment from the `microsoft-sovereign-cloud.endpoint` setting.
75
+ */
76
+ export declare function getConfiguredAzureEnv(): azureEnv.Environment & {
77
+ isCustomCloud: boolean;
78
+ };
79
+
80
+ /**
81
+ * Sets the configured Azure cloud.
82
+ *
83
+ * @param cloud Use `'AzureCloud'` for public Azure cloud, `'AzureChinaCloud'` for Azure China, or `'AzureUSGovernment'` for Azure US Government.
84
+ * These are the same values as the cloud names in `@azure/ms-rest-azure-env`. For a custom cloud, use an instance of the `@azure/ms-rest-azure-env` `EnvironmentParameters`.
85
+ *
86
+ * @param target (Optional) The configuration target to use, by default {@link vscode.ConfigurationTarget.Global}.
87
+ */
88
+ export declare function setConfiguredAzureEnv(cloud: string | azureEnv.EnvironmentParameters, target?: vscode.ConfigurationTarget): Promise<void>;
89
+ ```
90
+
91
+ ## License
92
+
93
+ [MIT](LICENSE.md)
@@ -0,0 +1,14 @@
1
+ import type * as vscode from 'vscode';
2
+ /**
3
+ * Represents a means of obtaining authentication data for an Azure subscription.
4
+ */
5
+ export interface AzureAuthentication {
6
+ /**
7
+ * Gets a VS Code authentication session for an Azure subscription.
8
+ *
9
+ * @param scopes - The scopes for which the authentication is needed.
10
+ *
11
+ * @returns A VS Code authentication session or undefined, if none could be obtained.
12
+ */
13
+ getSession(scopes?: string[]): vscode.ProviderResult<vscode.AuthenticationSession>;
14
+ }
@@ -0,0 +1,7 @@
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
+ //# sourceMappingURL=AzureAuthentication.js.map
@@ -0,0 +1,44 @@
1
+ import type { TokenCredential } from '@azure/core-auth';
2
+ import type { Environment } from '@azure/ms-rest-azure-env';
3
+ import type { AzureAuthentication } from './AzureAuthentication';
4
+ /**
5
+ * A type representing an Azure subscription ID, not including the tenant ID.
6
+ */
7
+ export type SubscriptionId = string;
8
+ /**
9
+ * A type representing an Azure tenant ID.
10
+ */
11
+ export type TenantId = string;
12
+ /**
13
+ * Represents an Azure subscription.
14
+ */
15
+ export interface AzureSubscription {
16
+ /**
17
+ * Access to the authentication session associated with this subscription.
18
+ */
19
+ readonly authentication: AzureAuthentication;
20
+ /**
21
+ * The Azure environment to which this subscription belongs.
22
+ */
23
+ readonly environment: Environment;
24
+ /**
25
+ * Whether this subscription belongs to a custom cloud.
26
+ */
27
+ readonly isCustomCloud: boolean;
28
+ /**
29
+ * The display name of this subscription.
30
+ */
31
+ readonly name: string;
32
+ /**
33
+ * The ID of this subscription.
34
+ */
35
+ readonly subscriptionId: SubscriptionId;
36
+ /**
37
+ * The ID of the tenant to which this subscription belongs.
38
+ */
39
+ readonly tenantId: TenantId;
40
+ /**
41
+ * The credential for authentication to this subscription. Compatible with Azure track 2 SDKs.
42
+ */
43
+ readonly credential: TokenCredential;
44
+ }
@@ -0,0 +1,7 @@
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
+ //# sourceMappingURL=AzureSubscription.js.map
@@ -0,0 +1,48 @@
1
+ import type * as vscode from 'vscode';
2
+ import type { AzureSubscription } from './AzureSubscription';
3
+ /**
4
+ * An interface for obtaining Azure subscription information
5
+ */
6
+ export interface AzureSubscriptionProvider {
7
+ /**
8
+ * Gets a list of Azure subscriptions available to the user.
9
+ *
10
+ * @param filter - Whether to filter the list returned, according to the list returned
11
+ * by `getTenantFilters()` and `getSubscriptionFilters()`. Optional, default true.
12
+ *
13
+ * @returns A list of Azure subscriptions.
14
+ *
15
+ * @throws A {@link NotSignedInError} If the user is not signed in to Azure.
16
+ * Use {@link isSignedIn} and/or {@link signIn} before this method to ensure
17
+ * the user is signed in.
18
+ */
19
+ getSubscriptions(filter: boolean): Promise<AzureSubscription[]>;
20
+ /**
21
+ * Checks to see if a user is signed in.
22
+ *
23
+ * @returns True if the user is signed in, false otherwise.
24
+ */
25
+ isSignedIn(): Promise<boolean>;
26
+ /**
27
+ * Asks the user to sign in or pick an account to use.
28
+ *
29
+ * @returns True if the user is signed in, false otherwise.
30
+ */
31
+ signIn(): Promise<boolean>;
32
+ /**
33
+ * An event that is fired when the user signs in. Debounced to fire at most once every 5 seconds.
34
+ */
35
+ onDidSignIn: vscode.Event<void>;
36
+ /**
37
+ * Signs the user out
38
+ *
39
+ * @deprecated Not currently supported by VS Code auth providers
40
+ *
41
+ * @throws Throws an {@link Error} every time
42
+ */
43
+ signOut(): Promise<void>;
44
+ /**
45
+ * An event that is fired when the user signs out. Debounced to fire at most once every 5 seconds.
46
+ */
47
+ onDidSignOut: vscode.Event<void>;
48
+ }
@@ -0,0 +1,7 @@
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
+ //# sourceMappingURL=AzureSubscriptionProvider.js.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * An error indicating the user is not signed in.
3
+ */
4
+ export declare class NotSignedInError extends Error {
5
+ readonly isNotSignedInError = true;
6
+ constructor();
7
+ }
8
+ /**
9
+ * Tests if an object is a `NotSignedInError`. This should be used instead of `instanceof`.
10
+ *
11
+ * @param error The object to test
12
+ *
13
+ * @returns True if the object is a NotSignedInError, false otherwise
14
+ */
15
+ export declare function isNotSignedInError(error: unknown): error is NotSignedInError;
@@ -0,0 +1,30 @@
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.isNotSignedInError = exports.NotSignedInError = void 0;
8
+ const vscode = require("vscode");
9
+ /**
10
+ * An error indicating the user is not signed in.
11
+ */
12
+ class NotSignedInError extends Error {
13
+ constructor() {
14
+ super(vscode.l10n.t('You are not signed in to an Azure account. Please sign in.'));
15
+ this.isNotSignedInError = true;
16
+ }
17
+ }
18
+ exports.NotSignedInError = NotSignedInError;
19
+ /**
20
+ * Tests if an object is a `NotSignedInError`. This should be used instead of `instanceof`.
21
+ *
22
+ * @param error The object to test
23
+ *
24
+ * @returns True if the object is a NotSignedInError, false otherwise
25
+ */
26
+ function isNotSignedInError(error) {
27
+ return !!error && typeof error === 'object' && error.isNotSignedInError === true;
28
+ }
29
+ exports.isNotSignedInError = isNotSignedInError;
30
+ //# sourceMappingURL=NotSignedInError.js.map
@@ -0,0 +1,112 @@
1
+ import * as vscode from 'vscode';
2
+ import type { AzureSubscription, SubscriptionId, TenantId } from './AzureSubscription';
3
+ import type { AzureSubscriptionProvider } from './AzureSubscriptionProvider';
4
+ /**
5
+ * A class for obtaining Azure subscription information using VSCode's built-in authentication
6
+ * provider.
7
+ */
8
+ export declare class VSCodeAzureSubscriptionProvider extends vscode.Disposable implements AzureSubscriptionProvider {
9
+ private readonly onDidSignInEmitter;
10
+ private lastSignInEventFired;
11
+ private suppressSignInEvents;
12
+ private readonly onDidSignOutEmitter;
13
+ private lastSignOutEventFired;
14
+ constructor();
15
+ /**
16
+ * Gets a list of Azure subscriptions available to the user.
17
+ *
18
+ * @param filter - Whether to filter the list returned, according to the list returned
19
+ * by `getTenantFilters()` and `getSubscriptionFilters()`. Optional, default true.
20
+ *
21
+ * @returns A list of Azure subscriptions.
22
+ *
23
+ * @throws A {@link NotSignedInError} If the user is not signed in to Azure.
24
+ * Use {@link isSignedIn} and/or {@link signIn} before this method to ensure
25
+ * the user is signed in.
26
+ */
27
+ getSubscriptions(filter?: boolean): Promise<AzureSubscription[]>;
28
+ /**
29
+ * Checks to see if a user is signed in.
30
+ *
31
+ * @returns True if the user is signed in, false otherwise.
32
+ */
33
+ isSignedIn(): Promise<boolean>;
34
+ /**
35
+ * Asks the user to sign in or pick an account to use.
36
+ *
37
+ * @returns True if the user is signed in, false otherwise.
38
+ */
39
+ signIn(): Promise<boolean>;
40
+ /**
41
+ * An event that is fired when the user signs in. Debounced to fire at most once every 5 seconds.
42
+ */
43
+ readonly onDidSignIn: vscode.Event<void>;
44
+ /**
45
+ * Signs the user out
46
+ *
47
+ * @deprecated Not currently supported by VS Code auth providers
48
+ */
49
+ signOut(): Promise<void>;
50
+ /**
51
+ * An event that is fired when the user signs out. Debounced to fire at most once every 5 seconds.
52
+ */
53
+ readonly onDidSignOut: vscode.Event<void>;
54
+ /**
55
+ * Gets the tenant filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
56
+ * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
57
+ * and/or `getTenantFilters()` overridden.
58
+ *
59
+ * If no values are returned by `getTenantFilters()`, then all tenants will be scanned for subscriptions.
60
+ *
61
+ * @returns A list of tenant IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
62
+ */
63
+ protected getTenantFilters(): Promise<TenantId[]>;
64
+ /**
65
+ * Gets the subscription filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
66
+ * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
67
+ * and/or `getTenantFilters()` overridden.
68
+ *
69
+ * If no values are returned by `getSubscriptionFilters()`, then all subscriptions will be returned.
70
+ *
71
+ * @returns A list of subscription IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
72
+ */
73
+ protected getSubscriptionFilters(): Promise<SubscriptionId[]>;
74
+ /**
75
+ * Gets the tenants available to a user.
76
+ *
77
+ * @returns The list of tenants visible to the user.
78
+ */
79
+ private getTenants;
80
+ /**
81
+ * Gets the subscriptions for a given tenant.
82
+ *
83
+ * @param tenantId The tenant ID to get subscriptions for.
84
+ *
85
+ * @returns The list of subscriptions for the tenant.
86
+ */
87
+ private getSubscriptionsForTenant;
88
+ /**
89
+ * Gets a fully-configured subscription client for a given tenant ID
90
+ *
91
+ * @param tenantId (Optional) The tenant ID to get a client for
92
+ *
93
+ * @returns A client, the credential used by the client, and the authentication function
94
+ */
95
+ private getSubscriptionClient;
96
+ /**
97
+ * Gets a normalized list of scopes
98
+ *
99
+ * @param scopes An input scope string, list, or undefined
100
+ * @param tenantId (Optional) The tenant ID, will be added to the scopes
101
+ *
102
+ * @returns A list of scopes, with the default scope and (optionally) the tenant scope added
103
+ */
104
+ private getScopes;
105
+ /**
106
+ * Gets the default Azure scopes required for resource management,
107
+ * depending on the configured endpoint
108
+ *
109
+ * @returns The default Azure scopes required
110
+ */
111
+ private getDefaultScopes;
112
+ }
@@ -0,0 +1,321 @@
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 NotSignedInError_1 = require("./NotSignedInError");
26
+ const configuredAzureEnv_1 = require("./utils/configuredAzureEnv");
27
+ const EventDebounce = 5 * 1000; // 5 seconds
28
+ /**
29
+ * A class for obtaining Azure subscription information using VSCode's built-in authentication
30
+ * provider.
31
+ */
32
+ class VSCodeAzureSubscriptionProvider extends vscode.Disposable {
33
+ constructor() {
34
+ const disposable = vscode.authentication.onDidChangeSessions((e) => __awaiter(this, void 0, void 0, function* () {
35
+ // Ignore any sign in that isn't for the configured auth provider
36
+ if (e.provider.id !== (0, configuredAzureEnv_1.getConfiguredAuthProviderId)()) {
37
+ return;
38
+ }
39
+ if (yield this.isSignedIn()) {
40
+ if (!this.suppressSignInEvents && Date.now() > this.lastSignInEventFired + EventDebounce) {
41
+ this.lastSignInEventFired = Date.now();
42
+ this.onDidSignInEmitter.fire();
43
+ }
44
+ }
45
+ else if (Date.now() > this.lastSignOutEventFired + EventDebounce) {
46
+ this.lastSignOutEventFired = Date.now();
47
+ this.onDidSignOutEmitter.fire();
48
+ }
49
+ }));
50
+ super(() => {
51
+ this.onDidSignInEmitter.dispose();
52
+ this.onDidSignOutEmitter.dispose();
53
+ disposable.dispose();
54
+ });
55
+ this.onDidSignInEmitter = new vscode.EventEmitter();
56
+ this.lastSignInEventFired = 0;
57
+ this.suppressSignInEvents = false;
58
+ this.onDidSignOutEmitter = new vscode.EventEmitter();
59
+ this.lastSignOutEventFired = 0;
60
+ /**
61
+ * An event that is fired when the user signs in. Debounced to fire at most once every 5 seconds.
62
+ */
63
+ this.onDidSignIn = this.onDidSignInEmitter.event;
64
+ /**
65
+ * An event that is fired when the user signs out. Debounced to fire at most once every 5 seconds.
66
+ */
67
+ this.onDidSignOut = this.onDidSignOutEmitter.event;
68
+ }
69
+ /**
70
+ * Gets a list of Azure subscriptions available to the user.
71
+ *
72
+ * @param filter - Whether to filter the list returned, according to the list returned
73
+ * by `getTenantFilters()` and `getSubscriptionFilters()`. Optional, default true.
74
+ *
75
+ * @returns A list of Azure subscriptions.
76
+ *
77
+ * @throws A {@link NotSignedInError} If the user is not signed in to Azure.
78
+ * Use {@link isSignedIn} and/or {@link signIn} before this method to ensure
79
+ * the user is signed in.
80
+ */
81
+ getSubscriptions(filter = true) {
82
+ return __awaiter(this, void 0, void 0, function* () {
83
+ const tenantIds = yield this.getTenantFilters();
84
+ const tenantFilterNormalized = filter && !!tenantIds.length; // If the list is empty it is treated as "no filter"
85
+ const subscriptionIds = yield this.getSubscriptionFilters();
86
+ const subscriptionFilterNormalized = filter && !!subscriptionIds.length; // If the list is empty it is treated as "no filter"
87
+ const results = [];
88
+ try {
89
+ this.suppressSignInEvents = true;
90
+ // Get the list of tenants
91
+ for (const tenant of yield this.getTenants()) {
92
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
93
+ const tenantId = tenant.tenantId;
94
+ // If filtering is enabled, and the current tenant is not in that list, then skip it
95
+ if (tenantFilterNormalized && !tenantIds.includes(tenantId)) {
96
+ continue;
97
+ }
98
+ // For each tenant, get the list of subscriptions
99
+ for (const subscription of yield this.getSubscriptionsForTenant(tenantId)) {
100
+ // If filtering is enabled, and the current subscription is not in that list, then skip it
101
+ if (subscriptionFilterNormalized && !subscriptionIds.includes(subscription.subscriptionId)) {
102
+ continue;
103
+ }
104
+ results.push(subscription);
105
+ }
106
+ }
107
+ }
108
+ finally {
109
+ this.suppressSignInEvents = false;
110
+ }
111
+ return results;
112
+ });
113
+ }
114
+ /**
115
+ * Checks to see if a user is signed in.
116
+ *
117
+ * @returns True if the user is signed in, false otherwise.
118
+ */
119
+ isSignedIn() {
120
+ return __awaiter(this, void 0, void 0, function* () {
121
+ const session = yield vscode.authentication.getSession((0, configuredAzureEnv_1.getConfiguredAuthProviderId)(), this.getDefaultScopes(), { createIfNone: false, silent: true });
122
+ return !!session;
123
+ });
124
+ }
125
+ /**
126
+ * Asks the user to sign in or pick an account to use.
127
+ *
128
+ * @returns True if the user is signed in, false otherwise.
129
+ */
130
+ signIn() {
131
+ return __awaiter(this, void 0, void 0, function* () {
132
+ const session = yield vscode.authentication.getSession((0, configuredAzureEnv_1.getConfiguredAuthProviderId)(), this.getDefaultScopes(), { createIfNone: true, clearSessionPreference: true });
133
+ return !!session;
134
+ });
135
+ }
136
+ /**
137
+ * Signs the user out
138
+ *
139
+ * @deprecated Not currently supported by VS Code auth providers
140
+ */
141
+ signOut() {
142
+ 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.'));
143
+ }
144
+ /**
145
+ * Gets the tenant filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
146
+ * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
147
+ * and/or `getTenantFilters()` overridden.
148
+ *
149
+ * If no values are returned by `getTenantFilters()`, then all tenants will be scanned for subscriptions.
150
+ *
151
+ * @returns A list of tenant IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
152
+ */
153
+ getTenantFilters() {
154
+ return __awaiter(this, void 0, void 0, function* () {
155
+ const config = vscode.workspace.getConfiguration('azureResourceGroups');
156
+ const fullSubscriptionIds = config.get('selectedSubscriptions', []);
157
+ return fullSubscriptionIds.map(id => id.split('/')[0]);
158
+ });
159
+ }
160
+ /**
161
+ * Gets the subscription filters that are configured in `azureResourceGroups.selectedSubscriptions`. To
162
+ * override the settings with a custom filter, implement a child class with `getSubscriptionFilters()`
163
+ * and/or `getTenantFilters()` overridden.
164
+ *
165
+ * If no values are returned by `getSubscriptionFilters()`, then all subscriptions will be returned.
166
+ *
167
+ * @returns A list of subscription IDs that are configured in `azureResourceGroups.selectedSubscriptions`.
168
+ */
169
+ getSubscriptionFilters() {
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ const config = vscode.workspace.getConfiguration('azureResourceGroups');
172
+ const fullSubscriptionIds = config.get('selectedSubscriptions', []);
173
+ return fullSubscriptionIds.map(id => id.split('/')[1]);
174
+ });
175
+ }
176
+ /**
177
+ * Gets the tenants available to a user.
178
+ *
179
+ * @returns The list of tenants visible to the user.
180
+ */
181
+ getTenants() {
182
+ var _a, e_1, _b, _c;
183
+ return __awaiter(this, void 0, void 0, function* () {
184
+ const { client } = yield this.getSubscriptionClient();
185
+ const tenants = [];
186
+ try {
187
+ for (var _d = true, _e = __asyncValues(client.tenants.list()), _f; _f = yield _e.next(), _a = _f.done, !_a;) {
188
+ _c = _f.value;
189
+ _d = false;
190
+ try {
191
+ const tenant = _c;
192
+ tenants.push(tenant);
193
+ }
194
+ finally {
195
+ _d = true;
196
+ }
197
+ }
198
+ }
199
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
200
+ finally {
201
+ try {
202
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
203
+ }
204
+ finally { if (e_1) throw e_1.error; }
205
+ }
206
+ return tenants;
207
+ });
208
+ }
209
+ /**
210
+ * Gets the subscriptions for a given tenant.
211
+ *
212
+ * @param tenantId The tenant ID to get subscriptions for.
213
+ *
214
+ * @returns The list of subscriptions for the tenant.
215
+ */
216
+ getSubscriptionsForTenant(tenantId) {
217
+ var _a, e_2, _b, _c;
218
+ return __awaiter(this, void 0, void 0, function* () {
219
+ const { client, credential, authentication } = yield this.getSubscriptionClient(tenantId);
220
+ const environment = (0, configuredAzureEnv_1.getConfiguredAzureEnv)();
221
+ const subscriptions = [];
222
+ try {
223
+ for (var _d = true, _e = __asyncValues(client.subscriptions.list()), _f; _f = yield _e.next(), _a = _f.done, !_a;) {
224
+ _c = _f.value;
225
+ _d = false;
226
+ try {
227
+ const subscription = _c;
228
+ subscriptions.push({
229
+ authentication: authentication,
230
+ environment: environment,
231
+ credential: credential,
232
+ isCustomCloud: environment.isCustomCloud,
233
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
234
+ name: subscription.displayName,
235
+ subscriptionId: subscription.subscriptionId,
236
+ /* eslint-enable @typescript-eslint/no-non-null-assertion */
237
+ tenantId: tenantId,
238
+ });
239
+ }
240
+ finally {
241
+ _d = true;
242
+ }
243
+ }
244
+ }
245
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
246
+ finally {
247
+ try {
248
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
249
+ }
250
+ finally { if (e_2) throw e_2.error; }
251
+ }
252
+ return subscriptions;
253
+ });
254
+ }
255
+ /**
256
+ * Gets a fully-configured subscription client for a given tenant ID
257
+ *
258
+ * @param tenantId (Optional) The tenant ID to get a client for
259
+ *
260
+ * @returns A client, the credential used by the client, and the authentication function
261
+ */
262
+ getSubscriptionClient(tenantId) {
263
+ return __awaiter(this, void 0, void 0, function* () {
264
+ const armSubs = yield Promise.resolve().then(() => require('@azure/arm-subscriptions'));
265
+ // This gets filled in when the client calls `getToken`, and then it can be returned in the `authentication` property of `AzureSubscription`
266
+ let session;
267
+ const credential = {
268
+ getToken: (scopes) => __awaiter(this, void 0, void 0, function* () {
269
+ // TODO: change to `getSessions` when that API is available: https://github.com/microsoft/vscode/issues/152399
270
+ session = yield vscode.authentication.getSession((0, configuredAzureEnv_1.getConfiguredAuthProviderId)(), this.getScopes(scopes, tenantId), { createIfNone: false, silent: true });
271
+ if (!session) {
272
+ throw new NotSignedInError_1.NotSignedInError();
273
+ }
274
+ return {
275
+ token: session.accessToken,
276
+ expiresOnTimestamp: 0
277
+ };
278
+ })
279
+ };
280
+ return {
281
+ client: new armSubs.SubscriptionClient(credential),
282
+ credential: credential,
283
+ authentication: {
284
+ getSession: () => session // Rewrapped to make TS not confused about the weird initialization pattern
285
+ }
286
+ };
287
+ });
288
+ }
289
+ /**
290
+ * Gets a normalized list of scopes
291
+ *
292
+ * @param scopes An input scope string, list, or undefined
293
+ * @param tenantId (Optional) The tenant ID, will be added to the scopes
294
+ *
295
+ * @returns A list of scopes, with the default scope and (optionally) the tenant scope added
296
+ */
297
+ getScopes(scopes, tenantId) {
298
+ const scopeSet = new Set(this.getDefaultScopes());
299
+ if (typeof scopes === 'string') {
300
+ scopeSet.add(scopes);
301
+ }
302
+ else if (Array.isArray(scopes)) {
303
+ scopes.forEach(scope => scopeSet.add(scope));
304
+ }
305
+ if (tenantId) {
306
+ scopeSet.add(`VSCODE_TENANT:${tenantId}`);
307
+ }
308
+ return Array.from(scopeSet);
309
+ }
310
+ /**
311
+ * Gets the default Azure scopes required for resource management,
312
+ * depending on the configured endpoint
313
+ *
314
+ * @returns The default Azure scopes required
315
+ */
316
+ getDefaultScopes() {
317
+ return [`${(0, configuredAzureEnv_1.getConfiguredAzureEnv)().resourceManagerEndpointUrl}.default`];
318
+ }
319
+ }
320
+ exports.VSCodeAzureSubscriptionProvider = VSCodeAzureSubscriptionProvider;
321
+ //# sourceMappingURL=VSCodeAzureSubscriptionProvider.js.map
@@ -0,0 +1,6 @@
1
+ export * from './AzureAuthentication';
2
+ export * from './AzureSubscription';
3
+ export * from './AzureSubscriptionProvider';
4
+ export * from './NotSignedInError';
5
+ export * from './utils/configuredAzureEnv';
6
+ export * from './VSCodeAzureSubscriptionProvider';
@@ -0,0 +1,27 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
18
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ __exportStar(require("./AzureAuthentication"), exports);
22
+ __exportStar(require("./AzureSubscription"), exports);
23
+ __exportStar(require("./AzureSubscriptionProvider"), exports);
24
+ __exportStar(require("./NotSignedInError"), exports);
25
+ __exportStar(require("./utils/configuredAzureEnv"), exports);
26
+ __exportStar(require("./VSCodeAzureSubscriptionProvider"), exports);
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,24 @@
1
+ import * as azureEnv from '@azure/ms-rest-azure-env';
2
+ import * as vscode from 'vscode';
3
+ /**
4
+ * Gets the configured Azure environment.
5
+ *
6
+ * @returns The configured Azure environment from the `microsoft-sovereign-cloud.endpoint` setting.
7
+ */
8
+ export declare function getConfiguredAzureEnv(): azureEnv.Environment & {
9
+ isCustomCloud: boolean;
10
+ };
11
+ /**
12
+ * Sets the configured Azure cloud.
13
+ *
14
+ * @param cloud Use `'AzureCloud'` for public Azure cloud, `'AzureChinaCloud'` for Azure China, or `'AzureUSGovernment'` for Azure US Government.
15
+ * These are the same values as the cloud names in `@azure/ms-rest-azure-env`. For a custom cloud, use an instance of the `@azure/ms-rest-azure-env` `EnvironmentParameters`.
16
+ *
17
+ * @param target (Optional) The configuration target to use, by default {@link vscode.ConfigurationTarget.Global}.
18
+ */
19
+ export declare function setConfiguredAzureEnv(cloud: string | azureEnv.EnvironmentParameters, target?: vscode.ConfigurationTarget): Promise<void>;
20
+ /**
21
+ * Gets the ID of the authentication provider configured to be used
22
+ * @returns The provider ID to use, either `'microsoft'` or `'microsoft-sovereign-cloud'`
23
+ */
24
+ export declare function getConfiguredAuthProviderId(): string;
@@ -0,0 +1,90 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.getConfiguredAuthProviderId = exports.setConfiguredAzureEnv = exports.getConfiguredAzureEnv = void 0;
17
+ const azureEnv = require("@azure/ms-rest-azure-env"); // This package is so small that it's not worth lazy loading
18
+ const vscode = require("vscode");
19
+ const AzureCloudName = azureEnv.Environment.AzureCloud.name;
20
+ const AzureChinaCloudName = azureEnv.Environment.ChinaCloud.name;
21
+ const AzureUSGovernmentCloudName = azureEnv.Environment.USGovernment.name;
22
+ const CloudNameToEndpointSettingValue = {};
23
+ CloudNameToEndpointSettingValue[AzureCloudName] = undefined;
24
+ CloudNameToEndpointSettingValue[AzureChinaCloudName] = 'Azure China';
25
+ CloudNameToEndpointSettingValue[AzureUSGovernmentCloudName] = 'Azure US Government';
26
+ /**
27
+ * Gets the configured Azure environment.
28
+ *
29
+ * @returns The configured Azure environment from the `microsoft-sovereign-cloud.endpoint` setting.
30
+ */
31
+ function getConfiguredAzureEnv() {
32
+ var _a;
33
+ const authProviderConfig = vscode.workspace.getConfiguration('microsoft-sovereign-cloud');
34
+ const endpointSettingValue = (_a = authProviderConfig.get('endpoint')) === null || _a === void 0 ? void 0 : _a.toLowerCase();
35
+ // The endpoint setting will accept either the environment name (either 'Azure China' or 'Azure US Government'),
36
+ // or an endpoint URL. Since the user could configure the same environment either way, we need to check both.
37
+ // We'll also throw to lowercase just to maximize the chance of success.
38
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
39
+ if (endpointSettingValue === CloudNameToEndpointSettingValue[AzureChinaCloudName].toLowerCase() || endpointSettingValue === azureEnv.Environment.ChinaCloud.activeDirectoryEndpointUrl.toLowerCase()) {
40
+ return Object.assign(Object.assign({}, azureEnv.Environment.get(azureEnv.Environment.ChinaCloud.name)), { isCustomCloud: false });
41
+ }
42
+ else if (endpointSettingValue === CloudNameToEndpointSettingValue[AzureUSGovernmentCloudName].toLowerCase() || endpointSettingValue === azureEnv.Environment.USGovernment.activeDirectoryEndpointUrl.toLowerCase()) {
43
+ return Object.assign(Object.assign({}, azureEnv.Environment.get(azureEnv.Environment.USGovernment.name)), { isCustomCloud: false });
44
+ }
45
+ else if (endpointSettingValue) {
46
+ const rgConfig = vscode.workspace.getConfiguration('azureResourceGroups');
47
+ const customCloud = rgConfig.get('customCloud'); // TODO: final setting name
48
+ if (customCloud) {
49
+ return Object.assign(Object.assign({}, new azureEnv.Environment(customCloud)), { isCustomCloud: true });
50
+ }
51
+ throw new Error(vscode.l10n.t('The custom cloud choice is not configured. Please configure the setting `azureResourceGroups.customCloud`.')); // TODO: final setting name
52
+ }
53
+ /* eslint-enable @typescript-eslint/no-non-null-assertion */
54
+ return Object.assign(Object.assign({}, azureEnv.Environment.get(azureEnv.Environment.AzureCloud.name)), { isCustomCloud: false });
55
+ }
56
+ exports.getConfiguredAzureEnv = getConfiguredAzureEnv;
57
+ /**
58
+ * Sets the configured Azure cloud.
59
+ *
60
+ * @param cloud Use `'AzureCloud'` for public Azure cloud, `'AzureChinaCloud'` for Azure China, or `'AzureUSGovernment'` for Azure US Government.
61
+ * These are the same values as the cloud names in `@azure/ms-rest-azure-env`. For a custom cloud, use an instance of the `@azure/ms-rest-azure-env` `EnvironmentParameters`.
62
+ *
63
+ * @param target (Optional) The configuration target to use, by default {@link vscode.ConfigurationTarget.Global}.
64
+ */
65
+ function setConfiguredAzureEnv(cloud, target = vscode.ConfigurationTarget.Global) {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ const authProviderConfig = vscode.workspace.getConfiguration('microsoft-sovereign-cloud');
68
+ if (typeof cloud === 'string' && cloud in CloudNameToEndpointSettingValue) {
69
+ yield authProviderConfig.update('endpoint', CloudNameToEndpointSettingValue[cloud], target);
70
+ }
71
+ else if (typeof cloud === 'object' && 'activeDirectoryEndpointUrl' in cloud) {
72
+ yield authProviderConfig.update('endpoint', cloud.activeDirectoryEndpointUrl, target);
73
+ const rgConfig = vscode.workspace.getConfiguration('azureResourceGroups');
74
+ yield rgConfig.update('customCloud', cloud, target); // TODO: final setting name
75
+ }
76
+ else {
77
+ throw new Error(`Invalid cloud value: ${JSON.stringify(cloud)}`);
78
+ }
79
+ });
80
+ }
81
+ exports.setConfiguredAzureEnv = setConfiguredAzureEnv;
82
+ /**
83
+ * Gets the ID of the authentication provider configured to be used
84
+ * @returns The provider ID to use, either `'microsoft'` or `'microsoft-sovereign-cloud'`
85
+ */
86
+ function getConfiguredAuthProviderId() {
87
+ return getConfiguredAzureEnv().name === AzureCloudName ? 'microsoft' : 'microsoft-sovereign-cloud';
88
+ }
89
+ exports.getConfiguredAuthProviderId = getConfiguredAuthProviderId;
90
+ //# sourceMappingURL=configuredAzureEnv.js.map
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@microsoft/vscode-azext-azureauth",
3
+ "author": "Microsoft Corporation",
4
+ "version": "1.0.0",
5
+ "description": "Azure authentication helpers for Visual Studio Code",
6
+ "tags": [
7
+ "azure",
8
+ "vscode"
9
+ ],
10
+ "keywords": [
11
+ "azure",
12
+ "vscode"
13
+ ],
14
+ "main": "out/src/index.js",
15
+ "types": "out/src/index.d.ts",
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/Microsoft/vscode-azuretools"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/Microsoft/vscode-azuretools/issues"
23
+ },
24
+ "homepage": "https://github.com/Microsoft/vscode-azuretools/blob/main/auth/README.md",
25
+ "scripts": {
26
+ "build": "tsc -p ./",
27
+ "compile": "tsc -watch -p ./",
28
+ "lint": "eslint --ext .ts .",
29
+ "lint-fix": "eslint --ext .ts . --fix",
30
+ "test": "node ./out/test/runTest.js",
31
+ "package": "npm pack"
32
+ },
33
+ "devDependencies": {
34
+ "@azure/core-auth": "^1.4.0",
35
+ "@microsoft/eslint-config-azuretools": "^0.2.1",
36
+ "@types/glob": "^8.1.0",
37
+ "@types/html-to-text": "^8.1.0",
38
+ "@types/mocha": "^7.0.2",
39
+ "@types/node": "^16.0.0",
40
+ "@types/semver": "^7.3.9",
41
+ "@types/uuid": "^9.0.1",
42
+ "@types/vscode": "1.76.0",
43
+ "@typescript-eslint/eslint-plugin": "^5.53.0",
44
+ "@vscode/test-electron": "^2.1.5",
45
+ "eslint": "^8.34.0",
46
+ "eslint-plugin-import": "^2.22.1",
47
+ "glob": "^7.1.6",
48
+ "mocha": "^9.1.3",
49
+ "mocha-junit-reporter": "^2.0.2",
50
+ "mocha-multi-reporters": "^1.1.7",
51
+ "typescript": "^4.9.4"
52
+ },
53
+ "dependencies": {
54
+ "@azure/arm-subscriptions": "^5.1.0",
55
+ "@azure/ms-rest-azure-env": "^2.0.0"
56
+ }
57
+ }