@azure/identity 4.3.0-beta.1 → 4.3.0-beta.2

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/dist/index.js CHANGED
@@ -12,6 +12,7 @@ var fs = require('fs');
12
12
  var os = require('os');
13
13
  var path = require('path');
14
14
  var msalCommon = require('@azure/msal-node');
15
+ var fs$1 = require('node:fs');
15
16
  var https = require('https');
16
17
  var promises = require('fs/promises');
17
18
  var child_process = require('child_process');
@@ -44,7 +45,7 @@ var child_process__namespace = /*#__PURE__*/_interopNamespaceDefault(child_proce
44
45
  /**
45
46
  * Current version of the `@azure/identity` package.
46
47
  */
47
- const SDK_VERSION = `4.3.0-beta.1`;
48
+ const SDK_VERSION = `4.3.0-beta.2`;
48
49
  /**
49
50
  * The default client ID for authentication
50
51
  * @internal
@@ -1179,18 +1180,6 @@ function prepareRequestOptions$3(scopes, clientId, resourceId) {
1179
1180
  }),
1180
1181
  });
1181
1182
  }
1182
- /**
1183
- * Retrieves the file contents at the given path using promises.
1184
- * Useful since `fs`'s readFileSync locks the thread, and to avoid extra dependencies.
1185
- */
1186
- function readFileAsync$1(path, options) {
1187
- return new Promise((resolve, reject) => fs.readFile(path, options, (err, data) => {
1188
- if (err) {
1189
- reject(err);
1190
- }
1191
- resolve(data);
1192
- }));
1193
- }
1194
1183
  /**
1195
1184
  * Does a request to the authentication provider that results in a file path.
1196
1185
  */
@@ -1211,6 +1200,43 @@ async function filePathRequest(identityClient, requestPrepareOptions) {
1211
1200
  throw Error(`Invalid www-authenticate header format: ${authHeader}`);
1212
1201
  }
1213
1202
  }
1203
+ function platformToFilePath() {
1204
+ switch (process.platform) {
1205
+ case "win32":
1206
+ if (!process.env.PROGRAMDATA) {
1207
+ throw new Error(`${msiName$4}: PROGRAMDATA environment variable has no value.`);
1208
+ }
1209
+ return `${process.env.PROGRAMDATA}\\AzureConnectedMachineAgent\\Tokens`;
1210
+ case "linux":
1211
+ return "/var/opt/azcmagent/tokens";
1212
+ default:
1213
+ throw new Error(`${msiName$4}: Unsupported platform ${process.platform}.`);
1214
+ }
1215
+ }
1216
+ /**
1217
+ * Validates that a given Azure Arc MSI file path is valid for use.
1218
+ *
1219
+ * A valid file will:
1220
+ * 1. Be in the expected path for the current platform.
1221
+ * 2. Have a `.key` extension.
1222
+ * 3. Be at most 4096 bytes in size.
1223
+ */
1224
+ function validateKeyFile(filePath) {
1225
+ if (!filePath) {
1226
+ throw new Error(`${msiName$4}: Failed to find the token file.`);
1227
+ }
1228
+ if (!filePath.endsWith(".key")) {
1229
+ throw new Error(`${msiName$4}: unexpected file path from HIMDS service: ${filePath}.`);
1230
+ }
1231
+ const expectedPath = platformToFilePath();
1232
+ if (!filePath.startsWith(expectedPath)) {
1233
+ throw new Error(`${msiName$4}: unexpected file path from HIMDS service: ${filePath}.`);
1234
+ }
1235
+ const stats = fs$1.statSync(filePath);
1236
+ if (stats.size > 4096) {
1237
+ throw new Error(`${msiName$4}: The file at ${filePath} is larger than expected at ${stats.size} bytes.`);
1238
+ }
1239
+ }
1214
1240
  /**
1215
1241
  * Defines how to determine whether the Azure Arc MSI is available, and also how to retrieve a token from the Azure Arc MSI.
1216
1242
  */
@@ -1240,10 +1266,8 @@ const arcMsi = {
1240
1266
  logger$m.info(`${msiName$4}: Authenticating.`);
1241
1267
  const requestOptions = Object.assign(Object.assign({ disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$3(scopes, clientId, resourceId)), { allowInsecureConnection: true });
1242
1268
  const filePath = await filePathRequest(identityClient, requestOptions);
1243
- if (!filePath) {
1244
- throw new Error(`${msiName$4}: Failed to find the token file.`);
1245
- }
1246
- const key = await readFileAsync$1(filePath, { encoding: "utf-8" });
1269
+ validateKeyFile(filePath);
1270
+ const key = await fs$1.promises.readFile(filePath, { encoding: "utf-8" });
1247
1271
  (_a = requestOptions.headers) === null || _a === void 0 ? void 0 : _a.set("Authorization", `Basic ${key}`);
1248
1272
  const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({}, requestOptions), {
1249
1273
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
@@ -2165,18 +2189,56 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
2165
2189
  return deviceCodeRequest;
2166
2190
  });
2167
2191
  }
2192
+ async function getTokenByUsernamePassword(scopes, username, password, options = {}) {
2193
+ msalLogger.getToken.info(`Attempting to acquire token using username and password`);
2194
+ const msalApp = await getPublicApp(options);
2195
+ return withSilentAuthentication(msalApp, scopes, options, () => {
2196
+ const requestOptions = {
2197
+ scopes,
2198
+ username,
2199
+ password,
2200
+ authority: state.msalConfig.auth.authority,
2201
+ claims: options === null || options === void 0 ? void 0 : options.claims,
2202
+ };
2203
+ return msalApp.acquireTokenByUsernamePassword(requestOptions);
2204
+ });
2205
+ }
2168
2206
  function getActiveAccount() {
2169
2207
  if (!state.cachedAccount) {
2170
2208
  return undefined;
2171
2209
  }
2172
2210
  return msalToPublic(clientId, state.cachedAccount);
2173
2211
  }
2212
+ async function getTokenByAuthorizationCode(scopes, redirectUri, authorizationCode, clientSecret, options = {}) {
2213
+ msalLogger.getToken.info(`Attempting to acquire token using authorization code`);
2214
+ let msalApp;
2215
+ if (clientSecret) {
2216
+ // If a client secret is provided, we need to use a confidential client application
2217
+ // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret
2218
+ state.msalConfig.auth.clientSecret = clientSecret;
2219
+ msalApp = await getConfidentialApp(options);
2220
+ }
2221
+ else {
2222
+ msalApp = await getPublicApp(options);
2223
+ }
2224
+ return withSilentAuthentication(msalApp, scopes, options, () => {
2225
+ return msalApp.acquireTokenByCode({
2226
+ scopes,
2227
+ redirectUri,
2228
+ code: authorizationCode,
2229
+ authority: state.msalConfig.auth.authority,
2230
+ claims: options === null || options === void 0 ? void 0 : options.claims,
2231
+ });
2232
+ });
2233
+ }
2174
2234
  return {
2175
2235
  getActiveAccount,
2176
2236
  getTokenByClientSecret,
2177
2237
  getTokenByClientAssertion,
2178
2238
  getTokenByClientCertificate,
2179
2239
  getTokenByDeviceCode,
2240
+ getTokenByUsernamePassword,
2241
+ getTokenByAuthorizationCode,
2180
2242
  };
2181
2243
  }
2182
2244
 
