@azure/identity 2.1.0-alpha.20220315.2 → 2.1.0-alpha.20220322.5

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.

Potentially problematic release.


This version of @azure/identity might be problematic. Click here for more details.

package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ var coreClient = require('@azure/core-client');
8
8
  var coreUtil = require('@azure/core-util');
9
9
  var coreRestPipeline = require('@azure/core-rest-pipeline');
10
10
  var abortController = require('@azure/abort-controller');
11
- var logger$k = require('@azure/logger');
11
+ var logger$l = require('@azure/logger');
12
12
  var msalCommon = require('@azure/msal-common');
13
13
  var uuid = require('uuid');
14
14
  var fs = require('fs');
@@ -273,7 +273,7 @@ async function trace(operationName, options, fn, createSpanFn = createSpan) {
273
273
  /**
274
274
  * The AzureLogger used for all clients within the identity package
275
275
  */
276
- const logger$j = logger$k.createClientLogger("identity");
276
+ const logger$k = logger$l.createClientLogger("identity");
277
277
  /**
278
278
  * Separates a list of environment variable names into a plain object with two arrays: an array of missing environment variables and another array with assigned environment variables.
279
279
  * @param supportedEnvVars - List of environment variable names
@@ -313,7 +313,7 @@ function formatError(scope, error) {
313
313
  * `[title] => [message]`
314
314
  *
315
315
  */
316
- function credentialLoggerInstance(title, parent, log = logger$j) {
316
+ function credentialLoggerInstance(title, parent, log = logger$k) {
317
317
  const fullTitle = parent ? `${parent.fullTitle} ${title}` : title;
318
318
  function info(message) {
319
319
  log.info(`${fullTitle} =>`, message);
@@ -338,7 +338,7 @@ function credentialLoggerInstance(title, parent, log = logger$j) {
338
338
  * `[title] => getToken() => [message]`
339
339
  *
340
340
  */
341
- function credentialLogger(title, log = logger$j) {
341
+ function credentialLogger(title, log = logger$k) {
342
342
  const credLogger = credentialLoggerInstance(title, undefined, log);
343
343
  return Object.assign(Object.assign({}, credLogger), { parent: log, getToken: credentialLoggerInstance("=> getToken()", credLogger, log) });
344
344
  }
@@ -367,7 +367,7 @@ function getIdentityClientAuthorityHost(options) {
367
367
  */
368
368
  class IdentityClient extends coreClient.ServiceClient {
369
369
  constructor(options) {
370
- var _a;
370
+ var _a, _b;
371
371
  const packageDetails = `azsdk-js-identity/2.1.0-beta.2`;
372
372
  const userAgentPrefix = ((_a = options === null || options === void 0 ? void 0 : options.userAgentOptions) === null || _a === void 0 ? void 0 : _a.userAgentPrefix)
373
373
  ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
@@ -383,9 +383,10 @@ class IdentityClient extends coreClient.ServiceClient {
383
383
  }, baseUri }));
384
384
  this.authorityHost = baseUri;
385
385
  this.abortControllers = new Map();
386
+ this.allowLoggingAccountIdentifiers = (_b = options === null || options === void 0 ? void 0 : options.loggingOptions) === null || _b === void 0 ? void 0 : _b.allowLoggingAccountIdentifiers;
386
387
  }
387
388
  async sendTokenRequest(request, expiresOnParser) {
388
- logger$j.info(`IdentityClient: sending token request to [${request.url}]`);
389
+ logger$k.info(`IdentityClient: sending token request to [${request.url}]`);
389
390
  const response = await this.sendRequest(request);
390
391
  expiresOnParser =
391
392
  expiresOnParser ||
@@ -397,6 +398,7 @@ class IdentityClient extends coreClient.ServiceClient {
397
398
  if (!parsedBody.access_token) {
398
399
  return null;
399
400
  }
401
+ this.logIdentifiers(response);
400
402
  const token = {
401
403
  accessToken: {
402
404
  token: parsedBody.access_token,
@@ -404,12 +406,12 @@ class IdentityClient extends coreClient.ServiceClient {
404
406
  },
405
407
  refreshToken: parsedBody.refresh_token,
406
408
  };
407
- logger$j.info(`IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`);
409
+ logger$k.info(`IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`);
408
410
  return token;
409
411
  }
410
412
  else {
411
413
  const error = new AuthenticationError(response.status, response.bodyAsText);
412
- logger$j.warning(`IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`);
414
+ logger$k.warning(`IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`);
413
415
  throw error;
414
416
  }
415
417
  }
@@ -417,7 +419,7 @@ class IdentityClient extends coreClient.ServiceClient {
417
419
  if (refreshToken === undefined) {
418
420
  return null;
419
421
  }
420
- logger$j.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`);
422
+ logger$k.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`);
421
423
  const { span, updatedOptions } = createSpan("IdentityClient-refreshAccessToken", options);
422
424
  const refreshParams = {
423
425
  grant_type: "refresh_token",
@@ -443,7 +445,7 @@ class IdentityClient extends coreClient.ServiceClient {
443
445
  tracingOptions: updatedOptions === null || updatedOptions === void 0 ? void 0 : updatedOptions.tracingOptions,
444
446
  });
445
447
  const response = await this.sendTokenRequest(request, expiresOnParser);
446
- logger$j.info(`IdentityClient: refreshed token for client ID: ${clientId}`);
448
+ logger$k.info(`IdentityClient: refreshed token for client ID: ${clientId}`);
447
449
  return response;
448
450
  }
449
451
  catch (err) {
@@ -452,7 +454,7 @@ class IdentityClient extends coreClient.ServiceClient {
452
454
  // It's likely that the refresh token has expired, so
453
455
  // return null so that the credential implementation will
454
456
  // initiate the authentication flow again.
455
- logger$j.info(`IdentityClient: interaction required for client ID: ${clientId}`);
457
+ logger$k.info(`IdentityClient: interaction required for client ID: ${clientId}`);
456
458
  span.setStatus({
457
459
  code: coreTracing.SpanStatusCode.ERROR,
458
460
  message: err.message,
@@ -460,7 +462,7 @@ class IdentityClient extends coreClient.ServiceClient {
460
462
  return null;
461
463
  }
462
464
  else {
463
- logger$j.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`);
465
+ logger$k.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`);
464
466
  span.setStatus({
465
467
  code: coreTracing.SpanStatusCode.ERROR,
466
468
  message: err.message,
@@ -518,6 +520,7 @@ class IdentityClient extends coreClient.ServiceClient {
518
520
  abortSignal: this.generateAbortSignal(noCorrelationId),
519
521
  });
520
522
  const response = await this.sendRequest(request);
523
+ this.logIdentifiers(response);
521
524
  return {
522
525
  body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,
523
526
  headers: response.headers.toJSON(),
@@ -534,12 +537,45 @@ class IdentityClient extends coreClient.ServiceClient {
534
537
  abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),
535
538
  });
536
539
  const response = await this.sendRequest(request);
540
+ this.logIdentifiers(response);
537
541
  return {
538
542
  body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,
539
543
  headers: response.headers.toJSON(),
540
544
  status: response.status,
541
545
  };
542
546
  }
547
+ /**
548
+ * If allowLoggingAccountIdentifiers was set on the constructor options
549
+ * we try to log the account identifiers by parsing the received access token.
550
+ *
551
+ * The account identifiers we try to log are:
552
+ * - `appid`: The application or Client Identifier.
553
+ * - `upn`: User Principal Name.
554
+ * - It might not be available in some authentication scenarios.
555
+ * - If it's not available, we put a placeholder: "No User Principal Name available".
556
+ * - `tid`: Tenant Identifier.
557
+ * - `oid`: Object Identifier of the authenticated user.
558
+ */
559
+ logIdentifiers(response) {
560
+ if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {
561
+ return;
562
+ }
563
+ const unavailableUpn = "No User Principal Name available";
564
+ try {
565
+ const parsed = response.parsedBody || JSON.parse(response.bodyAsText);
566
+ const accessToken = parsed.access_token;
567
+ if (!accessToken) {
568
+ // Without an access token allowLoggingAccountIdentifiers isn't useful.
569
+ return;
570
+ }
571
+ const base64Metadata = accessToken.split(".")[1];
572
+ const { appid, upn, tid, oid } = JSON.parse(Buffer.from(base64Metadata, "base64").toString("utf8"));
573
+ logger$k.info(`[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${upn || unavailableUpn}. Object ID (user): ${oid}`);
574
+ }
575
+ catch (e) {
576
+ logger$k.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e.message);
577
+ }
578
+ }
543
579
  }
544
580
 
545
581
  // Copyright (c) Microsoft Corporation.
@@ -978,7 +1014,7 @@ class MsalNode extends MsalBaseUtilities {
978
1014
  const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
979
1015
  this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;
980
1016
  const authority = getAuthority(tenantId, this.authorityHost);
981
- this.identityClient = new IdentityClient(Object.assign(Object.assign({}, options.tokenCredentialOptions), { authorityHost: authority }));
1017
+ this.identityClient = new IdentityClient(Object.assign(Object.assign({}, options.tokenCredentialOptions), { authorityHost: authority, loggingOptions: options.loggingOptions }));
982
1018
  let clientCapabilities = ["cp1"];
983
1019
  if (process.env.AZURE_IDENTITY_DISABLE_CP1) {
984
1020
  clientCapabilities = [];
@@ -1148,7 +1184,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
1148
1184
  // Copyright (c) Microsoft Corporation.
1149
1185
  const CommonTenantId = "common";
1150
1186
  const AzureAccountClientId = "aebc6443-996d-45c2-90f0-388ff96faa56"; // VSC: 'aebc6443-996d-45c2-90f0-388ff96faa56'
1151
- const logger$i = credentialLogger("VisualStudioCodeCredential");
1187
+ const logger$j = credentialLogger("VisualStudioCodeCredential");
1152
1188
  let findCredentials = undefined;
1153
1189
  const vsCodeCredentialControl = {
1154
1190
  setVsCodeCredentialFinder(finder) {
@@ -1201,7 +1237,7 @@ function getPropertyFromVSCode(property) {
1201
1237
  }
1202
1238
  }
1203
1239
  catch (e) {
1204
- logger$i.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`);
1240
+ logger$j.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`);
1205
1241
  return;
1206
1242
  }
1207
1243
  }
@@ -1229,7 +1265,7 @@ class VisualStudioCodeCredential {
1229
1265
  const authorityHost = mapVSCodeAuthorityHosts[this.cloudName];
1230
1266
  this.identityClient = new IdentityClient(Object.assign({ authorityHost }, options));
1231
1267
  if (options && options.tenantId) {
1232
- checkTenantId(logger$i, options.tenantId);
1268
+ checkTenantId(logger$j, options.tenantId);
1233
1269
  this.tenantId = options.tenantId;
1234
1270
  }
1235
1271
  else {
@@ -1281,7 +1317,7 @@ class VisualStudioCodeCredential {
1281
1317
  // Check to make sure the scope we get back is a valid scope
1282
1318
  if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) {
1283
1319
  const error = new Error("Invalid scope was specified by the user or calling client");
1284
- logger$i.getToken.info(formatError(scopes, error));
1320
+ logger$j.getToken.info(formatError(scopes, error));
1285
1321
  throw error;
1286
1322
  }
1287
1323
  if (scopeString.indexOf("offline_access") < 0) {
@@ -1301,18 +1337,18 @@ class VisualStudioCodeCredential {
1301
1337
  if (refreshToken) {
1302
1338
  const tokenResponse = await this.identityClient.refreshAccessToken(tenantId, AzureAccountClientId, scopeString, refreshToken, undefined);
1303
1339
  if (tokenResponse) {
1304
- logger$i.getToken.info(formatSuccess(scopes));
1340
+ logger$j.getToken.info(formatSuccess(scopes));
1305
1341
  return tokenResponse.accessToken;
1306
1342
  }
1307
1343
  else {
1308
1344
  const error = new CredentialUnavailableError("Could not retrieve the token associated with Visual Studio Code. Have you connected using the 'Azure Account' extension recently? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.");
1309
- logger$i.getToken.info(formatError(scopes, error));
1345
+ logger$j.getToken.info(formatError(scopes, error));
1310
1346
  throw error;
1311
1347
  }
1312
1348
  }
1313
1349
  else {
1314
1350
  const error = new CredentialUnavailableError("Could not retrieve the token associated with Visual Studio Code. Did you connect using the 'Azure Account' extension? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.");
1315
- logger$i.getToken.info(formatError(scopes, error));
1351
+ logger$j.getToken.info(formatError(scopes, error));
1316
1352
  throw error;
1317
1353
  }
1318
1354
  }
@@ -1363,7 +1399,7 @@ function useIdentityPlugin(plugin) {
1363
1399
  /**
1364
1400
  * @internal
1365
1401
  */
1366
- const logger$h = credentialLogger("ChainedTokenCredential");
1402
+ const logger$i = credentialLogger("ChainedTokenCredential");
1367
1403
  /**
1368
1404
  * Enables multiple `TokenCredential` implementations to be tried in order
1369
1405
  * until one of the getToken methods returns an access token.
@@ -1418,7 +1454,7 @@ class ChainedTokenCredential {
1418
1454
  errors.push(err);
1419
1455
  }
1420
1456
  else {
1421
- logger$h.getToken.info(formatError(scopes, err));
1457
+ logger$i.getToken.info(formatError(scopes, err));
1422
1458
  throw err;
1423
1459
  }
1424
1460
  }
@@ -1429,11 +1465,11 @@ class ChainedTokenCredential {
1429
1465
  code: coreTracing.SpanStatusCode.ERROR,
1430
1466
  message: err.message,
1431
1467
  });
1432
- logger$h.getToken.info(formatError(scopes, err));
1468
+ logger$i.getToken.info(formatError(scopes, err));
1433
1469
  throw err;
1434
1470
  }
1435
1471
  span.end();
1436
- logger$h.getToken.info(`Result for ${successfulCredentialName}: ${formatSuccess(scopes)}`);
1472
+ logger$i.getToken.info(`Result for ${successfulCredentialName}: ${formatSuccess(scopes)}`);
1437
1473
  if (token === null) {
1438
1474
  throw new CredentialUnavailableError("Failed to retrieve a valid token");
1439
1475
  }
@@ -1511,7 +1547,7 @@ const cliCredentialInternals = {
1511
1547
  });
1512
1548
  },
1513
1549
  };
1514
- const logger$g = credentialLogger("AzureCliCredential");
1550
+ const logger$h = credentialLogger("AzureCliCredential");
1515
1551
  /**
1516
1552
  * This credential will use the currently logged-in user login information
1517
1553
  * via the Azure CLI ('az') commandline tool.
@@ -1541,11 +1577,11 @@ class AzureCliCredential {
1541
1577
  async getToken(scopes, options) {
1542
1578
  const tenantId = processMultiTenantRequest(this.tenantId, options);
1543
1579
  if (tenantId) {
1544
- checkTenantId(logger$g, tenantId);
1580
+ checkTenantId(logger$h, tenantId);
1545
1581
  }
1546
1582
  const scope = typeof scopes === "string" ? scopes : scopes[0];
1547
- logger$g.getToken.info(`Using the scope ${scope}`);
1548
- ensureValidScope(scope, logger$g);
1583
+ logger$h.getToken.info(`Using the scope ${scope}`);
1584
+ ensureValidScope(scope, logger$h);
1549
1585
  const resource = getScopeResource(scope);
1550
1586
  let responseData = "";
1551
1587
  const { span } = createSpan(`${this.constructor.name}.getToken`, options);
@@ -1556,22 +1592,22 @@ class AzureCliCredential {
1556
1592
  const isNotInstallError = obj.stderr.match("az:(.*)not found") || obj.stderr.startsWith("'az' is not recognized");
1557
1593
  if (isNotInstallError) {
1558
1594
  const error = new CredentialUnavailableError("Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'.");
1559
- logger$g.getToken.info(formatError(scopes, error));
1595
+ logger$h.getToken.info(formatError(scopes, error));
1560
1596
  throw error;
1561
1597
  }
1562
1598
  else if (isLoginError) {
1563
1599
  const error = new CredentialUnavailableError("Please run 'az login' from a command prompt to authenticate before using this credential.");
1564
- logger$g.getToken.info(formatError(scopes, error));
1600
+ logger$h.getToken.info(formatError(scopes, error));
1565
1601
  throw error;
1566
1602
  }
1567
1603
  const error = new CredentialUnavailableError(obj.stderr);
1568
- logger$g.getToken.info(formatError(scopes, error));
1604
+ logger$h.getToken.info(formatError(scopes, error));
1569
1605
  throw error;
1570
1606
  }
1571
1607
  else {
1572
1608
  responseData = obj.stdout;
1573
1609
  const response = JSON.parse(responseData);
1574
- logger$g.getToken.info(formatSuccess(scopes));
1610
+ logger$h.getToken.info(formatSuccess(scopes));
1575
1611
  const returnValue = {
1576
1612
  token: response.accessToken,
1577
1613
  expiresOnTimestamp: new Date(response.expiresOn).getTime(),
@@ -1585,7 +1621,7 @@ class AzureCliCredential {
1585
1621
  code: coreTracing.SpanStatusCode.ERROR,
1586
1622
  message: error.message,
1587
1623
  });
1588
- logger$g.getToken.info(formatError(scopes, error));
1624
+ logger$h.getToken.info(formatError(scopes, error));
1589
1625
  throw error;
1590
1626
  }
1591
1627
  }
@@ -1622,7 +1658,7 @@ const processUtils = {
1622
1658
  };
1623
1659
 
1624
1660
  // Copyright (c) Microsoft Corporation.
1625
- const logger$f = credentialLogger("AzurePowerShellCredential");
1661
+ const logger$g = credentialLogger("AzurePowerShellCredential");
1626
1662
  const isWindows = process.platform === "win32";
1627
1663
  /**
1628
1664
  * Returns a platform-appropriate command name by appending ".exe" on Windows.
@@ -1753,15 +1789,15 @@ class AzurePowerShellCredential {
1753
1789
  return trace(`${this.constructor.name}.getToken`, options, async () => {
1754
1790
  const tenantId = processMultiTenantRequest(this.tenantId, options);
1755
1791
  if (tenantId) {
1756
- checkTenantId(logger$f, tenantId);
1792
+ checkTenantId(logger$g, tenantId);
1757
1793
  }
1758
1794
  const scope = typeof scopes === "string" ? scopes : scopes[0];
1759
- ensureValidScope(scope, logger$f);
1760
- logger$f.getToken.info(`Using the scope ${scope}`);
1795
+ ensureValidScope(scope, logger$g);
1796
+ logger$g.getToken.info(`Using the scope ${scope}`);
1761
1797
  const resource = getScopeResource(scope);
1762
1798
  try {
1763
1799
  const response = await this.getAzurePowerShellAccessToken(resource, tenantId);
1764
- logger$f.getToken.info(formatSuccess(scopes));
1800
+ logger$g.getToken.info(formatSuccess(scopes));
1765
1801
  return {
1766
1802
  token: response.Token,
1767
1803
  expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),
@@ -1770,16 +1806,16 @@ class AzurePowerShellCredential {
1770
1806
  catch (err) {
1771
1807
  if (isNotInstalledError(err)) {
1772
1808
  const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);
1773
- logger$f.getToken.info(formatError(scope, error));
1809
+ logger$g.getToken.info(formatError(scope, error));
1774
1810
  throw error;
1775
1811
  }
1776
1812
  else if (isLoginError(err)) {
1777
1813
  const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);
1778
- logger$f.getToken.info(formatError(scope, error));
1814
+ logger$g.getToken.info(formatError(scope, error));
1779
1815
  throw error;
1780
1816
  }
1781
1817
  const error = new CredentialUnavailableError(`${err}. ${powerShellPublicErrorMessages.troubleshoot}`);
1782
- logger$f.getToken.info(formatError(scope, error));
1818
+ logger$g.getToken.info(formatError(scope, error));
1783
1819
  throw error;
1784
1820
  }
1785
1821
  });
@@ -1817,7 +1853,7 @@ class MsalClientSecret extends MsalNode {
1817
1853
  }
1818
1854
 
1819
1855
  // Copyright (c) Microsoft Corporation.
1820
- const logger$e = credentialLogger("ClientSecretCredential");
1856
+ const logger$f = credentialLogger("ClientSecretCredential");
1821
1857
  /**
1822
1858
  * Enables authentication to Azure Active Directory using a client secret
1823
1859
  * that was generated for an App Registration. More information on how
@@ -1841,7 +1877,7 @@ class ClientSecretCredential {
1841
1877
  if (!tenantId || !clientId || !clientSecret) {
1842
1878
  throw new Error("ClientSecretCredential: tenantId, clientId, and clientSecret are required parameters. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");
1843
1879
  }
1844
- this.msalFlow = new MsalClientSecret(Object.assign(Object.assign({}, options), { logger: logger$e,
1880
+ this.msalFlow = new MsalClientSecret(Object.assign(Object.assign({}, options), { logger: logger$f,
1845
1881
  clientId,
1846
1882
  tenantId,
1847
1883
  clientSecret, tokenCredentialOptions: options }));
@@ -1874,8 +1910,12 @@ const readFileAsync$2 = util.promisify(fs.readFile);
1874
1910
  */
1875
1911
  async function parseCertificate(configuration, sendCertificateChain) {
1876
1912
  const certificateParts = {};
1913
+ const certificate = configuration
1914
+ .certificate;
1915
+ const certificatePath = configuration
1916
+ .certificatePath;
1877
1917
  certificateParts.certificateContents =
1878
- configuration.certificate || (await readFileAsync$2(configuration.certificatePath, "utf8"));
1918
+ certificate || (await readFileAsync$2(certificatePath, "utf8"));
1879
1919
  if (sendCertificateChain) {
1880
1920
  certificateParts.x5c = certificateParts.certificateContents;
1881
1921
  }
@@ -1947,7 +1987,7 @@ class MsalClientCertificate extends MsalNode {
1947
1987
 
1948
1988
  // Copyright (c) Microsoft Corporation.
1949
1989
  const credentialName$2 = "ClientCertificateCredential";
1950
- const logger$d = credentialLogger(credentialName$2);
1990
+ const logger$e = credentialLogger(credentialName$2);
1951
1991
  /**
1952
1992
  * Enables authentication to Azure Active Directory using a PEM-encoded
1953
1993
  * certificate that is assigned to an App Registration. More information
@@ -1966,14 +2006,17 @@ class ClientCertificateCredential {
1966
2006
  certificatePath: certificatePathOrConfiguration,
1967
2007
  }
1968
2008
  : certificatePathOrConfiguration));
1969
- if (!configuration || !(configuration.certificate || configuration.certificatePath)) {
2009
+ const certificate = configuration
2010
+ .certificate;
2011
+ const certificatePath = configuration.certificatePath;
2012
+ if (!configuration || !(certificate || certificatePath)) {
1970
2013
  throw new Error(`${credentialName$2}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
1971
2014
  }
1972
- if (configuration.certificate && configuration.certificatePath) {
2015
+ if (certificate && certificatePath) {
1973
2016
  throw new Error(`${credentialName$2}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
1974
2017
  }
1975
2018
  this.msalFlow = new MsalClientCertificate(Object.assign(Object.assign({}, options), { configuration,
1976
- logger: logger$d,
2019
+ logger: logger$e,
1977
2020
  clientId,
1978
2021
  tenantId, sendCertificateChain: options.sendCertificateChain, tokenCredentialOptions: options }));
1979
2022
  }
@@ -2024,7 +2067,7 @@ class MsalUsernamePassword extends MsalNode {
2024
2067
  }
2025
2068
 
2026
2069
  // Copyright (c) Microsoft Corporation.
2027
- const logger$c = credentialLogger("UsernamePasswordCredential");
2070
+ const logger$d = credentialLogger("UsernamePasswordCredential");
2028
2071
  /**
2029
2072
  * Enables authentication to Azure Active Directory with a user's
2030
2073
  * username and password. This credential requires a high degree of
@@ -2047,7 +2090,7 @@ class UsernamePasswordCredential {
2047
2090
  if (!tenantId || !clientId || !username || !password) {
2048
2091
  throw new Error("UsernamePasswordCredential: tenantId, clientId, username and password are required parameters. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");
2049
2092
  }
2050
- this.msalFlow = new MsalUsernamePassword(Object.assign(Object.assign({}, options), { logger: logger$c,
2093
+ this.msalFlow = new MsalUsernamePassword(Object.assign(Object.assign({}, options), { logger: logger$d,
2051
2094
  clientId,
2052
2095
  tenantId,
2053
2096
  username,
@@ -2090,7 +2133,7 @@ const AllSupportedEnvironmentVariables = [
2090
2133
  "AZURE_PASSWORD",
2091
2134
  ];
2092
2135
  const credentialName$1 = "EnvironmentCredential";
2093
- const logger$b = credentialLogger(credentialName$1);
2136
+ const logger$c = credentialLogger(credentialName$1);
2094
2137
  /**
2095
2138
  * Enables authentication to Azure Active Directory using client secret
2096
2139
  * details configured in environment variables
@@ -2120,26 +2163,26 @@ class EnvironmentCredential {
2120
2163
  // Keep track of any missing environment variables for error details
2121
2164
  this._credential = undefined;
2122
2165
  const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(", ");
2123
- logger$b.info(`Found the following environment variables: ${assigned}`);
2166
+ logger$c.info(`Found the following environment variables: ${assigned}`);
2124
2167
  const tenantId = process.env.AZURE_TENANT_ID, clientId = process.env.AZURE_CLIENT_ID, clientSecret = process.env.AZURE_CLIENT_SECRET;
2125
2168
  if (tenantId) {
2126
- checkTenantId(logger$b, tenantId);
2169
+ checkTenantId(logger$c, tenantId);
2127
2170
  }
2128
2171
  if (tenantId && clientId && clientSecret) {
2129
- logger$b.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`);
2172
+ logger$c.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`);
2130
2173
  this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
2131
2174
  return;
2132
2175
  }
2133
2176
  const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;
2134
2177
  if (tenantId && clientId && certificatePath) {
2135
- logger$b.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`);
2178
+ logger$c.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`);
2136
2179
  this._credential = new ClientCertificateCredential(tenantId, clientId, { certificatePath }, options);
2137
2180
  return;
2138
2181
  }
2139
2182
  const username = process.env.AZURE_USERNAME;
2140
2183
  const password = process.env.AZURE_PASSWORD;
2141
2184
  if (tenantId && clientId && username && password) {
2142
- logger$b.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`);
2185
+ logger$c.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`);
2143
2186
  this._credential = new UsernamePasswordCredential(tenantId, clientId, username, password, options);
2144
2187
  }
2145
2188
  }
@@ -2154,7 +2197,7 @@ class EnvironmentCredential {
2154
2197
  if (this._credential) {
2155
2198
  try {
2156
2199
  const result = await this._credential.getToken(scopes, newOptions);
2157
- logger$b.getToken.info(formatSuccess(scopes));
2200
+ logger$c.getToken.info(formatSuccess(scopes));
2158
2201
  return result;
2159
2202
  }
2160
2203
  catch (err) {
@@ -2162,7 +2205,7 @@ class EnvironmentCredential {
2162
2205
  error: `${credentialName$1} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,
2163
2206
  error_description: err.message.toString().split("More details:").join(""),
2164
2207
  });
2165
- logger$b.getToken.info(formatError(scopes, authenticationError));
2208
+ logger$c.getToken.info(formatError(scopes, authenticationError));
2166
2209
  throw authenticationError;
2167
2210
  }
2168
2211
  }
@@ -2208,22 +2251,22 @@ function mapScopesToResource(scopes) {
2208
2251
  }
2209
2252
 
2210
2253
  // Copyright (c) Microsoft Corporation.
2211
- const msiName$5 = "ManagedIdentityCredential - AppServiceMSI 2017";
2212
- const logger$a = credentialLogger(msiName$5);
2254
+ const msiName$6 = "ManagedIdentityCredential - AppServiceMSI 2017";
2255
+ const logger$b = credentialLogger(msiName$6);
2213
2256
  /**
2214
2257
  * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.
2215
2258
  */
2216
- function expiresOnParser$2(requestBody) {
2259
+ function expiresOnParser$3(requestBody) {
2217
2260
  // App Service always returns string expires_on values.
2218
2261
  return Date.parse(requestBody.expires_on);
2219
2262
  }
2220
2263
  /**
2221
2264
  * Generates the options used on the request for an access token.
2222
2265
  */
2223
- function prepareRequestOptions$5(scopes, clientId) {
2266
+ function prepareRequestOptions$6(scopes, clientId) {
2224
2267
  const resource = mapScopesToResource(scopes);
2225
2268
  if (!resource) {
2226
- throw new Error(`${msiName$5}: Multiple scopes are not supported.`);
2269
+ throw new Error(`${msiName$6}: Multiple scopes are not supported.`);
2227
2270
  }
2228
2271
  const queryParameters = {
2229
2272
  resource,
@@ -2235,10 +2278,10 @@ function prepareRequestOptions$5(scopes, clientId) {
2235
2278
  const query = new URLSearchParams(queryParameters);
2236
2279
  // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
2237
2280
  if (!process.env.MSI_ENDPOINT) {
2238
- throw new Error(`${msiName$5}: Missing environment variable: MSI_ENDPOINT`);
2281
+ throw new Error(`${msiName$6}: Missing environment variable: MSI_ENDPOINT`);
2239
2282
  }
2240
2283
  if (!process.env.MSI_SECRET) {
2241
- throw new Error(`${msiName$5}: Missing environment variable: MSI_SECRET`);
2284
+ throw new Error(`${msiName$6}: Missing environment variable: MSI_SECRET`);
2242
2285
  }
2243
2286
  return {
2244
2287
  url: `${process.env.MSI_ENDPOINT}?${query.toString()}`,
@@ -2256,40 +2299,40 @@ const appServiceMsi2017 = {
2256
2299
  async isAvailable({ scopes }) {
2257
2300
  const resource = mapScopesToResource(scopes);
2258
2301
  if (!resource) {
2259
- logger$a.info(`${msiName$5}: Unavailable. Multiple scopes are not supported.`);
2302
+ logger$b.info(`${msiName$6}: Unavailable. Multiple scopes are not supported.`);
2260
2303
  return false;
2261
2304
  }
2262
2305
  const env = process.env;
2263
2306
  const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);
2264
2307
  if (!result) {
2265
- logger$a.info(`${msiName$5}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`);
2308
+ logger$b.info(`${msiName$6}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`);
2266
2309
  }
2267
2310
  return result;
2268
2311
  },
2269
2312
  async getToken(configuration, getTokenOptions = {}) {
2270
2313
  const { identityClient, scopes, clientId, resourceId } = configuration;
2271
2314
  if (resourceId) {
2272
- logger$a.warning(`${msiName$5}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
2315
+ logger$b.warning(`${msiName$6}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
2273
2316
  }
2274
- logger$a.info(`${msiName$5}: Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`);
2275
- const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$5(scopes, clientId)), {
2317
+ logger$b.info(`${msiName$6}: Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`);
2318
+ const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$6(scopes, clientId)), {
2276
2319
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
2277
2320
  allowInsecureConnection: true }));
2278
- const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser$2);
2321
+ const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser$3);
2279
2322
  return (tokenResponse && tokenResponse.accessToken) || null;
2280
2323
  },
2281
2324
  };
2282
2325
 
2283
2326
  // Copyright (c) Microsoft Corporation.
2284
- const msiName$4 = "ManagedIdentityCredential - CloudShellMSI";
2285
- const logger$9 = credentialLogger(msiName$4);
2327
+ const msiName$5 = "ManagedIdentityCredential - CloudShellMSI";
2328
+ const logger$a = credentialLogger(msiName$5);
2286
2329
  /**
2287
2330
  * Generates the options used on the request for an access token.
2288
2331
  */
2289
- function prepareRequestOptions$4(scopes, clientId, resourceId) {
2332
+ function prepareRequestOptions$5(scopes, clientId, resourceId) {
2290
2333
  const resource = mapScopesToResource(scopes);
2291
2334
  if (!resource) {
2292
- throw new Error(`${msiName$4}: Multiple scopes are not supported.`);
2335
+ throw new Error(`${msiName$5}: Multiple scopes are not supported.`);
2293
2336
  }
2294
2337
  const body = {
2295
2338
  resource,
@@ -2302,7 +2345,7 @@ function prepareRequestOptions$4(scopes, clientId, resourceId) {
2302
2345
  }
2303
2346
  // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
2304
2347
  if (!process.env.MSI_ENDPOINT) {
2305
- throw new Error(`${msiName$4}: Missing environment variable: MSI_ENDPOINT`);
2348
+ throw new Error(`${msiName$5}: Missing environment variable: MSI_ENDPOINT`);
2306
2349
  }
2307
2350
  const params = new URLSearchParams(body);
2308
2351
  return {
@@ -2324,25 +2367,25 @@ const cloudShellMsi = {
2324
2367
  async isAvailable({ scopes }) {
2325
2368
  const resource = mapScopesToResource(scopes);
2326
2369
  if (!resource) {
2327
- logger$9.info(`${msiName$4}: Unavailable. Multiple scopes are not supported.`);
2370
+ logger$a.info(`${msiName$5}: Unavailable. Multiple scopes are not supported.`);
2328
2371
  return false;
2329
2372
  }
2330
2373
  const result = Boolean(process.env.MSI_ENDPOINT);
2331
2374
  if (!result) {
2332
- logger$9.info(`${msiName$4}: Unavailable. The environment variable MSI_ENDPOINT is needed.`);
2375
+ logger$a.info(`${msiName$5}: Unavailable. The environment variable MSI_ENDPOINT is needed.`);
2333
2376
  }
2334
2377
  return result;
2335
2378
  },
2336
2379
  async getToken(configuration, getTokenOptions = {}) {
2337
2380
  const { identityClient, scopes, clientId, resourceId } = configuration;
2338
2381
  if (clientId) {
2339
- logger$9.warning(`${msiName$4}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
2382
+ logger$a.warning(`${msiName$5}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
2340
2383
  }
2341
2384
  if (resourceId) {
2342
- logger$9.warning(`${msiName$4}: user defined managed Identity by resource Id not supported. The argument resourceId might be ignored by the service.`);
2385
+ logger$a.warning(`${msiName$5}: user defined managed Identity by resource Id not supported. The argument resourceId might be ignored by the service.`);
2343
2386
  }
2344
- logger$9.info(`${msiName$4}: Using the endpoint coming form the environment variable MSI_ENDPOINT = ${process.env.MSI_ENDPOINT}.`);
2345
- const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$4(scopes, clientId, resourceId)), {
2387
+ logger$a.info(`${msiName$5}: Using the endpoint coming form the environment variable MSI_ENDPOINT = ${process.env.MSI_ENDPOINT}.`);
2388
+ const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$5(scopes, clientId, resourceId)), {
2346
2389
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
2347
2390
  allowInsecureConnection: true }));
2348
2391
  const tokenResponse = await identityClient.sendTokenRequest(request);
@@ -2351,33 +2394,33 @@ const cloudShellMsi = {
2351
2394
  };
2352
2395
 
2353
2396
  // Copyright (c) Microsoft Corporation.
2354
- const msiName$3 = "ManagedIdentityCredential - IMDS";
2355
- const logger$8 = credentialLogger(msiName$3);
2397
+ const msiName$4 = "ManagedIdentityCredential - IMDS";
2398
+ const logger$9 = credentialLogger(msiName$4);
2356
2399
  /**
2357
2400
  * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.
2358
2401
  */
2359
- function expiresOnParser$1(requestBody) {
2402
+ function expiresOnParser$2(requestBody) {
2360
2403
  if (requestBody.expires_on) {
2361
2404
  // Use the expires_on timestamp if it's available
2362
2405
  const expires = +requestBody.expires_on * 1000;
2363
- logger$8.info(`${msiName$3}: Using expires_on: ${expires} (original value: ${requestBody.expires_on})`);
2406
+ logger$9.info(`${msiName$4}: Using expires_on: ${expires} (original value: ${requestBody.expires_on})`);
2364
2407
  return expires;
2365
2408
  }
2366
2409
  else {
2367
2410
  // If these aren't possible, use expires_in and calculate a timestamp
2368
2411
  const expires = Date.now() + requestBody.expires_in * 1000;
2369
- logger$8.info(`${msiName$3}: IMDS using expires_in: ${expires} (original value: ${requestBody.expires_in})`);
2412
+ logger$9.info(`${msiName$4}: IMDS using expires_in: ${expires} (original value: ${requestBody.expires_in})`);
2370
2413
  return expires;
2371
2414
  }
2372
2415
  }
2373
2416
  /**
2374
2417
  * Generates the options used on the request for an access token.
2375
2418
  */
2376
- function prepareRequestOptions$3(scopes, clientId, resourceId, options) {
2419
+ function prepareRequestOptions$4(scopes, clientId, resourceId, options) {
2377
2420
  var _a;
2378
2421
  const resource = mapScopesToResource(scopes);
2379
2422
  if (!resource) {
2380
- throw new Error(`${msiName$3}: Multiple scopes are not supported.`);
2423
+ throw new Error(`${msiName$4}: Multiple scopes are not supported.`);
2381
2424
  }
2382
2425
  const { skipQuery, skipMetadataHeader } = options || {};
2383
2426
  let query = "";
@@ -2427,7 +2470,7 @@ const imdsMsi = {
2427
2470
  var _a, _b;
2428
2471
  const resource = mapScopesToResource(scopes);
2429
2472
  if (!resource) {
2430
- logger$8.info(`${msiName$3}: Unavailable. Multiple scopes are not supported.`);
2473
+ logger$9.info(`${msiName$4}: Unavailable. Multiple scopes are not supported.`);
2431
2474
  return false;
2432
2475
  }
2433
2476
  const { span, updatedOptions: options } = createSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions);
@@ -2438,7 +2481,7 @@ const imdsMsi = {
2438
2481
  if (!identityClient) {
2439
2482
  throw new Error("Missing IdentityClient");
2440
2483
  }
2441
- const requestOptions = prepareRequestOptions$3(resource, clientId, resourceId, {
2484
+ const requestOptions = prepareRequestOptions$4(resource, clientId, resourceId, {
2442
2485
  skipMetadataHeader: true,
2443
2486
  skipQuery: true,
2444
2487
  });
@@ -2452,7 +2495,7 @@ const imdsMsi = {
2452
2495
  // This MSI uses the imdsEndpoint to get the token, which only uses http://
2453
2496
  request.allowInsecureConnection = true;
2454
2497
  try {
2455
- logger$8.info(`${msiName$3}: Pinging the Azure IMDS endpoint`);
2498
+ logger$9.info(`${msiName$4}: Pinging the Azure IMDS endpoint`);
2456
2499
  await identityClient.sendRequest(request);
2457
2500
  }
2458
2501
  catch (err) {
@@ -2464,7 +2507,7 @@ const imdsMsi = {
2464
2507
  ) {
2465
2508
  // If the request failed, or Node.js was unable to establish a connection,
2466
2509
  // or the host was down, we'll assume the IMDS endpoint isn't available.
2467
- logger$8.info(`${msiName$3}: The Azure IMDS endpoint is unavailable`);
2510
+ logger$9.info(`${msiName$4}: The Azure IMDS endpoint is unavailable`);
2468
2511
  span.setStatus({
2469
2512
  code: coreTracing.SpanStatusCode.ERROR,
2470
2513
  message: err.message,
@@ -2473,13 +2516,13 @@ const imdsMsi = {
2473
2516
  }
2474
2517
  }
2475
2518
  // If we received any response, the endpoint is available
2476
- logger$8.info(`${msiName$3}: The Azure IMDS endpoint is available`);
2519
+ logger$9.info(`${msiName$4}: The Azure IMDS endpoint is available`);
2477
2520
  return true;
2478
2521
  }
2479
2522
  catch (err) {
2480
2523
  // createWebResource failed.
2481
2524
  // This error should bubble up to the user.
2482
- logger$8.info(`${msiName$3}: Error when creating the WebResource for the Azure IMDS endpoint: ${err.message}`);
2525
+ logger$9.info(`${msiName$4}: Error when creating the WebResource for the Azure IMDS endpoint: ${err.message}`);
2483
2526
  span.setStatus({
2484
2527
  code: coreTracing.SpanStatusCode.ERROR,
2485
2528
  message: err.message,
@@ -2492,12 +2535,12 @@ const imdsMsi = {
2492
2535
  },
2493
2536
  async getToken(configuration, getTokenOptions = {}) {
2494
2537
  const { identityClient, scopes, clientId, resourceId } = configuration;
2495
- logger$8.info(`${msiName$3}: Using the Azure IMDS endpoint coming from the environment variable MSI_ENDPOINT=${process.env.MSI_ENDPOINT}, and using the cloud shell to proceed with the authentication.`);
2538
+ logger$9.info(`${msiName$4}: Using the Azure IMDS endpoint coming from the environment variable MSI_ENDPOINT=${process.env.MSI_ENDPOINT}, and using the cloud shell to proceed with the authentication.`);
2496
2539
  let nextDelayInMs = imdsMsiRetryConfig.startDelayInMs;
2497
2540
  for (let retries = 0; retries < imdsMsiRetryConfig.maxRetries; retries++) {
2498
2541
  try {
2499
- const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$3(scopes, clientId, resourceId)), { allowInsecureConnection: true }));
2500
- const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser$1);
2542
+ const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$4(scopes, clientId, resourceId)), { allowInsecureConnection: true }));
2543
+ const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser$2);
2501
2544
  return (tokenResponse && tokenResponse.accessToken) || null;
2502
2545
  }
2503
2546
  catch (error) {
@@ -2509,20 +2552,20 @@ const imdsMsi = {
2509
2552
  throw error;
2510
2553
  }
2511
2554
  }
2512
- throw new AuthenticationError(404, `${msiName$3}: Failed to retrieve IMDS token after ${imdsMsiRetryConfig.maxRetries} retries.`);
2555
+ throw new AuthenticationError(404, `${msiName$4}: Failed to retrieve IMDS token after ${imdsMsiRetryConfig.maxRetries} retries.`);
2513
2556
  },
2514
2557
  };
2515
2558
 
2516
2559
  // Copyright (c) Microsoft Corporation.
2517
- const msiName$2 = "ManagedIdentityCredential - Azure Arc MSI";
2518
- const logger$7 = credentialLogger(msiName$2);
2560
+ const msiName$3 = "ManagedIdentityCredential - Azure Arc MSI";
2561
+ const logger$8 = credentialLogger(msiName$3);
2519
2562
  /**
2520
2563
  * Generates the options used on the request for an access token.
2521
2564
  */
2522
- function prepareRequestOptions$2(scopes, clientId, resourceId) {
2565
+ function prepareRequestOptions$3(scopes, clientId, resourceId) {
2523
2566
  const resource = mapScopesToResource(scopes);
2524
2567
  if (!resource) {
2525
- throw new Error(`${msiName$2}: Multiple scopes are not supported.`);
2568
+ throw new Error(`${msiName$3}: Multiple scopes are not supported.`);
2526
2569
  }
2527
2570
  const queryParameters = {
2528
2571
  resource,
@@ -2536,7 +2579,7 @@ function prepareRequestOptions$2(scopes, clientId, resourceId) {
2536
2579
  }
2537
2580
  // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
2538
2581
  if (!process.env.IDENTITY_ENDPOINT) {
2539
- throw new Error(`${msiName$2}: Missing environment variable: IDENTITY_ENDPOINT`);
2582
+ throw new Error(`${msiName$3}: Missing environment variable: IDENTITY_ENDPOINT`);
2540
2583
  }
2541
2584
  const query = new URLSearchParams(queryParameters);
2542
2585
  return coreRestPipeline.createPipelineRequest({
@@ -2571,7 +2614,7 @@ async function filePathRequest(identityClient, requestPrepareOptions) {
2571
2614
  if (response.bodyAsText) {
2572
2615
  message = ` Response: ${response.bodyAsText}`;
2573
2616
  }
2574
- throw new AuthenticationError(response.status, `${msiName$2}: To authenticate with Azure Arc MSI, status code 401 is expected on the first request. ${message}`);
2617
+ throw new AuthenticationError(response.status, `${msiName$3}: To authenticate with Azure Arc MSI, status code 401 is expected on the first request. ${message}`);
2575
2618
  }
2576
2619
  const authHeader = response.headers.get("www-authenticate") || "";
2577
2620
  try {
@@ -2588,12 +2631,12 @@ const arcMsi = {
2588
2631
  async isAvailable({ scopes }) {
2589
2632
  const resource = mapScopesToResource(scopes);
2590
2633
  if (!resource) {
2591
- logger$7.info(`${msiName$2}: Unavailable. Multiple scopes are not supported.`);
2634
+ logger$8.info(`${msiName$3}: Unavailable. Multiple scopes are not supported.`);
2592
2635
  return false;
2593
2636
  }
2594
2637
  const result = Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);
2595
2638
  if (!result) {
2596
- logger$7.info(`${msiName$2}: The environment variables needed are: IMDS_ENDPOINT and IDENTITY_ENDPOINT`);
2639
+ logger$8.info(`${msiName$3}: The environment variables needed are: IMDS_ENDPOINT and IDENTITY_ENDPOINT`);
2597
2640
  }
2598
2641
  return result;
2599
2642
  },
@@ -2601,16 +2644,16 @@ const arcMsi = {
2601
2644
  var _a;
2602
2645
  const { identityClient, scopes, clientId, resourceId } = configuration;
2603
2646
  if (clientId) {
2604
- logger$7.warning(`${msiName$2}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
2647
+ logger$8.warning(`${msiName$3}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
2605
2648
  }
2606
2649
  if (resourceId) {
2607
- logger$7.warning(`${msiName$2}: user defined managed Identity by resource Id is not supported. Argument resourceId will be ignored.`);
2650
+ logger$8.warning(`${msiName$3}: user defined managed Identity by resource Id is not supported. Argument resourceId will be ignored.`);
2608
2651
  }
2609
- logger$7.info(`${msiName$2}: Authenticating.`);
2610
- const requestOptions = Object.assign(Object.assign({ disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$2(scopes, clientId, resourceId)), { allowInsecureConnection: true });
2652
+ logger$8.info(`${msiName$3}: Authenticating.`);
2653
+ const requestOptions = Object.assign(Object.assign({ disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$3(scopes, clientId, resourceId)), { allowInsecureConnection: true });
2611
2654
  const filePath = await filePathRequest(identityClient, requestOptions);
2612
2655
  if (!filePath) {
2613
- throw new Error(`${msiName$2}: Failed to find the token file.`);
2656
+ throw new Error(`${msiName$3}: Failed to find the token file.`);
2614
2657
  }
2615
2658
  const key = await readFileAsync$1(filePath, { encoding: "utf-8" });
2616
2659
  (_a = requestOptions.headers) === null || _a === void 0 ? void 0 : _a.set("Authorization", `Basic ${key}`);
@@ -2623,13 +2666,13 @@ const arcMsi = {
2623
2666
  };
2624
2667
 
2625
2668
  // Copyright (c) Microsoft Corporation.
2626
- const msiName$1 = "ManagedIdentityCredential - Token Exchange";
2627
- const logger$6 = credentialLogger(msiName$1);
2669
+ const msiName$2 = "ManagedIdentityCredential - Token Exchange";
2670
+ const logger$7 = credentialLogger(msiName$2);
2628
2671
  const readFileAsync = util.promisify(fs__default["default"].readFile);
2629
2672
  /**
2630
2673
  * Generates the options used on the request for an access token.
2631
2674
  */
2632
- function prepareRequestOptions$1(scopes, clientAssertion, clientId) {
2675
+ function prepareRequestOptions$2(scopes, clientAssertion, clientId) {
2633
2676
  var _a;
2634
2677
  const bodyParams = {
2635
2678
  scope: Array.isArray(scopes) ? scopes.join(" ") : scopes,
@@ -2680,21 +2723,21 @@ function tokenExchangeMsi() {
2680
2723
  const env = process.env;
2681
2724
  const result = Boolean((clientId || env.AZURE_CLIENT_ID) && env.AZURE_TENANT_ID && azureFederatedTokenFilePath);
2682
2725
  if (!result) {
2683
- logger$6.info(`${msiName$1}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`);
2726
+ logger$7.info(`${msiName$2}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`);
2684
2727
  }
2685
2728
  return result;
2686
2729
  },
2687
2730
  async getToken(configuration, getTokenOptions = {}) {
2688
2731
  const { identityClient, scopes, clientId } = configuration;
2689
- logger$6.info(`${msiName$1}: Using the client assertion coming from environment variables.`);
2732
+ logger$7.info(`${msiName$2}: Using the client assertion coming from environment variables.`);
2690
2733
  let assertion;
2691
2734
  try {
2692
2735
  assertion = await readAssertion();
2693
2736
  }
2694
2737
  catch (err) {
2695
- throw new Error(`${msiName$1}: Failed to read ${azureFederatedTokenFilePath}, indicated by the environment variable AZURE_FEDERATED_TOKEN_FILE`);
2738
+ throw new Error(`${msiName$2}: Failed to read ${azureFederatedTokenFilePath}, indicated by the environment variable AZURE_FEDERATED_TOKEN_FILE`);
2696
2739
  }
2697
- const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$1(scopes, assertion, clientId || process.env.AZURE_CLIENT_ID)), {
2740
+ const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$2(scopes, assertion, clientId || process.env.AZURE_CLIENT_ID)), {
2698
2741
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
2699
2742
  allowInsecureConnection: true }));
2700
2743
  const tokenResponse = await identityClient.sendTokenRequest(request);
@@ -2714,22 +2757,22 @@ function tokenExchangeMsi() {
2714
2757
  //
2715
2758
  // curl --insecure $IDENTITY_ENDPOINT'?api-version=2019-07-01-preview&resource=https://vault.azure.net/' -H "Secret: $IDENTITY_HEADER"
2716
2759
  //
2717
- const msiName = "ManagedIdentityCredential - Fabric MSI";
2718
- const logger$5 = credentialLogger(msiName);
2760
+ const msiName$1 = "ManagedIdentityCredential - Fabric MSI";
2761
+ const logger$6 = credentialLogger(msiName$1);
2719
2762
  /**
2720
2763
  * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.
2721
2764
  */
2722
- function expiresOnParser(requestBody) {
2765
+ function expiresOnParser$1(requestBody) {
2723
2766
  // Parses a string representation of the milliseconds since epoch into a number value
2724
2767
  return Number(requestBody.expires_on);
2725
2768
  }
2726
2769
  /**
2727
2770
  * Generates the options used on the request for an access token.
2728
2771
  */
2729
- function prepareRequestOptions(scopes, clientId, resourceId) {
2772
+ function prepareRequestOptions$1(scopes, clientId, resourceId) {
2730
2773
  const resource = mapScopesToResource(scopes);
2731
2774
  if (!resource) {
2732
- throw new Error(`${msiName}: Multiple scopes are not supported.`);
2775
+ throw new Error(`${msiName$1}: Multiple scopes are not supported.`);
2733
2776
  }
2734
2777
  const queryParameters = {
2735
2778
  resource,
@@ -2765,34 +2808,107 @@ const fabricMsi = {
2765
2808
  async isAvailable({ scopes }) {
2766
2809
  const resource = mapScopesToResource(scopes);
2767
2810
  if (!resource) {
2768
- logger$5.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
2811
+ logger$6.info(`${msiName$1}: Unavailable. Multiple scopes are not supported.`);
2769
2812
  return false;
2770
2813
  }
2771
2814
  const env = process.env;
2772
2815
  const result = Boolean(env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER && env.IDENTITY_SERVER_THUMBPRINT);
2773
2816
  if (!result) {
2774
- logger$5.info(`${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT, IDENTITY_HEADER and IDENTITY_SERVER_THUMBPRINT`);
2817
+ logger$6.info(`${msiName$1}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT, IDENTITY_HEADER and IDENTITY_SERVER_THUMBPRINT`);
2775
2818
  }
2776
2819
  return result;
2777
2820
  },
2778
2821
  async getToken(configuration, getTokenOptions = {}) {
2779
2822
  const { scopes, identityClient, clientId, resourceId } = configuration;
2780
2823
  if (resourceId) {
2781
- logger$5.warning(`${msiName}: user defined managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
2824
+ logger$6.warning(`${msiName$1}: user defined managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
2782
2825
  }
2783
- logger$5.info([
2784
- `${msiName}:`,
2826
+ logger$6.info([
2827
+ `${msiName$1}:`,
2785
2828
  "Using the endpoint and the secret coming from the environment variables:",
2786
2829
  `IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT},`,
2787
2830
  "IDENTITY_HEADER=[REDACTED] and",
2788
2831
  "IDENTITY_SERVER_THUMBPRINT=[REDACTED].",
2789
2832
  ].join(" "));
2790
- const request = coreRestPipeline.createPipelineRequest(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)));
2833
+ const request = coreRestPipeline.createPipelineRequest(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$1(scopes, clientId, resourceId)));
2791
2834
  request.agent = new https__default["default"].Agent({
2792
2835
  // This is necessary because Service Fabric provides a self-signed certificate.
2793
2836
  // The alternative path is to verify the certificate using the IDENTITY_SERVER_THUMBPRINT env variable.
2794
2837
  rejectUnauthorized: false,
2795
2838
  });
2839
+ const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser$1);
2840
+ return (tokenResponse && tokenResponse.accessToken) || null;
2841
+ },
2842
+ };
2843
+
2844
+ // Copyright (c) Microsoft Corporation.
2845
+ const msiName = "ManagedIdentityCredential - AppServiceMSI 2019";
2846
+ const logger$5 = credentialLogger(msiName);
2847
+ /**
2848
+ * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.
2849
+ */
2850
+ function expiresOnParser(requestBody) {
2851
+ // App Service always returns string expires_on values.
2852
+ return Date.parse(requestBody.expires_on);
2853
+ }
2854
+ /**
2855
+ * Generates the options used on the request for an access token.
2856
+ */
2857
+ function prepareRequestOptions(scopes, clientId, resourceId) {
2858
+ const resource = mapScopesToResource(scopes);
2859
+ if (!resource) {
2860
+ throw new Error(`${msiName}: Multiple scopes are not supported.`);
2861
+ }
2862
+ const queryParameters = {
2863
+ resource,
2864
+ "api-version": "2019-08-01",
2865
+ };
2866
+ if (clientId) {
2867
+ queryParameters.client_id = clientId;
2868
+ }
2869
+ if (resourceId) {
2870
+ queryParameters.mi_res_id = resourceId;
2871
+ }
2872
+ const query = new URLSearchParams(queryParameters);
2873
+ // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
2874
+ if (!process.env.IDENTITY_ENDPOINT) {
2875
+ throw new Error(`${msiName}: Missing environment variable: IDENTITY_ENDPOINT`);
2876
+ }
2877
+ if (!process.env.IDENTITY_HEADER) {
2878
+ throw new Error(`${msiName}: Missing environment variable: IDENTITY_HEADER`);
2879
+ }
2880
+ return {
2881
+ url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,
2882
+ method: "GET",
2883
+ headers: coreRestPipeline.createHttpHeaders({
2884
+ Accept: "application/json",
2885
+ "X-IDENTITY-HEADER": process.env.IDENTITY_HEADER,
2886
+ }),
2887
+ };
2888
+ }
2889
+ /**
2890
+ * Defines how to determine whether the Azure App Service MSI is available, and also how to retrieve a token from the Azure App Service MSI.
2891
+ */
2892
+ const appServiceMsi2019 = {
2893
+ async isAvailable({ scopes }) {
2894
+ const resource = mapScopesToResource(scopes);
2895
+ if (!resource) {
2896
+ logger$5.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
2897
+ return false;
2898
+ }
2899
+ const env = process.env;
2900
+ const result = Boolean(env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER);
2901
+ if (!result) {
2902
+ logger$5.info(`${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT and IDENTITY_HEADER.`);
2903
+ }
2904
+ return result;
2905
+ },
2906
+ async getToken(configuration, getTokenOptions = {}) {
2907
+ const { identityClient, scopes, clientId, resourceId } = configuration;
2908
+ logger$5.info(`${msiName}: Using the endpoint and the secret coming form the environment variables: IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT} and IDENTITY_HEADER=[REDACTED].`);
2909
+ const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)), {
2910
+ // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
2911
+ allowInsecureConnection: true }));
2796
2912
  const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser);
2797
2913
  return (tokenResponse && tokenResponse.accessToken) || null;
2798
2914
  },
@@ -2839,7 +2955,15 @@ class ManagedIdentityCredential {
2839
2955
  if (this.cachedMSI) {
2840
2956
  return this.cachedMSI;
2841
2957
  }
2842
- const MSIs = [fabricMsi, appServiceMsi2017, cloudShellMsi, arcMsi, tokenExchangeMsi(), imdsMsi];
2958
+ const MSIs = [
2959
+ fabricMsi,
2960
+ appServiceMsi2019,
2961
+ appServiceMsi2017,
2962
+ cloudShellMsi,
2963
+ arcMsi,
2964
+ tokenExchangeMsi(),
2965
+ imdsMsi,
2966
+ ];
2843
2967
  for (const msi of MSIs) {
2844
2968
  if (await msi.isAvailable({
2845
2969
  scopes,
@@ -2981,13 +3105,24 @@ class ManagedIdentityCredential {
2981
3105
  * @internal
2982
3106
  */
2983
3107
  class DefaultManagedIdentityCredential extends ManagedIdentityCredential {
3108
+ // Constructor overload with just the other default options
3109
+ // Last constructor overload with Union of all options not required since the above two constructor overloads have optional properties
2984
3110
  constructor(options) {
2985
3111
  var _a, _b, _c;
2986
3112
  const managedIdentityClientId = (_b = (_a = options) === null || _a === void 0 ? void 0 : _a.managedIdentityClientId) !== null && _b !== void 0 ? _b : process.env.AZURE_CLIENT_ID;
2987
3113
  const managedResourceId = (_c = options) === null || _c === void 0 ? void 0 : _c.managedIdentityResourceId;
2988
3114
  // ManagedIdentityCredential throws if both the resourceId and the clientId are provided.
2989
- const managedIdentityOptions = Object.assign({ resourceId: managedResourceId, clientId: managedIdentityClientId }, options);
2990
- super(managedIdentityOptions);
3115
+ if (managedResourceId) {
3116
+ const managedIdentityResourceIdOptions = Object.assign(Object.assign({}, options), { resourceId: managedResourceId });
3117
+ super(managedIdentityResourceIdOptions);
3118
+ }
3119
+ else if (managedIdentityClientId) {
3120
+ const managedIdentityClientOptions = Object.assign(Object.assign({}, options), { clientId: managedIdentityClientId });
3121
+ super(managedIdentityClientOptions);
3122
+ }
3123
+ else {
3124
+ super(options);
3125
+ }
2991
3126
  }
2992
3127
  }
2993
3128
  const defaultCredentials = [
@@ -3002,30 +3137,6 @@ const defaultCredentials = [
3002
3137
  * work for most applications that use the Azure SDK.
3003
3138
  */
3004
3139
  class DefaultAzureCredential extends ChainedTokenCredential {
3005
- /**
3006
- * Creates an instance of the DefaultAzureCredential class.
3007
- *
3008
- * This credential provides a default {@link ChainedTokenCredential} configuration that should
3009
- * work for most applications that use the Azure SDK.
3010
- *
3011
- * The following credential types will be tried, in order:
3012
- *
3013
- * - {@link EnvironmentCredential}
3014
- * - {@link ManagedIdentityCredential}
3015
- * - {@link VisualStudioCodeCredential}
3016
- * - {@link AzureCliCredential}
3017
- * - {@link AzurePowerShellCredential}
3018
- *
3019
- * Consult the documentation of these credential types for more information
3020
- * on how they attempt authentication.
3021
- *
3022
- * **Note**: `VisualStudioCodeCredential` is provided by a plugin package:
3023
- * `@azure/identity-vscode`. If this package is not installed and registered
3024
- * using the plugin API (`useIdentityPlugin`), then authentication using
3025
- * `VisualStudioCodeCredential` will not be available.
3026
- *
3027
- * @param options - Optional parameters. See {@link DefaultAzureCredentialOptions}.
3028
- */
3029
3140
  constructor(options) {
3030
3141
  super(...defaultCredentials.map((ctor) => new ctor(options)));
3031
3142
  this.UnavailableMessage =
@@ -3516,27 +3627,6 @@ const logger = credentialLogger(credentialName);
3516
3627
  * Enables authentication to Azure Active Directory using the [On Behalf Of flow](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow).
3517
3628
  */
3518
3629
  class OnBehalfOfCredential {
3519
- /**
3520
- * Creates an instance of the {@link OnBehalfOfCredential} with the details
3521
- * needed to authenticate against Azure Active Directory with a client
3522
- * secret or a path to a PEM certificate, and an user assertion.
3523
- *
3524
- * Example using the `KeyClient` from [\@azure/keyvault-keys](https://www.npmjs.com/package/\@azure/keyvault-keys):
3525
- *
3526
- * ```ts
3527
- * const tokenCredential = new OnBehalfOfCredential({
3528
- * tenantId,
3529
- * clientId,
3530
- * clientSecret, // or `certificatePath: "/path/to/certificate.pem"
3531
- * userAssertionToken: "access-token"
3532
- * });
3533
- * const client = new KeyClient("vault-url", tokenCredential);
3534
- *
3535
- * await client.getKey("key-name");
3536
- * ```
3537
- *
3538
- * @param options - Optional parameters, generally common across credentials.
3539
- */
3540
3630
  constructor(options) {
3541
3631
  this.options = options;
3542
3632
  const { clientSecret } = options;
@@ -3593,7 +3683,7 @@ exports.UsernamePasswordCredential = UsernamePasswordCredential;
3593
3683
  exports.VisualStudioCodeCredential = VisualStudioCodeCredential;
3594
3684
  exports.deserializeAuthenticationRecord = deserializeAuthenticationRecord;
3595
3685
  exports.getDefaultAzureCredential = getDefaultAzureCredential;
3596
- exports.logger = logger$j;
3686
+ exports.logger = logger$k;
3597
3687
  exports.serializeAuthenticationRecord = serializeAuthenticationRecord;
3598
3688
  exports.useIdentityPlugin = useIdentityPlugin;
3599
3689
  //# sourceMappingURL=index.js.map