@@ -3455,117 +3517,425 @@ class ClientSecretCredential {
3455
3517
 
3456
3518
  // Copyright (c) Microsoft Corporation.
3457
3519
  // Licensed under the MIT license.
3520
+ const logger$7 = credentialLogger("UsernamePasswordCredential");
3458
3521
  /**
3459
- * MSAL partial base client for Node.js.
3460
- *
3461
- * It completes the input configuration with some default values.
3462
- * It also provides with utility protected methods that can be used from any of the clients,
3463
- * which includes handlers for successful responses and errors.
3464
- *
3465
- * @internal
3522
+ * Enables authentication to Microsoft Entra ID with a user's
3523
+ * username and password. This credential requires a high degree of
3524
+ * trust so you should only use it when other, more secure credential
3525
+ * types can't be used.
3466
3526
  */
3467
- class MsalNode {
3468
- constructor(options) {
3469
- var _a, _b, _c, _d, _e, _f;
3470
- this.app = {};
3471
- this.caeApp = {};
3472
- this.requiresConfidential = false;
3473
- this.logger = options.logger;
3474
- this.msalConfig = this.defaultNodeMsalConfig(options);
3475
- this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
3476
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds((_a = options === null || options === void 0 ? void 0 : options.tokenCredentialOptions) === null || _a === void 0 ? void 0 : _a.additionallyAllowedTenants);
3477
- this.clientId = this.msalConfig.auth.clientId;
3478
- if (options === null || options === void 0 ? void 0 : options.getAssertion) {
3479
- this.getAssertion = options.getAssertion;
3480
- }
3481
- this.enableBroker = (_b = options === null || options === void 0 ? void 0 : options.brokerOptions) === null || _b === void 0 ? void 0 : _b.enabled;
3482
- this.enableMsaPassthrough = (_c = options === null || options === void 0 ? void 0 : options.brokerOptions) === null || _c === void 0 ? void 0 : _c.legacyEnableMsaPassthrough;
3483
- this.parentWindowHandle = (_d = options.brokerOptions) === null || _d === void 0 ? void 0 : _d.parentWindowHandle;
3484
- // If persistence has been configured
3485
- if (persistenceProvider !== undefined && ((_e = options.tokenCachePersistenceOptions) === null || _e === void 0 ? void 0 : _e.enabled)) {
3486
- const cacheBaseName = options.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME;
3487
- const nonCaeOptions = Object.assign({ name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions);
3488
- const caeOptions = Object.assign({ name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions);
3489
- this.createCachePlugin = () => persistenceProvider(nonCaeOptions);
3490
- this.createCachePluginCae = () => persistenceProvider(caeOptions);
3491
- }
3492
- else if ((_f = options.tokenCachePersistenceOptions) === null || _f === void 0 ? void 0 : _f.enabled) {
3493
- throw new Error([
3494
- "Persistent token caching was requested, but no persistence provider was configured.",
3495
- "You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)",
3496
- "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",
3497
- "`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.",
3498
- ].join(" "));
3499
- }
3500
- // If broker has not been configured
3501
- if (!hasNativeBroker() && this.enableBroker) {
3502
- throw new Error([
3503
- "Broker for WAM was requested to be enabled, but no native broker was configured.",
3504
- "You must install the identity-broker plugin package (`npm install --save @azure/identity-broker`)",
3505
- "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",
3506
- "`useIdentityPlugin(createNativeBrokerPlugin())` before using `enableBroker`.",
3507
- ].join(" "));
3527
+ class UsernamePasswordCredential {
3528
+ /**
3529
+ * Creates an instance of the UsernamePasswordCredential with the details
3530
+ * needed to authenticate against Microsoft Entra ID with a username
3531
+ * and password.
3532
+ *
3533
+ * @param tenantId - The Microsoft Entra tenant (directory).
3534
+ * @param clientId - The client (application) ID of an App Registration in the tenant.
3535
+ * @param username - The user account's e-mail address (user name).
3536
+ * @param password - The user account's account password
3537
+ * @param options - Options for configuring the client which makes the authentication request.
3538
+ */
3539
+ constructor(tenantId, clientId, username, password, options = {}) {
3540
+ if (!tenantId || !clientId || !username || !password) {
3541
+ throw new Error("UsernamePasswordCredential: tenantId, clientId, username and password are required parameters. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");
3508
3542
  }
3509
- this.azureRegion = calculateRegionalAuthority(options.regionalAuthority);
3543
+ this.tenantId = tenantId;
3544
+ this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
3545
+ this.username = username;
3546
+ this.password = password;
3547
+ this.msalClient = createMsalClient(clientId, this.tenantId, Object.assign(Object.assign({}, options), { tokenCredentialOptions: options !== null && options !== void 0 ? options : {} }));
3510
3548
  }
3511
3549
  /**
3512
- * Generates a MSAL configuration that generally works for Node.js
3550
+ * Authenticates with Microsoft Entra ID and returns an access token if successful.
3551
+ * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
3552
+ *
3553
+ * If the user provided the option `disableAutomaticAuthentication`,
3554
+ * once the token can't be retrieved silently,
3555
+ * this method won't attempt to request user interaction to retrieve the token.
3556
+ *
3557
+ * @param scopes - The list of scopes for which the token will have access.
3558
+ * @param options - The options used to configure any requests this
3559
+ * TokenCredential implementation might make.
3513
3560
  */
3514
- defaultNodeMsalConfig(options) {
3515
- var _a;
3516
- const clientId = options.clientId || DeveloperSignOnClientId;
3517
- const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
3518
- this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;
3519
- const authority = getAuthority(tenantId, this.authorityHost);
3520
- this.identityClient = new IdentityClient(Object.assign(Object.assign({}, options.tokenCredentialOptions), { authorityHost: authority, loggingOptions: options.loggingOptions }));
3521
- const clientCapabilities = [];
3522
- return {
3523
- auth: {
3524
- clientId,
3525
- authority,
3526
- knownAuthorities: getKnownAuthorities(tenantId, authority, options.disableInstanceDiscovery),
3527
- clientCapabilities,
3528
- },
3529
- // Cache is defined in this.prepare();
3530
- system: {
3531
- networkClient: this.identityClient,
3532
- loggerOptions: {
3533
- loggerCallback: defaultLoggerCallback(options.logger),
3534
- logLevel: getMSALLogLevel(logger$r.getLogLevel()),
3535
- piiLoggingEnabled: (_a = options.loggingOptions) === null || _a === void 0 ? void 0 : _a.enableUnsafeSupportLogging,
3536
- },
3537
- },
3538
- };
3561
+ async getToken(scopes, options = {}) {
3562
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3563
+ newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger$7);
3564
+ const arrayScopes = ensureScopes(scopes);
3565
+ return this.msalClient.getTokenByUsernamePassword(arrayScopes, this.username, this.password, newOptions);
3566
+ });
3539
3567
  }
3540
- getApp(appType, enableCae) {
3541
- const app = enableCae ? this.caeApp : this.app;
3542
- if (appType === "publicFirst") {
3543
- return (app.public || app.confidential);
3568
+ }
3569
+
3570
+ // Copyright (c) Microsoft Corporation.
3571
+ // Licensed under the MIT license.
3572
+ /**
3573
+ * Contains the list of all supported environment variable names so that an
3574
+ * appropriate error message can be generated when no credentials can be
3575
+ * configured.
3576
+ *
3577
+ * @internal
3578
+ */
3579
+ const AllSupportedEnvironmentVariables = [
3580
+ "AZURE_TENANT_ID",
3581
+ "AZURE_CLIENT_ID",
3582
+ "AZURE_CLIENT_SECRET",
3583
+ "AZURE_CLIENT_CERTIFICATE_PATH",
3584
+ "AZURE_CLIENT_CERTIFICATE_PASSWORD",
3585
+ "AZURE_USERNAME",
3586
+ "AZURE_PASSWORD",
3587
+ "AZURE_ADDITIONALLY_ALLOWED_TENANTS",
3588
+ ];
3589
+ function getAdditionallyAllowedTenants() {
3590
+ var _a;
3591
+ const additionallyAllowedValues = (_a = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS) !== null && _a !== void 0 ? _a : "";
3592
+ return additionallyAllowedValues.split(";");
3593
+ }
3594
+ const credentialName$2 = "EnvironmentCredential";
3595
+ const logger$6 = credentialLogger(credentialName$2);
3596
+ /**
3597
+ * Enables authentication to Microsoft Entra ID using a client secret or certificate, or as a user
3598
+ * with a username and password.
3599
+ */
3600
+ class EnvironmentCredential {
3601
+ /**
3602
+ * Creates an instance of the EnvironmentCredential class and decides what credential to use depending on the available environment variables.
3603
+ *
3604
+ * Required environment variables:
3605
+ * - `AZURE_TENANT_ID`: The Microsoft Entra tenant (directory) ID.
3606
+ * - `AZURE_CLIENT_ID`: The client (application) ID of an App Registration in the tenant.
3607
+ *
3608
+ * If setting the AZURE_TENANT_ID, then you can also set the additionally allowed tenants
3609
+ * - `AZURE_ADDITIONALLY_ALLOWED_TENANTS`: For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens with a single semicolon delimited string. Use * to allow all tenants.
3610
+ *
3611
+ * Environment variables used for client credential authentication:
3612
+ * - `AZURE_CLIENT_SECRET`: A client secret that was generated for the App Registration.
3613
+ * - `AZURE_CLIENT_CERTIFICATE_PATH`: The path to a PEM certificate to use during the authentication, instead of the client secret.
3614
+ * - `AZURE_CLIENT_CERTIFICATE_PASSWORD`: (optional) password for the certificate file.
3615
+ *
3616
+ * Alternatively, users can provide environment variables for username and password authentication:
3617
+ * - `AZURE_USERNAME`: Username to authenticate with.
3618
+ * - `AZURE_PASSWORD`: Password to authenticate with.
3619
+ *
3620
+ * If the environment variables required to perform the authentication are missing, a {@link CredentialUnavailableError} will be thrown.
3621
+ * If the authentication fails, or if there's an unknown error, an {@link AuthenticationError} will be thrown.
3622
+ *
3623
+ * @param options - Options for configuring the client which makes the authentication request.
3624
+ */
3625
+ constructor(options) {
3626
+ // Keep track of any missing environment variables for error details
3627
+ this._credential = undefined;
3628
+ const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(", ");
3629
+ logger$6.info(`Found the following environment variables: ${assigned}`);
3630
+ const tenantId = process.env.AZURE_TENANT_ID, clientId = process.env.AZURE_CLIENT_ID, clientSecret = process.env.AZURE_CLIENT_SECRET;
3631
+ const additionallyAllowedTenantIds = getAdditionallyAllowedTenants();
3632
+ const newOptions = Object.assign(Object.assign({}, options), { additionallyAllowedTenantIds });
3633
+ if (tenantId) {
3634
+ checkTenantId(logger$6, tenantId);
3544
3635
  }
3545
- else if (appType === "confidentialFirst") {
3546
- return (app.confidential || app.public);
3636
+ if (tenantId && clientId && clientSecret) {
3637
+ logger$6.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`);
3638
+ this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions);
3639
+ return;
3547
3640
  }
3548
- else if (appType === "confidential") {
3549
- return app.confidential;
3641
+ const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;
3642
+ const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD;
3643
+ if (tenantId && clientId && certificatePath) {
3644
+ logger$6.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`);
3645
+ this._credential = new ClientCertificateCredential(tenantId, clientId, { certificatePath, certificatePassword }, newOptions);
3646
+ return;
3550
3647
  }
3551
- else {
3552
- return app.public;
3648
+ const username = process.env.AZURE_USERNAME;
3649
+ const password = process.env.AZURE_PASSWORD;
3650
+ if (tenantId && clientId && username && password) {
3651
+ logger$6.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`);
3652
+ this._credential = new UsernamePasswordCredential(tenantId, clientId, username, password, newOptions);
3553
3653
  }
3554
3654
  }
3555
3655
  /**
3556
- * Prepares the MSAL applications.
3656
+ * Authenticates with Microsoft Entra ID and returns an access token if successful.
3657
+ *
3658
+ * @param scopes - The list of scopes for which the token will have access.
3659
+ * @param options - Optional parameters. See {@link GetTokenOptions}.
3557
3660
  */
3558
- async init(options) {
3559
- if (options === null || options === void 0 ? void 0 : options.abortSignal) {
3560
- options.abortSignal.addEventListener("abort", () => {
3561
- // This will abort any pending request in the IdentityClient,
3562
- // based on the received or generated correlationId
3563
- this.identityClient.abortRequests(options.correlationId);
3564
- });
3565
- }
3566
- const app = (options === null || options === void 0 ? void 0 : options.enableCae) ? this.caeApp : this.app;
3567
- if (options === null || options === void 0 ? void 0 : options.enableCae) {
3568
- this.msalConfig.auth.clientCapabilities = ["cp1"];
3661
+ async getToken(scopes, options = {}) {
3662
+ return tracingClient.withSpan(`${credentialName$2}.getToken`, options, async (newOptions) => {
3663
+ if (this._credential) {
3664
+ try {
3665
+ const result = await this._credential.getToken(scopes, newOptions);
3666
+ logger$6.getToken.info(formatSuccess(scopes));
3667
+ return result;
3668
+ }
3669
+ catch (err) {
3670
+ const authenticationError = new AuthenticationError(400, {
3671
+ error: `${credentialName$2} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,
3672
+ error_description: err.message.toString().split("More details:").join(""),
3673
+ });
3674
+ logger$6.getToken.info(formatError(scopes, authenticationError));
3675
+ throw authenticationError;
3676
+ }
3677
+ }
3678
+ throw new CredentialUnavailableError(`${credentialName$2} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`);
3679
+ });
3680
+ }
3681
+ }
3682
+
3683
+ // Copyright (c) Microsoft Corporation.
3684
+ // Licensed under the MIT license.
3685
+ const logger$5 = credentialLogger("DefaultAzureCredential");
3686
+ /**
3687
+ * Creates a {@link ManagedIdentityCredential} from the provided options.
3688
+ * @param options - Options to configure the credential.
3689
+ *
3690
+ * @internal
3691
+ */
3692
+ function createDefaultManagedIdentityCredential(options = {}) {
3693
+ var _a, _b, _c, _d;
3694
+ (_a = options.retryOptions) !== null && _a !== void 0 ? _a : (options.retryOptions = {
3695
+ maxRetries: 5,
3696
+ retryDelayInMs: 800,
3697
+ });
3698
+ const managedIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _b !== void 0 ? _b : process.env.AZURE_CLIENT_ID;
3699
+ const workloadIdentityClientId = (_c = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _c !== void 0 ? _c : managedIdentityClientId;
3700
+ const managedResourceId = options === null || options === void 0 ? void 0 : options.managedIdentityResourceId;
3701
+ const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;
3702
+ const tenantId = (_d = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _d !== void 0 ? _d : process.env.AZURE_TENANT_ID;
3703
+ if (managedResourceId) {
3704
+ const managedIdentityResourceIdOptions = Object.assign(Object.assign({}, options), { resourceId: managedResourceId });
3705
+ return new ManagedIdentityCredential(managedIdentityResourceIdOptions);
3706
+ }
3707
+ if (workloadFile && workloadIdentityClientId) {
3708
+ const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId: tenantId });
3709
+ return new ManagedIdentityCredential(workloadIdentityClientId, workloadIdentityCredentialOptions);
3710
+ }
3711
+ if (managedIdentityClientId) {
3712
+ const managedIdentityClientOptions = Object.assign(Object.assign({}, options), { clientId: managedIdentityClientId });
3713
+ return new ManagedIdentityCredential(managedIdentityClientOptions);
3714
+ }
3715
+ // We may be able to return a UnavailableCredential here, but that may be a breaking change
3716
+ return new ManagedIdentityCredential(options);
3717
+ }
3718
+ /**
3719
+ * Creates a {@link WorkloadIdentityCredential} from the provided options.
3720
+ * @param options - Options to configure the credential.
3721
+ *
3722
+ * @internal
3723
+ */
3724
+ function createDefaultWorkloadIdentityCredential(options) {
3725
+ var _a, _b, _c;
3726
+ const managedIdentityClientId = (_a = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _a !== void 0 ? _a : process.env.AZURE_CLIENT_ID;
3727
+ const workloadIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _b !== void 0 ? _b : managedIdentityClientId;
3728
+ const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;
3729
+ const tenantId = (_c = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _c !== void 0 ? _c : process.env.AZURE_TENANT_ID;
3730
+ if (workloadFile && workloadIdentityClientId) {
3731
+ const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId, clientId: workloadIdentityClientId, tokenFilePath: workloadFile });
3732
+ return new WorkloadIdentityCredential(workloadIdentityCredentialOptions);
3733
+ }
3734
+ if (tenantId) {
3735
+ const workloadIdentityClientTenantOptions = Object.assign(Object.assign({}, options), { tenantId });
3736
+ return new WorkloadIdentityCredential(workloadIdentityClientTenantOptions);
3737
+ }
3738
+ // We may be able to return a UnavailableCredential here, but that may be a breaking change
3739
+ return new WorkloadIdentityCredential(options);
3740
+ }
3741
+ /**
3742
+ * Creates a {@link AzureDeveloperCliCredential} from the provided options.
3743
+ * @param options - Options to configure the credential.
3744
+ *
3745
+ * @internal
3746
+ */
3747
+ function createDefaultAzureDeveloperCliCredential(options = {}) {
3748
+ const processTimeoutInMs = options.processTimeoutInMs;
3749
+ return new AzureDeveloperCliCredential(Object.assign({ processTimeoutInMs }, options));
3750
+ }
3751
+ /**
3752
+ * Creates a {@link AzureCliCredential} from the provided options.
3753
+ * @param options - Options to configure the credential.
3754
+ *
3755
+ * @internal
3756
+ */
3757
+ function createDefaultAzureCliCredential(options = {}) {
3758
+ const processTimeoutInMs = options.processTimeoutInMs;
3759
+ return new AzureCliCredential(Object.assign({ processTimeoutInMs }, options));
3760
+ }
3761
+ /**
3762
+ * Creates a {@link AzurePowerShellCredential} from the provided options.
3763
+ * @param options - Options to configure the credential.
3764
+ *
3765
+ * @internal
3766
+ */
3767
+ function createDefaultAzurePowershellCredential(options = {}) {
3768
+ const processTimeoutInMs = options.processTimeoutInMs;
3769
+ return new AzurePowerShellCredential(Object.assign({ processTimeoutInMs }, options));
3770
+ }
3771
+ /**
3772
+ * Creates an {@link EnvironmentCredential} from the provided options.
3773
+ * @param options - Options to configure the credential.
3774
+ *
3775
+ * @internal
3776
+ */
3777
+ function createEnvironmentCredential(options = {}) {
3778
+ return new EnvironmentCredential(options);
3779
+ }
3780
+ /**
3781
+ * A no-op credential that logs the reason it was skipped if getToken is called.
3782
+ * @internal
3783
+ */
3784
+ class UnavailableDefaultCredential {
3785
+ constructor(credentialName, message) {
3786
+ this.credentialName = credentialName;
3787
+ this.credentialUnavailableErrorMessage = message;
3788
+ }
3789
+ getToken() {
3790
+ logger$5.getToken.info(`Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`);
3791
+ return Promise.resolve(null);
3792
+ }
3793
+ }
3794
+ /**
3795
+ * Provides a default {@link ChainedTokenCredential} configuration that should
3796
+ * work for most applications that use the Azure SDK.
3797
+ */
3798
+ class DefaultAzureCredential extends ChainedTokenCredential {
3799
+ constructor(options) {
3800
+ const credentialFunctions = [
3801
+ createEnvironmentCredential,
3802
+ createDefaultWorkloadIdentityCredential,
3803
+ createDefaultManagedIdentityCredential,
3804
+ createDefaultAzureCliCredential,
3805
+ createDefaultAzurePowershellCredential,
3806
+ createDefaultAzureDeveloperCliCredential,
3807
+ ];
3808
+ // DefaultCredential constructors should not throw, instead throwing on getToken() which is handled by ChainedTokenCredential.
3809
+ // When adding new credentials to the default chain, consider:
3810
+ // 1. Making the constructor parameters required and explicit
3811
+ // 2. Validating any required parameters in the factory function
3812
+ // 3. Returning a UnavailableDefaultCredential from the factory function if a credential is unavailable for any reason
3813
+ const credentials = credentialFunctions.map((createCredentialFn) => {
3814
+ try {
3815
+ return createCredentialFn(options);
3816
+ }
3817
+ catch (err) {
3818
+ logger$5.warning(`Skipped ${createCredentialFn.name} because of an error creating the credential: ${err}`);
3819
+ return new UnavailableDefaultCredential(createCredentialFn.name, err.message);
3820
+ }
3821
+ });
3822
+ super(...credentials);
3823
+ }
3824
+ }
3825
+
3826
+ // Copyright (c) Microsoft Corporation.
3827
+ // Licensed under the MIT license.
3828
+ /**
3829
+ * MSAL partial base client for Node.js.
3830
+ *
3831
+ * It completes the input configuration with some default values.
3832
+ * It also provides with utility protected methods that can be used from any of the clients,
3833
+ * which includes handlers for successful responses and errors.
3834
+ *
3835
+ * @internal
3836
+ */
3837
+ class MsalNode {
3838
+ constructor(options) {
3839
+ var _a, _b, _c, _d, _e, _f;
3840
+ this.app = {};
3841
+ this.caeApp = {};
3842
+ this.requiresConfidential = false;
3843
+ this.logger = options.logger;
3844
+ this.msalConfig = this.defaultNodeMsalConfig(options);
3845
+ this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
3846
+ this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds((_a = options === null || options === void 0 ? void 0 : options.tokenCredentialOptions) === null || _a === void 0 ? void 0 : _a.additionallyAllowedTenants);
3847
+ this.clientId = this.msalConfig.auth.clientId;
3848
+ if (options === null || options === void 0 ? void 0 : options.getAssertion) {
3849
+ this.getAssertion = options.getAssertion;
3850
+ }
3851
+ this.enableBroker = (_b = options === null || options === void 0 ? void 0 : options.brokerOptions) === null || _b === void 0 ? void 0 : _b.enabled;
3852
+ this.enableMsaPassthrough = (_c = options === null || options === void 0 ? void 0 : options.brokerOptions) === null || _c === void 0 ? void 0 : _c.legacyEnableMsaPassthrough;
3853
+ this.parentWindowHandle = (_d = options.brokerOptions) === null || _d === void 0 ? void 0 : _d.parentWindowHandle;
3854
+ // If persistence has been configured
3855
+ if (persistenceProvider !== undefined && ((_e = options.tokenCachePersistenceOptions) === null || _e === void 0 ? void 0 : _e.enabled)) {
3856
+ const cacheBaseName = options.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME;
3857
+ const nonCaeOptions = Object.assign({ name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions);
3858
+ const caeOptions = Object.assign({ name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions);
3859
+ this.createCachePlugin = () => persistenceProvider(nonCaeOptions);
3860
+ this.createCachePluginCae = () => persistenceProvider(caeOptions);
3861
+ }
3862
+ else if ((_f = options.tokenCachePersistenceOptions) === null || _f === void 0 ? void 0 : _f.enabled) {
3863
+ throw new Error([
3864
+ "Persistent token caching was requested, but no persistence provider was configured.",
3865
+ "You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)",
3866
+ "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",
3867
+ "`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.",
3868
+ ].join(" "));
3869
+ }
3870
+ // If broker has not been configured
3871
+ if (!hasNativeBroker() && this.enableBroker) {
3872
+ throw new Error([
3873
+ "Broker for WAM was requested to be enabled, but no native broker was configured.",
3874
+ "You must install the identity-broker plugin package (`npm install --save @azure/identity-broker`)",
3875
+ "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",
3876
+ "`useIdentityPlugin(createNativeBrokerPlugin())` before using `enableBroker`.",
3877
+ ].join(" "));
3878
+ }
3879
+ this.azureRegion = calculateRegionalAuthority(options.regionalAuthority);
3880
+ }
3881
+ /**
3882
+ * Generates a MSAL configuration that generally works for Node.js
3883
+ */
3884
+ defaultNodeMsalConfig(options) {
3885
+ var _a;
3886
+ const clientId = options.clientId || DeveloperSignOnClientId;
3887
+ const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
3888
+ this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;
3889
+ const authority = getAuthority(tenantId, this.authorityHost);
3890
+ this.identityClient = new IdentityClient(Object.assign(Object.assign({}, options.tokenCredentialOptions), { authorityHost: authority, loggingOptions: options.loggingOptions }));
3891
+ const clientCapabilities = [];
3892
+ return {
3893
+ auth: {
3894
+ clientId,
3895
+ authority,
3896
+ knownAuthorities: getKnownAuthorities(tenantId, authority, options.disableInstanceDiscovery),
3897
+ clientCapabilities,
3898
+ },
3899
+ // Cache is defined in this.prepare();
3900
+ system: {
3901
+ networkClient: this.identityClient,
3902
+ loggerOptions: {
3903
+ loggerCallback: defaultLoggerCallback(options.logger),
3904
+ logLevel: getMSALLogLevel(logger$r.getLogLevel()),
3905
+ piiLoggingEnabled: (_a = options.loggingOptions) === null || _a === void 0 ? void 0 : _a.enableUnsafeSupportLogging,
3906
+ },
3907
+ },
3908
+ };
3909
+ }
3910
+ getApp(appType, enableCae) {
3911
+ const app = enableCae ? this.caeApp : this.app;
3912
+ if (appType === "publicFirst") {
3913
+ return (app.public || app.confidential);
3914
+ }
3915
+ else if (appType === "confidentialFirst") {
3916
+ return (app.confidential || app.public);
3917
+ }
3918
+ else if (appType === "confidential") {
3919
+ return app.confidential;
3920
+ }
3921
+ else {
3922
+ return app.public;
3923
+ }
3924
+ }
3925
+ /**
3926
+ * Prepares the MSAL applications.
3927
+ */
3928
+ async init(options) {
3929
+ if (options === null || options === void 0 ? void 0 : options.abortSignal) {
3930
+ options.abortSignal.addEventListener("abort", () => {
3931
+ // This will abort any pending request in the IdentityClient,
3932
+ // based on the received or generated correlationId
3933
+ this.identityClient.abortRequests(options.correlationId);
3934
+ });
3935
+ }
3936
+ const app = (options === null || options === void 0 ? void 0 : options.enableCae) ? this.caeApp : this.app;
3937
+ if (options === null || options === void 0 ? void 0 : options.enableCae) {
3938
+ this.msalConfig.auth.clientCapabilities = ["cp1"];
3569
3939
  }
3570
3940
  if (app.public || app.confidential) {
3571
3941
  return;
@@ -3691,417 +4061,76 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
3691
4061
  silentRequest.tokenQueryParameters["msal_request_type"] = "consumer_passthrough";
3692
4062
  }
3693
4063
  }
3694
- try {
3695
- this.logger.info("Attempting to acquire token silently");
3696
- /**
3697
- * The following code to retrieve all accounts is done as a workaround in an attempt to force the
3698
- * refresh of the token cache with the token and the account passed in through the
3699
- * `authenticationRecord` parameter. See issue - https://github.com/Azure/azure-sdk-for-js/issues/24349#issuecomment-1496715651
3700
- * This workaround serves as a workaround for silent authentication not happening when authenticationRecord is passed.
3701
- */
3702
- await ((_a = this.getApp("publicFirst", options === null || options === void 0 ? void 0 : options.enableCae)) === null || _a === void 0 ? void 0 : _a.getTokenCache().getAllAccounts());
3703
- const response = (_c = (await ((_b = this.getApp("confidential", options === null || options === void 0 ? void 0 : options.enableCae)) === null || _b === void 0 ? void 0 : _b.acquireTokenSilent(silentRequest)))) !== null && _c !== void 0 ? _c : (await this.getApp("public", options === null || options === void 0 ? void 0 : options.enableCae).acquireTokenSilent(silentRequest));
3704
- return this.handleResult(scopes, response || undefined);
3705
- }
3706
- catch (err) {
3707
- throw handleMsalError(scopes, err, options);
3708
- }
3709
- }
3710
- /**
3711
- * Wrapper around each MSAL flow get token operation: doGetToken.
3712
- * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.
3713
- */
3714
- async getToken(scopes, options = {}) {
3715
- const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds) ||
3716
- this.tenantId;
3717
- options.authority = getAuthority(tenantId, this.authorityHost);
3718
- options.correlationId = (options === null || options === void 0 ? void 0 : options.correlationId) || randomUUID();
3719
- await this.init(options);
3720
- try {
3721
- // MSAL now caches tokens based on their claims,
3722
- // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent
3723
- // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533
3724
- const optionsClaims = options.claims;
3725
- if (optionsClaims) {
3726
- this.cachedClaims = optionsClaims;
3727
- }
3728
- if (this.cachedClaims && !optionsClaims) {
3729
- options.claims = this.cachedClaims;
3730
- }
3731
- // We don't return the promise since we want to catch errors right here.
3732
- return await this.getTokenSilent(scopes, options);
3733
- }
3734
- catch (err) {
3735
- if (err.name !== "AuthenticationRequiredError") {
3736
- throw err;
3737
- }
3738
- if (options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication) {
3739
- throw new AuthenticationRequiredError({
3740
- scopes,
3741
- getTokenOptions: options,
3742
- message: "Automatic authentication has been disabled. You may call the authentication() method.",
3743
- });
3744
- }
3745
- this.logger.info(`Silent authentication failed, falling back to interactive method.`);
3746
- return this.doGetToken(scopes, options);
3747
- }
3748
- }
3749
- /**
3750
- * Handles the MSAL authentication result.
3751
- * If the result has an account, we update the local account reference.
3752
- * If the token received is invalid, an error will be thrown depending on what's missing.
3753
- */
3754
- handleResult(scopes, result, getTokenOptions) {
3755
- if (result === null || result === void 0 ? void 0 : result.account) {
3756
- this.account = msalToPublic(this.clientId, result.account);
3757
- }
3758
- ensureValidMsalToken(scopes, result, getTokenOptions);
3759
- this.logger.getToken.info(formatSuccess(scopes));
3760
- return {
3761
- token: result.accessToken,
3762
- expiresOnTimestamp: result.expiresOn.getTime(),
3763
- };
3764
- }
3765
- }
3766
-
3767
- // Copyright (c) Microsoft Corporation.
3768
- // Licensed under the MIT license.
3769
- /**
3770
- * MSAL username and password client. Calls to the MSAL's public application's `acquireTokenByUsernamePassword` during `doGetToken`.
3771
- * @internal
3772
- */
3773
- class MsalUsernamePassword extends MsalNode {
3774
- constructor(options) {
3775
- super(options);
3776
- this.username = options.username;
3777
- this.password = options.password;
3778
- }
3779
- async doGetToken(scopes, options) {
3780
- try {
3781
- const requestOptions = {
3782
- scopes,
3783
- username: this.username,
3784
- password: this.password,
3785
- correlationId: options === null || options === void 0 ? void 0 : options.correlationId,
3786
- authority: options === null || options === void 0 ? void 0 : options.authority,
3787
- claims: options === null || options === void 0 ? void 0 : options.claims,
3788
- };
3789
- const result = await this.getApp("public", options === null || options === void 0 ? void 0 : options.enableCae).acquireTokenByUsernamePassword(requestOptions);
3790
- return this.handleResult(scopes, result || undefined);
3791
- }
3792
- catch (error) {
3793
- throw handleMsalError(scopes, error, options);
3794
- }
3795
- }
3796
- }
3797
-
3798
- // Copyright (c) Microsoft Corporation.
3799
- // Licensed under the MIT license.
3800
- const logger$7 = credentialLogger("UsernamePasswordCredential");
3801
- /**
3802
- * Enables authentication to Microsoft Entra ID with a user's
3803
- * username and password. This credential requires a high degree of
3804
- * trust so you should only use it when other, more secure credential
3805
- * types can't be used.
3806
- */
3807
- class UsernamePasswordCredential {
3808
- /**
3809
- * Creates an instance of the UsernamePasswordCredential with the details
3810
- * needed to authenticate against Microsoft Entra ID with a username
3811
- * and password.
3812
- *
3813
- * @param tenantId - The Microsoft Entra tenant (directory).
3814
- * @param clientId - The client (application) ID of an App Registration in the tenant.
3815
- * @param username - The user account's e-mail address (user name).
3816
- * @param password - The user account's account password
3817
- * @param options - Options for configuring the client which makes the authentication request.
3818
- */
3819
- constructor(tenantId, clientId, username, password, options = {}) {
3820
- if (!tenantId || !clientId || !username || !password) {
3821
- throw new Error("UsernamePasswordCredential: tenantId, clientId, username and password are required parameters. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");
3822
- }
3823
- this.tenantId = tenantId;
3824
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
3825
- this.msalFlow = new MsalUsernamePassword(Object.assign(Object.assign({}, options), { logger: logger$7,
3826
- clientId,
3827
- tenantId,
3828
- username,
3829
- password, tokenCredentialOptions: options || {} }));
3830
- }
3831
- /**
3832
- * Authenticates with Microsoft Entra ID and returns an access token if successful.
3833
- * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
3834
- *
3835
- * If the user provided the option `disableAutomaticAuthentication`,
3836
- * once the token can't be retrieved silently,
3837
- * this method won't attempt to request user interaction to retrieve the token.
3838
- *
3839
- * @param scopes - The list of scopes for which the token will have access.
3840
- * @param options - The options used to configure any requests this
3841
- * TokenCredential implementation might make.
3842
- */
3843
- async getToken(scopes, options = {}) {
3844
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3845
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger$7);
3846
- const arrayScopes = ensureScopes(scopes);
3847
- return this.msalFlow.getToken(arrayScopes, newOptions);
3848
- });
3849
- }
3850
- }
3851
-
3852
- // Copyright (c) Microsoft Corporation.
3853
- // Licensed under the MIT license.
3854
- /**
3855
- * Contains the list of all supported environment variable names so that an
3856
- * appropriate error message can be generated when no credentials can be
3857
- * configured.
3858
- *
3859
- * @internal
3860
- */
3861
- const AllSupportedEnvironmentVariables = [
3862
- "AZURE_TENANT_ID",
3863
- "AZURE_CLIENT_ID",
3864
- "AZURE_CLIENT_SECRET",
3865
- "AZURE_CLIENT_CERTIFICATE_PATH",
3866
- "AZURE_CLIENT_CERTIFICATE_PASSWORD",
3867
- "AZURE_USERNAME",
3868
- "AZURE_PASSWORD",
3869
- "AZURE_ADDITIONALLY_ALLOWED_TENANTS",
3870
- ];
3871
- function getAdditionallyAllowedTenants() {
3872
- var _a;
3873
- const additionallyAllowedValues = (_a = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS) !== null && _a !== void 0 ? _a : "";
3874
- return additionallyAllowedValues.split(";");
3875
- }
3876
- const credentialName$2 = "EnvironmentCredential";
3877
- const logger$6 = credentialLogger(credentialName$2);
3878
- /**
3879
- * Enables authentication to Microsoft Entra ID using a client secret or certificate, or as a user
3880
- * with a username and password.
3881
- */
3882
- class EnvironmentCredential {
3883
- /**
3884
- * Creates an instance of the EnvironmentCredential class and decides what credential to use depending on the available environment variables.
3885
- *
3886
- * Required environment variables:
3887
- * - `AZURE_TENANT_ID`: The Microsoft Entra tenant (directory) ID.
3888
- * - `AZURE_CLIENT_ID`: The client (application) ID of an App Registration in the tenant.
3889
- *
3890
- * If setting the AZURE_TENANT_ID, then you can also set the additionally allowed tenants
3891
- * - `AZURE_ADDITIONALLY_ALLOWED_TENANTS`: For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens with a single semicolon delimited string. Use * to allow all tenants.
3892
- *
3893
- * Environment variables used for client credential authentication:
3894
- * - `AZURE_CLIENT_SECRET`: A client secret that was generated for the App Registration.
3895
- * - `AZURE_CLIENT_CERTIFICATE_PATH`: The path to a PEM certificate to use during the authentication, instead of the client secret.
3896
- * - `AZURE_CLIENT_CERTIFICATE_PASSWORD`: (optional) password for the certificate file.
3897
- *
3898
- * Alternatively, users can provide environment variables for username and password authentication:
3899
- * - `AZURE_USERNAME`: Username to authenticate with.
3900
- * - `AZURE_PASSWORD`: Password to authenticate with.
3901
- *
3902
- * If the environment variables required to perform the authentication are missing, a {@link CredentialUnavailableError} will be thrown.
3903
- * If the authentication fails, or if there's an unknown error, an {@link AuthenticationError} will be thrown.
3904
- *
3905
- * @param options - Options for configuring the client which makes the authentication request.
3906
- */
3907
- constructor(options) {
3908
- // Keep track of any missing environment variables for error details
3909
- this._credential = undefined;
3910
- const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(", ");
3911
- logger$6.info(`Found the following environment variables: ${assigned}`);
3912
- const tenantId = process.env.AZURE_TENANT_ID, clientId = process.env.AZURE_CLIENT_ID, clientSecret = process.env.AZURE_CLIENT_SECRET;
3913
- const additionallyAllowedTenantIds = getAdditionallyAllowedTenants();
3914
- const newOptions = Object.assign(Object.assign({}, options), { additionallyAllowedTenantIds });
3915
- if (tenantId) {
3916
- checkTenantId(logger$6, tenantId);
3917
- }
3918
- if (tenantId && clientId && clientSecret) {
3919
- logger$6.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`);
3920
- this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions);
3921
- return;
3922
- }
3923
- const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;
3924
- const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD;
3925
- if (tenantId && clientId && certificatePath) {
3926
- logger$6.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`);
3927
- this._credential = new ClientCertificateCredential(tenantId, clientId, { certificatePath, certificatePassword }, newOptions);
3928
- return;
3929
- }
3930
- const username = process.env.AZURE_USERNAME;
3931
- const password = process.env.AZURE_PASSWORD;
3932
- if (tenantId && clientId && username && password) {
3933
- logger$6.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`);
3934
- this._credential = new UsernamePasswordCredential(tenantId, clientId, username, password, newOptions);
4064
+ try {
4065
+ this.logger.info("Attempting to acquire token silently");
4066
+ /**
4067
+ * The following code to retrieve all accounts is done as a workaround in an attempt to force the
4068
+ * refresh of the token cache with the token and the account passed in through the
4069
+ * `authenticationRecord` parameter. See issue - https://github.com/Azure/azure-sdk-for-js/issues/24349#issuecomment-1496715651
4070
+ * This workaround serves as a workaround for silent authentication not happening when authenticationRecord is passed.
4071
+ */
4072
+ await ((_a = this.getApp("publicFirst", options === null || options === void 0 ? void 0 : options.enableCae)) === null || _a === void 0 ? void 0 : _a.getTokenCache().getAllAccounts());
4073
+ const response = (_c = (await ((_b = this.getApp("confidential", options === null || options === void 0 ? void 0 : options.enableCae)) === null || _b === void 0 ? void 0 : _b.acquireTokenSilent(silentRequest)))) !== null && _c !== void 0 ? _c : (await this.getApp("public", options === null || options === void 0 ? void 0 : options.enableCae).acquireTokenSilent(silentRequest));
4074
+ return this.handleResult(scopes, response || undefined);
4075
+ }
4076
+ catch (err) {
4077
+ throw handleMsalError(scopes, err, options);
3935
4078
  }
3936
4079
  }
3937
4080
  /**
3938
- * Authenticates with Microsoft Entra ID and returns an access token if successful.
3939
- *
3940
- * @param scopes - The list of scopes for which the token will have access.
3941
- * @param options - Optional parameters. See {@link GetTokenOptions}.
4081
+ * Wrapper around each MSAL flow get token operation: doGetToken.
4082
+ * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.
3942
4083
  */
3943
4084
  async getToken(scopes, options = {}) {
3944
- return tracingClient.withSpan(`${credentialName$2}.getToken`, options, async (newOptions) => {
3945
- if (this._credential) {
3946
- try {
3947
- const result = await this._credential.getToken(scopes, newOptions);
3948
- logger$6.getToken.info(formatSuccess(scopes));
3949
- return result;
3950
- }
3951
- catch (err) {
3952
- const authenticationError = new AuthenticationError(400, {
3953
- error: `${credentialName$2} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,
3954
- error_description: err.message.toString().split("More details:").join(""),
3955
- });
3956
- logger$6.getToken.info(formatError(scopes, authenticationError));
3957
- throw authenticationError;
3958
- }
4085
+ const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds) ||
4086
+ this.tenantId;
4087
+ options.authority = getAuthority(tenantId, this.authorityHost);
4088
+ options.correlationId = (options === null || options === void 0 ? void 0 : options.correlationId) || randomUUID();
4089
+ await this.init(options);
4090
+ try {
4091
+ // MSAL now caches tokens based on their claims,
4092
+ // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent
4093
+ // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533
4094
+ const optionsClaims = options.claims;
4095
+ if (optionsClaims) {
4096
+ this.cachedClaims = optionsClaims;
3959
4097
  }
3960
- throw new CredentialUnavailableError(`${credentialName$2} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`);
3961
- });
3962
- }
3963
- }
3964
-
3965
- // Copyright (c) Microsoft Corporation.
3966
- // Licensed under the MIT license.
3967
- const logger$5 = credentialLogger("DefaultAzureCredential");
3968
- /**
3969
- * Creates a {@link ManagedIdentityCredential} from the provided options.
3970
- * @param options - Options to configure the credential.
3971
- *
3972
- * @internal
3973
- */
3974
- function createDefaultManagedIdentityCredential(options = {}) {
3975
- var _a, _b, _c, _d;
3976
- (_a = options.retryOptions) !== null && _a !== void 0 ? _a : (options.retryOptions = {
3977
- maxRetries: 5,
3978
- retryDelayInMs: 800,
3979
- });
3980
- const managedIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _b !== void 0 ? _b : process.env.AZURE_CLIENT_ID;
3981
- const workloadIdentityClientId = (_c = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _c !== void 0 ? _c : managedIdentityClientId;
3982
- const managedResourceId = options === null || options === void 0 ? void 0 : options.managedIdentityResourceId;
3983
- const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;
3984
- const tenantId = (_d = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _d !== void 0 ? _d : process.env.AZURE_TENANT_ID;
3985
- if (managedResourceId) {
3986
- const managedIdentityResourceIdOptions = Object.assign(Object.assign({}, options), { resourceId: managedResourceId });
3987
- return new ManagedIdentityCredential(managedIdentityResourceIdOptions);
3988
- }
3989
- if (workloadFile && workloadIdentityClientId) {
3990
- const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId: tenantId });
3991
- return new ManagedIdentityCredential(workloadIdentityClientId, workloadIdentityCredentialOptions);
3992
- }
3993
- if (managedIdentityClientId) {
3994
- const managedIdentityClientOptions = Object.assign(Object.assign({}, options), { clientId: managedIdentityClientId });
3995
- return new ManagedIdentityCredential(managedIdentityClientOptions);
3996
- }
3997
- // We may be able to return a UnavailableCredential here, but that may be a breaking change
3998
- return new ManagedIdentityCredential(options);
3999
- }
4000
- /**
4001
- * Creates a {@link WorkloadIdentityCredential} from the provided options.
4002
- * @param options - Options to configure the credential.
4003
- *
4004
- * @internal
4005
- */
4006
- function createDefaultWorkloadIdentityCredential(options) {
4007
- var _a, _b, _c;
4008
- const managedIdentityClientId = (_a = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _a !== void 0 ? _a : process.env.AZURE_CLIENT_ID;
4009
- const workloadIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _b !== void 0 ? _b : managedIdentityClientId;
4010
- const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;
4011
- const tenantId = (_c = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _c !== void 0 ? _c : process.env.AZURE_TENANT_ID;
4012
- if (workloadFile && workloadIdentityClientId) {
4013
- const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId, clientId: workloadIdentityClientId, tokenFilePath: workloadFile });
4014
- return new WorkloadIdentityCredential(workloadIdentityCredentialOptions);
4015
- }
4016
- if (tenantId) {
4017
- const workloadIdentityClientTenantOptions = Object.assign(Object.assign({}, options), { tenantId });
4018
- return new WorkloadIdentityCredential(workloadIdentityClientTenantOptions);
4019
- }
4020
- // We may be able to return a UnavailableCredential here, but that may be a breaking change
4021
- return new WorkloadIdentityCredential(options);
4022
- }
4023
- /**
4024
- * Creates a {@link AzureDeveloperCliCredential} from the provided options.
4025
- * @param options - Options to configure the credential.
4026
- *
4027
- * @internal
4028
- */
4029
- function createDefaultAzureDeveloperCliCredential(options = {}) {
4030
- const processTimeoutInMs = options.processTimeoutInMs;
4031
- return new AzureDeveloperCliCredential(Object.assign({ processTimeoutInMs }, options));
4032
- }
4033
- /**
4034
- * Creates a {@link AzureCliCredential} from the provided options.
4035
- * @param options - Options to configure the credential.
4036
- *
4037
- * @internal
4038
- */
4039
- function createDefaultAzureCliCredential(options = {}) {
4040
- const processTimeoutInMs = options.processTimeoutInMs;
4041
- return new AzureCliCredential(Object.assign({ processTimeoutInMs }, options));
4042
- }
4043
- /**
4044
- * Creates a {@link AzurePowerShellCredential} from the provided options.
4045
- * @param options - Options to configure the credential.
4046
- *
4047
- * @internal
4048
- */
4049
- function createDefaultAzurePowershellCredential(options = {}) {
4050
- const processTimeoutInMs = options.processTimeoutInMs;
4051
- return new AzurePowerShellCredential(Object.assign({ processTimeoutInMs }, options));
4052
- }
4053
- /**
4054
- * Creates an {@link EnvironmentCredential} from the provided options.
4055
- * @param options - Options to configure the credential.
4056
- *
4057
- * @internal
4058
- */
4059
- function createEnvironmentCredential(options = {}) {
4060
- return new EnvironmentCredential(options);
4061
- }
4062
- /**
4063
- * A no-op credential that logs the reason it was skipped if getToken is called.
4064
- * @internal
4065
- */
4066
- class UnavailableDefaultCredential {
4067
- constructor(credentialName, message) {
4068
- this.credentialName = credentialName;
4069
- this.credentialUnavailableErrorMessage = message;
4070
- }
4071
- getToken() {
4072
- logger$5.getToken.info(`Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`);
4073
- return Promise.resolve(null);
4074
- }
4075
- }
4076
- /**
4077
- * Provides a default {@link ChainedTokenCredential} configuration that should
4078
- * work for most applications that use the Azure SDK.
4079
- */
4080
- class DefaultAzureCredential extends ChainedTokenCredential {
4081
- constructor(options) {
4082
- const credentialFunctions = [
4083
- createEnvironmentCredential,
4084
- createDefaultWorkloadIdentityCredential,
4085
- createDefaultManagedIdentityCredential,
4086
- createDefaultAzureCliCredential,
4087
- createDefaultAzurePowershellCredential,
4088
- createDefaultAzureDeveloperCliCredential,
4089
- ];
4090
- // DefaultCredential constructors should not throw, instead throwing on getToken() which is handled by ChainedTokenCredential.
4091
- // When adding new credentials to the default chain, consider:
4092
- // 1. Making the constructor parameters required and explicit
4093
- // 2. Validating any required parameters in the factory function
4094
- // 3. Returning a UnavailableDefaultCredential from the factory function if a credential is unavailable for any reason
4095
- const credentials = credentialFunctions.map((createCredentialFn) => {
4096
- try {
4097
- return createCredentialFn(options);
4098
+ if (this.cachedClaims && !optionsClaims) {
4099
+ options.claims = this.cachedClaims;
4098
4100
  }
4099
- catch (err) {
4100
- logger$5.warning(`Skipped ${createCredentialFn.name} because of an error creating the credential: ${err}`);
4101
- return new UnavailableDefaultCredential(createCredentialFn.name, err.message);
4101
+ // We don't return the promise since we want to catch errors right here.
4102
+ return await this.getTokenSilent(scopes, options);
4103
+ }
4104
+ catch (err) {
4105
+ if (err.name !== "AuthenticationRequiredError") {
4106
+ throw err;
4102
4107
  }
4103
- });
4104
- super(...credentials);
4108
+ if (options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication) {
4109
+ throw new AuthenticationRequiredError({
4110
+ scopes,
4111
+ getTokenOptions: options,
4112
+ message: "Automatic authentication has been disabled. You may call the authentication() method.",
4113
+ });
4114
+ }
4115
+ this.logger.info(`Silent authentication failed, falling back to interactive method.`);
4116
+ return this.doGetToken(scopes, options);
4117
+ }
4118
+ }
4119
+ /**
4120
+ * Handles the MSAL authentication result.
4121
+ * If the result has an account, we update the local account reference.
4122
+ * If the token received is invalid, an error will be thrown depending on what's missing.
4123
+ */
4124
+ handleResult(scopes, result, getTokenOptions) {
4125
+ if (result === null || result === void 0 ? void 0 : result.account) {
4126
+ this.account = msalToPublic(this.clientId, result.account);
4127
+ }
4128
+ ensureValidMsalToken(scopes, result, getTokenOptions);
4129
+ this.logger.getToken.info(formatSuccess(scopes));
4130
+ return {
4131
+ token: result.accessToken,
4132
+ expiresOnTimestamp: result.expiresOn.getTime(),
4133
+ };
4105
4134
  }
4106
4135
  }
4107
4136
 
@@ -4344,7 +4373,7 @@ class DeviceCodeCredential {
4344
4373
  const clientId = (_a = options === null || options === void 0 ? void 0 : options.clientId) !== null && _a !== void 0 ? _a : DeveloperSignOnClientId;
4345
4374
  const tenantId = resolveTenantId(logger$3, options === null || options === void 0 ? void 0 : options.tenantId, clientId);
4346
4375
  this.userPromptCallback = (_b = options === null || options === void 0 ? void 0 : options.userPromptCallback) !== null && _b !== void 0 ? _b : defaultDeviceCodePromptCallback;
4347
- this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { tokenCredentialOptions: options || {} }));
4376
+ this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger: logger$3, tokenCredentialOptions: options || {} }));
4348
4377
  this.disableAutomaticAuthentication = options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication;
4349
4378
  }
4350
4379
  /**
@@ -4510,50 +4539,6 @@ class AzurePipelinesCredential {
4510
4539
  }
4511
4540
  }
4512
4541
 
4513
- // Copyright (c) Microsoft Corporation.
4514
- // Licensed under the MIT license.
4515
- /**
4516
- * This MSAL client sets up a web server to listen for redirect callbacks, then calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`
4517
- * to trigger the authentication flow, and then respond based on the values obtained from the redirect callback
4518
- * @internal
4519
- */
4520
- class MsalAuthorizationCode extends MsalNode {
4521
- constructor(options) {
4522
- super(options);
4523
- this.logger = credentialLogger("Node.js MSAL Authorization Code");
4524
- this.redirectUri = options.redirectUri;
4525
- this.authorizationCode = options.authorizationCode;
4526
- if (options.clientSecret) {
4527
- this.msalConfig.auth.clientSecret = options.clientSecret;
4528
- }
4529
- }
4530
- async getAuthCodeUrl(options) {
4531
- await this.init();
4532
- return this.getApp("confidentialFirst", options.enableCae).getAuthCodeUrl({
4533
- scopes: options.scopes,
4534
- redirectUri: options.redirectUri,
4535
- });
4536
- }
4537
- async doGetToken(scopes, options) {
4538
- try {
4539
- const result = await this.getApp("confidentialFirst", options === null || options === void 0 ? void 0 : options.enableCae).acquireTokenByCode({
4540
- scopes,
4541
- redirectUri: this.redirectUri,
4542
- code: this.authorizationCode,
4543
- correlationId: options === null || options === void 0 ? void 0 : options.correlationId,
4544
- authority: options === null || options === void 0 ? void 0 : options.authority,
4545
- claims: options === null || options === void 0 ? void 0 : options.claims,
4546
- });
4547
- // The Client Credential flow does not return an account,
4548
- // so each time getToken gets called, we will have to acquire a new token through the service.
4549
- return this.handleResult(scopes, result || undefined);
4550
- }
4551
- catch (err) {
4552
- throw handleMsalError(scopes, err, options);
4553
- }
4554
- }
4555
- }
4556
-
4557
4542
  // Copyright (c) Microsoft Corporation.
4558
4543
  // Licensed under the MIT license.
4559
4544
  const logger$1 = credentialLogger("AuthorizationCodeCredential");
@@ -4571,7 +4556,7 @@ class AuthorizationCodeCredential {
4571
4556
  */
4572
4557
  constructor(tenantId, clientId, clientSecretOrAuthorizationCode, authorizationCodeOrRedirectUri, redirectUriOrOptions, options) {
4573
4558
  checkTenantId(logger$1, tenantId);
4574
- let clientSecret = clientSecretOrAuthorizationCode;
4559
+ this.clientSecret = clientSecretOrAuthorizationCode;
4575
4560
  if (typeof redirectUriOrOptions === "string") {
4576
4561
  // the clientId+clientSecret constructor
4577
4562
  this.authorizationCode = authorizationCodeOrRedirectUri;
@@ -4582,15 +4567,13 @@ class AuthorizationCodeCredential {
4582
4567
  // clientId only
4583
4568
  this.authorizationCode = clientSecretOrAuthorizationCode;
4584
4569
  this.redirectUri = authorizationCodeOrRedirectUri;
4585
- clientSecret = undefined;
4570
+ this.clientSecret = undefined;
4586
4571
  options = redirectUriOrOptions;
4587
4572
  }
4588
4573
  // TODO: Validate tenant if provided
4589
4574
  this.tenantId = tenantId;
4590
4575
  this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
4591
- this.msalFlow = new MsalAuthorizationCode(Object.assign(Object.assign({}, options), { clientSecret,
4592
- clientId,
4593
- tenantId, tokenCredentialOptions: options || {}, logger: logger$1, redirectUri: this.redirectUri, authorizationCode: this.authorizationCode }));
4576
+ this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger: logger$1, tokenCredentialOptions: options !== null && options !== void 0 ? options : {} }));
4594
4577
  }
4595
4578
  /**
4596
4579
  * Authenticates with Microsoft Entra ID and returns an access token if successful.
@@ -4605,7 +4588,7 @@ class AuthorizationCodeCredential {
4605
4588
  const tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds);
4606
4589
  newOptions.tenantId = tenantId;
4607
4590
  const arrayScopes = ensureScopes(scopes);
4608
- return this.msalFlow.getToken(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
4591
+ return this.msalClient.getTokenByAuthorizationCode(arrayScopes, this.redirectUri, this.authorizationCode, this.clientSecret, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
4609
4592
  });
4610
4593
  }
4611
4594
  }