@azure/identity 2.1.0-beta.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (88) hide show
  1. package/README.md +65 -33
  2. package/dist/index.js +341 -303
  3. package/dist/index.js.map +1 -1
  4. package/dist-esm/src/client/identityClient.js +34 -45
  5. package/dist-esm/src/client/identityClient.js.map +1 -1
  6. package/dist-esm/src/constants.js +4 -0
  7. package/dist-esm/src/constants.js.map +1 -1
  8. package/dist-esm/src/credentials/authorizationCodeCredential.browser.js.map +1 -1
  9. package/dist-esm/src/credentials/authorizationCodeCredential.js +4 -3
  10. package/dist-esm/src/credentials/authorizationCodeCredential.js.map +1 -1
  11. package/dist-esm/src/credentials/azureCliCredential.js +34 -34
  12. package/dist-esm/src/credentials/azureCliCredential.js.map +1 -1
  13. package/dist-esm/src/credentials/azurePowerShellCredential.browser.js.map +1 -1
  14. package/dist-esm/src/credentials/azurePowerShellCredential.js +3 -3
  15. package/dist-esm/src/credentials/azurePowerShellCredential.js.map +1 -1
  16. package/dist-esm/src/credentials/chainedTokenCredential.js +28 -33
  17. package/dist-esm/src/credentials/chainedTokenCredential.js.map +1 -1
  18. package/dist-esm/src/credentials/clientAssertionCredential.browser.js +22 -0
  19. package/dist-esm/src/credentials/clientAssertionCredential.browser.js.map +1 -0
  20. package/dist-esm/src/credentials/clientAssertionCredential.js +45 -0
  21. package/dist-esm/src/credentials/clientAssertionCredential.js.map +1 -0
  22. package/dist-esm/src/credentials/clientCertificateCredential.browser.js.map +1 -1
  23. package/dist-esm/src/credentials/clientCertificateCredential.js +2 -2
  24. package/dist-esm/src/credentials/clientCertificateCredential.js.map +1 -1
  25. package/dist-esm/src/credentials/clientSecretCredential.browser.js +31 -38
  26. package/dist-esm/src/credentials/clientSecretCredential.browser.js.map +1 -1
  27. package/dist-esm/src/credentials/clientSecretCredential.js +2 -2
  28. package/dist-esm/src/credentials/clientSecretCredential.js.map +1 -1
  29. package/dist-esm/src/credentials/defaultAzureCredential.js +3 -3
  30. package/dist-esm/src/credentials/defaultAzureCredential.js.map +1 -1
  31. package/dist-esm/src/credentials/deviceCodeCredential.browser.js.map +1 -1
  32. package/dist-esm/src/credentials/deviceCodeCredential.js +3 -3
  33. package/dist-esm/src/credentials/deviceCodeCredential.js.map +1 -1
  34. package/dist-esm/src/credentials/environmentCredential.js +3 -3
  35. package/dist-esm/src/credentials/environmentCredential.js.map +1 -1
  36. package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js +3 -3
  37. package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js.map +1 -1
  38. package/dist-esm/src/credentials/interactiveBrowserCredential.js +3 -3
  39. package/dist-esm/src/credentials/interactiveBrowserCredential.js.map +1 -1
  40. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js.map +1 -1
  41. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js.map +1 -1
  42. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js.map +1 -1
  43. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js.map +1 -1
  44. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js.map +1 -1
  45. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js +38 -49
  46. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js.map +1 -1
  47. package/dist-esm/src/credentials/managedIdentityCredential/index.js +11 -13
  48. package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
  49. package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +1 -1
  50. package/dist-esm/src/credentials/onBehalfOfCredential.browser.js.map +1 -1
  51. package/dist-esm/src/credentials/onBehalfOfCredential.js +2 -2
  52. package/dist-esm/src/credentials/onBehalfOfCredential.js.map +1 -1
  53. package/dist-esm/src/credentials/usernamePasswordCredential.browser.js +5 -6
  54. package/dist-esm/src/credentials/usernamePasswordCredential.browser.js.map +1 -1
  55. package/dist-esm/src/credentials/usernamePasswordCredential.js +2 -2
  56. package/dist-esm/src/credentials/usernamePasswordCredential.js.map +1 -1
  57. package/dist-esm/src/credentials/visualStudioCodeCredential.browser.js.map +1 -1
  58. package/dist-esm/src/credentials/visualStudioCodeCredential.js.map +1 -1
  59. package/dist-esm/src/errors.js.map +1 -1
  60. package/dist-esm/src/index.js +1 -0
  61. package/dist-esm/src/index.js.map +1 -1
  62. package/dist-esm/src/msal/browserFlows/msalAuthCode.js.map +1 -1
  63. package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js +1 -1
  64. package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js.map +1 -1
  65. package/dist-esm/src/msal/credentials.js.map +1 -1
  66. package/dist-esm/src/msal/flows.js.map +1 -1
  67. package/dist-esm/src/msal/nodeFlows/msalAuthorizationCode.js +2 -2
  68. package/dist-esm/src/msal/nodeFlows/msalAuthorizationCode.js.map +1 -1
  69. package/dist-esm/src/msal/nodeFlows/msalClientAssertion.js +42 -0
  70. package/dist-esm/src/msal/nodeFlows/msalClientAssertion.js.map +1 -0
  71. package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js +3 -2
  72. package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js.map +1 -1
  73. package/dist-esm/src/msal/nodeFlows/msalClientSecret.js.map +1 -1
  74. package/dist-esm/src/msal/nodeFlows/msalDeviceCode.js.map +1 -1
  75. package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js +7 -1
  76. package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js.map +1 -1
  77. package/dist-esm/src/msal/nodeFlows/msalOnBehalfOf.js.map +1 -1
  78. package/dist-esm/src/msal/nodeFlows/msalOpenBrowser.js +2 -1
  79. package/dist-esm/src/msal/nodeFlows/msalOpenBrowser.js.map +1 -1
  80. package/dist-esm/src/msal/nodeFlows/msalUsernamePassword.js.map +1 -1
  81. package/dist-esm/src/msal/utils.js +1 -1
  82. package/dist-esm/src/msal/utils.js.map +1 -1
  83. package/dist-esm/src/util/logging.js.map +1 -1
  84. package/dist-esm/src/util/tracing.js +5 -36
  85. package/dist-esm/src/util/tracing.js.map +1 -1
  86. package/package.json +26 -20
  87. package/types/identity.d.ts +30 -0
  88. package/CHANGELOG.md +0 -544
package/dist/index.js CHANGED
@@ -3,12 +3,12 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var msalNode = require('@azure/msal-node');
6
- var coreTracing = require('@azure/core-tracing');
7
6
  var coreClient = require('@azure/core-client');
8
7
  var coreUtil = require('@azure/core-util');
9
8
  var coreRestPipeline = require('@azure/core-rest-pipeline');
10
9
  var abortController = require('@azure/abort-controller');
11
- var logger$l = require('@azure/logger');
10
+ var coreTracing = require('@azure/core-tracing');
11
+ var logger$m = require('@azure/logger');
12
12
  var msalCommon = require('@azure/msal-common');
13
13
  var uuid = require('uuid');
14
14
  var fs = require('fs');
@@ -186,6 +186,10 @@ function getIdentityTokenEndpointSuffix(tenantId) {
186
186
 
187
187
  // Copyright (c) Microsoft Corporation.
188
188
  // Licensed under the MIT license.
189
+ /**
190
+ * Current version of the `@azure/identity` package.
191
+ */
192
+ const SDK_VERSION = `2.1.0`;
189
193
  /**
190
194
  * The default client ID for authentication
191
195
  * @internal
@@ -231,49 +235,17 @@ const DefaultAuthorityHost = exports.AzureAuthorityHosts.AzurePublicCloud;
231
235
  * Creates a span using the global tracer.
232
236
  * @internal
233
237
  */
234
- const createSpan = coreTracing.createSpanFunction({
235
- packagePrefix: "",
238
+ const tracingClient = coreTracing.createTracingClient({
236
239
  namespace: "Microsoft.AAD",
240
+ packageName: "@azure/identity",
241
+ packageVersion: SDK_VERSION,
237
242
  });
238
- /**
239
- * From: https://github.com/Azure/azure-sdk-for-js/blob/46139daa3317a0d12e8b55b02b9d9cdf1b2e762a/sdk/appconfiguration/app-configuration/src/internal/tracingHelpers.ts
240
- * Traces an operation and properly handles reporting start, end and errors for a given span
241
- *
242
- * @param operationName - Name of a method in the TClient type
243
- * @param options - An options class, typically derived from \@azure/core-rest-pipeline/RequestOptionsBase
244
- * @param fn - The function to call with an options class that properly propagates the span context
245
- *
246
- * @internal
247
- */
248
- async function trace(operationName, options, fn, createSpanFn = createSpan) {
249
- const { updatedOptions, span } = createSpanFn(operationName, options);
250
- try {
251
- // NOTE: we really do need to await on this function here so we can handle any exceptions thrown and properly
252
- // close the span.
253
- const result = await fn(updatedOptions, span);
254
- // otel 0.16+ needs this or else the code ends up being set as UNSET
255
- span.setStatus({
256
- code: coreTracing.SpanStatusCode.OK,
257
- });
258
- return result;
259
- }
260
- catch (err) {
261
- span.setStatus({
262
- code: coreTracing.SpanStatusCode.ERROR,
263
- message: err.message,
264
- });
265
- throw err;
266
- }
267
- finally {
268
- span.end();
269
- }
270
- }
271
243
 
272
244
  // Copyright (c) Microsoft Corporation.
273
245
  /**
274
246
  * The AzureLogger used for all clients within the identity package
275
247
  */
276
- const logger$k = logger$l.createClientLogger("identity");
248
+ const logger$l = logger$m.createClientLogger("identity");
277
249
  /**
278
250
  * 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
251
  * @param supportedEnvVars - List of environment variable names
@@ -313,7 +285,7 @@ function formatError(scope, error) {
313
285
  * `[title] => [message]`
314
286
  *
315
287
  */
316
- function credentialLoggerInstance(title, parent, log = logger$k) {
288
+ function credentialLoggerInstance(title, parent, log = logger$l) {
317
289
  const fullTitle = parent ? `${parent.fullTitle} ${title}` : title;
318
290
  function info(message) {
319
291
  log.info(`${fullTitle} =>`, message);
@@ -338,7 +310,7 @@ function credentialLoggerInstance(title, parent, log = logger$k) {
338
310
  * `[title] => getToken() => [message]`
339
311
  *
340
312
  */
341
- function credentialLogger(title, log = logger$k) {
313
+ function credentialLogger(title, log = logger$l) {
342
314
  const credLogger = credentialLoggerInstance(title, undefined, log);
343
315
  return Object.assign(Object.assign({}, credLogger), { parent: log, getToken: credentialLoggerInstance("=> getToken()", credLogger, log) });
344
316
  }
@@ -368,7 +340,7 @@ function getIdentityClientAuthorityHost(options) {
368
340
  class IdentityClient extends coreClient.ServiceClient {
369
341
  constructor(options) {
370
342
  var _a, _b;
371
- const packageDetails = `azsdk-js-identity/2.1.0-beta.2`;
343
+ const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;
372
344
  const userAgentPrefix = ((_a = options === null || options === void 0 ? void 0 : options.userAgentOptions) === null || _a === void 0 ? void 0 : _a.userAgentPrefix)
373
345
  ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
374
346
  : `${packageDetails}`;
@@ -386,7 +358,7 @@ class IdentityClient extends coreClient.ServiceClient {
386
358
  this.allowLoggingAccountIdentifiers = (_b = options === null || options === void 0 ? void 0 : options.loggingOptions) === null || _b === void 0 ? void 0 : _b.allowLoggingAccountIdentifiers;
387
359
  }
388
360
  async sendTokenRequest(request, expiresOnParser) {
389
- logger$k.info(`IdentityClient: sending token request to [${request.url}]`);
361
+ logger$l.info(`IdentityClient: sending token request to [${request.url}]`);
390
362
  const response = await this.sendRequest(request);
391
363
  expiresOnParser =
392
364
  expiresOnParser ||
@@ -406,21 +378,20 @@ class IdentityClient extends coreClient.ServiceClient {
406
378
  },
407
379
  refreshToken: parsedBody.refresh_token,
408
380
  };
409
- logger$k.info(`IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`);
381
+ logger$l.info(`IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`);
410
382
  return token;
411
383
  }
412
384
  else {
413
385
  const error = new AuthenticationError(response.status, response.bodyAsText);
414
- logger$k.warning(`IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`);
386
+ logger$l.warning(`IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`);
415
387
  throw error;
416
388
  }
417
389
  }
418
- async refreshAccessToken(tenantId, clientId, scopes, refreshToken, clientSecret, expiresOnParser, options) {
390
+ async refreshAccessToken(tenantId, clientId, scopes, refreshToken, clientSecret, expiresOnParser, options = {}) {
419
391
  if (refreshToken === undefined) {
420
392
  return null;
421
393
  }
422
- logger$k.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`);
423
- const { span, updatedOptions } = createSpan("IdentityClient-refreshAccessToken", options);
394
+ logger$l.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`);
424
395
  const refreshParams = {
425
396
  grant_type: "refresh_token",
426
397
  client_id: clientId,
@@ -431,48 +402,39 @@ class IdentityClient extends coreClient.ServiceClient {
431
402
  refreshParams.client_secret = clientSecret;
432
403
  }
433
404
  const query = new URLSearchParams(refreshParams);
434
- try {
435
- const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);
436
- const request = coreRestPipeline.createPipelineRequest({
437
- url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,
438
- method: "POST",
439
- body: query.toString(),
440
- abortSignal: options && options.abortSignal,
441
- headers: coreRestPipeline.createHttpHeaders({
442
- Accept: "application/json",
443
- "Content-Type": "application/x-www-form-urlencoded",
444
- }),
445
- tracingOptions: updatedOptions === null || updatedOptions === void 0 ? void 0 : updatedOptions.tracingOptions,
446
- });
447
- const response = await this.sendTokenRequest(request, expiresOnParser);
448
- logger$k.info(`IdentityClient: refreshed token for client ID: ${clientId}`);
449
- return response;
450
- }
451
- catch (err) {
452
- if (err.name === AuthenticationErrorName &&
453
- err.errorResponse.error === "interaction_required") {
454
- // It's likely that the refresh token has expired, so
455
- // return null so that the credential implementation will
456
- // initiate the authentication flow again.
457
- logger$k.info(`IdentityClient: interaction required for client ID: ${clientId}`);
458
- span.setStatus({
459
- code: coreTracing.SpanStatusCode.ERROR,
460
- message: err.message,
405
+ return tracingClient.withSpan("IdentityClient.refreshAccessToken", options, async (updatedOptions) => {
406
+ try {
407
+ const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);
408
+ const request = coreRestPipeline.createPipelineRequest({
409
+ url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,
410
+ method: "POST",
411
+ body: query.toString(),
412
+ abortSignal: options.abortSignal,
413
+ headers: coreRestPipeline.createHttpHeaders({
414
+ Accept: "application/json",
415
+ "Content-Type": "application/x-www-form-urlencoded",
416
+ }),
417
+ tracingOptions: updatedOptions.tracingOptions,
461
418
  });
462
- return null;
419
+ const response = await this.sendTokenRequest(request, expiresOnParser);
420
+ logger$l.info(`IdentityClient: refreshed token for client ID: ${clientId}`);
421
+ return response;
463
422
  }
464
- else {
465
- logger$k.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`);
466
- span.setStatus({
467
- code: coreTracing.SpanStatusCode.ERROR,
468
- message: err.message,
469
- });
470
- throw err;
423
+ catch (err) {
424
+ if (err.name === AuthenticationErrorName &&
425
+ err.errorResponse.error === "interaction_required") {
426
+ // It's likely that the refresh token has expired, so
427
+ // return null so that the credential implementation will
428
+ // initiate the authentication flow again.
429
+ logger$l.info(`IdentityClient: interaction required for client ID: ${clientId}`);
430
+ return null;
431
+ }
432
+ else {
433
+ logger$l.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`);
434
+ throw err;
435
+ }
471
436
  }
472
- }
473
- finally {
474
- span.end();
475
- }
437
+ });
476
438
  }
477
439
  // Here is a custom layer that allows us to abort requests that go through MSAL,
478
440
  // since MSAL doesn't allow us to pass options all the way through.
@@ -570,10 +532,10 @@ class IdentityClient extends coreClient.ServiceClient {
570
532
  }
571
533
  const base64Metadata = accessToken.split(".")[1];
572
534
  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}`);
535
+ logger$l.info(`[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${upn || unavailableUpn}. Object ID (user): ${oid}`);
574
536
  }
575
537
  catch (e) {
576
- logger$k.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e.message);
538
+ logger$l.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e.message);
577
539
  }
578
540
  }
579
541
  }
@@ -989,6 +951,9 @@ class MsalNode extends MsalBaseUtilities {
989
951
  this.msalConfig = this.defaultNodeMsalConfig(options);
990
952
  this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
991
953
  this.clientId = this.msalConfig.auth.clientId;
954
+ if (options === null || options === void 0 ? void 0 : options.getAssertion) {
955
+ this.getAssertion = options.getAssertion;
956
+ }
992
957
  // If persistence has been configured
993
958
  if (persistenceProvider !== undefined && ((_a = options.tokenCachePersistenceOptions) === null || _a === void 0 ? void 0 : _a.enabled)) {
994
959
  this.createCachePlugin = () => persistenceProvider(options.tokenCachePersistenceOptions);
@@ -1055,6 +1020,9 @@ class MsalNode extends MsalBaseUtilities {
1055
1020
  };
1056
1021
  }
1057
1022
  this.publicApp = new msalNode__namespace.PublicClientApplication(this.msalConfig);
1023
+ if (this.getAssertion) {
1024
+ this.msalConfig.auth.clientAssertion = await this.getAssertion();
1025
+ }
1058
1026
  // The confidential client requires either a secret, assertion or certificate.
1059
1027
  if (this.msalConfig.auth.clientSecret ||
1060
1028
  this.msalConfig.auth.clientAssertion ||
@@ -1184,7 +1152,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
1184
1152
  // Copyright (c) Microsoft Corporation.
1185
1153
  const CommonTenantId = "common";
1186
1154
  const AzureAccountClientId = "aebc6443-996d-45c2-90f0-388ff96faa56"; // VSC: 'aebc6443-996d-45c2-90f0-388ff96faa56'
1187
- const logger$j = credentialLogger("VisualStudioCodeCredential");
1155
+ const logger$k = credentialLogger("VisualStudioCodeCredential");
1188
1156
  let findCredentials = undefined;
1189
1157
  const vsCodeCredentialControl = {
1190
1158
  setVsCodeCredentialFinder(finder) {
@@ -1237,7 +1205,7 @@ function getPropertyFromVSCode(property) {
1237
1205
  }
1238
1206
  }
1239
1207
  catch (e) {
1240
- logger$j.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`);
1208
+ logger$k.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`);
1241
1209
  return;
1242
1210
  }
1243
1211
  }
@@ -1265,7 +1233,7 @@ class VisualStudioCodeCredential {
1265
1233
  const authorityHost = mapVSCodeAuthorityHosts[this.cloudName];
1266
1234
  this.identityClient = new IdentityClient(Object.assign({ authorityHost }, options));
1267
1235
  if (options && options.tenantId) {
1268
- checkTenantId(logger$j, options.tenantId);
1236
+ checkTenantId(logger$k, options.tenantId);
1269
1237
  this.tenantId = options.tenantId;
1270
1238
  }
1271
1239
  else {
@@ -1317,7 +1285,7 @@ class VisualStudioCodeCredential {
1317
1285
  // Check to make sure the scope we get back is a valid scope
1318
1286
  if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) {
1319
1287
  const error = new Error("Invalid scope was specified by the user or calling client");
1320
- logger$j.getToken.info(formatError(scopes, error));
1288
+ logger$k.getToken.info(formatError(scopes, error));
1321
1289
  throw error;
1322
1290
  }
1323
1291
  if (scopeString.indexOf("offline_access") < 0) {
@@ -1337,18 +1305,18 @@ class VisualStudioCodeCredential {
1337
1305
  if (refreshToken) {
1338
1306
  const tokenResponse = await this.identityClient.refreshAccessToken(tenantId, AzureAccountClientId, scopeString, refreshToken, undefined);
1339
1307
  if (tokenResponse) {
1340
- logger$j.getToken.info(formatSuccess(scopes));
1308
+ logger$k.getToken.info(formatSuccess(scopes));
1341
1309
  return tokenResponse.accessToken;
1342
1310
  }
1343
1311
  else {
1344
1312
  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.");
1345
- logger$j.getToken.info(formatError(scopes, error));
1313
+ logger$k.getToken.info(formatError(scopes, error));
1346
1314
  throw error;
1347
1315
  }
1348
1316
  }
1349
1317
  else {
1350
1318
  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.");
1351
- logger$j.getToken.info(formatError(scopes, error));
1319
+ logger$k.getToken.info(formatError(scopes, error));
1352
1320
  throw error;
1353
1321
  }
1354
1322
  }
@@ -1399,7 +1367,7 @@ function useIdentityPlugin(plugin) {
1399
1367
  /**
1400
1368
  * @internal
1401
1369
  */
1402
- const logger$i = credentialLogger("ChainedTokenCredential");
1370
+ const logger$j = credentialLogger("ChainedTokenCredential");
1403
1371
  /**
1404
1372
  * Enables multiple `TokenCredential` implementations to be tried in order
1405
1373
  * until one of the getToken methods returns an access token.
@@ -1438,42 +1406,38 @@ class ChainedTokenCredential {
1438
1406
  * @param options - The options used to configure any requests this
1439
1407
  * `TokenCredential` implementation might make.
1440
1408
  */
1441
- async getToken(scopes, options) {
1409
+ async getToken(scopes, options = {}) {
1442
1410
  let token = null;
1443
1411
  let successfulCredentialName = "";
1444
1412
  const errors = [];
1445
- const { span, updatedOptions } = createSpan("ChainedTokenCredential.getToken", options);
1446
- for (let i = 0; i < this._sources.length && token === null; i++) {
1447
- try {
1448
- token = await this._sources[i].getToken(scopes, updatedOptions);
1449
- successfulCredentialName = this._sources[i].constructor.name;
1450
- }
1451
- catch (err) {
1452
- if (err.name === "CredentialUnavailableError" ||
1453
- err.name === "AuthenticationRequiredError") {
1454
- errors.push(err);
1413
+ return tracingClient.withSpan("ChainedTokenCredential.getToken", options, async (updatedOptions) => {
1414
+ for (let i = 0; i < this._sources.length && token === null; i++) {
1415
+ try {
1416
+ token = await this._sources[i].getToken(scopes, updatedOptions);
1417
+ successfulCredentialName = this._sources[i].constructor.name;
1455
1418
  }
1456
- else {
1457
- logger$i.getToken.info(formatError(scopes, err));
1458
- throw err;
1419
+ catch (err) {
1420
+ if (err.name === "CredentialUnavailableError" ||
1421
+ err.name === "AuthenticationRequiredError") {
1422
+ errors.push(err);
1423
+ }
1424
+ else {
1425
+ logger$j.getToken.info(formatError(scopes, err));
1426
+ throw err;
1427
+ }
1459
1428
  }
1460
1429
  }
1461
- }
1462
- if (!token && errors.length > 0) {
1463
- const err = new AggregateAuthenticationError(errors, "ChainedTokenCredential authentication failed.");
1464
- span.setStatus({
1465
- code: coreTracing.SpanStatusCode.ERROR,
1466
- message: err.message,
1467
- });
1468
- logger$i.getToken.info(formatError(scopes, err));
1469
- throw err;
1470
- }
1471
- span.end();
1472
- logger$i.getToken.info(`Result for ${successfulCredentialName}: ${formatSuccess(scopes)}`);
1473
- if (token === null) {
1474
- throw new CredentialUnavailableError("Failed to retrieve a valid token");
1475
- }
1476
- return token;
1430
+ if (!token && errors.length > 0) {
1431
+ const err = new AggregateAuthenticationError(errors, "ChainedTokenCredential authentication failed.");
1432
+ logger$j.getToken.info(formatError(scopes, err));
1433
+ throw err;
1434
+ }
1435
+ logger$j.getToken.info(`Result for ${successfulCredentialName}: ${formatSuccess(scopes)}`);
1436
+ if (token === null) {
1437
+ throw new CredentialUnavailableError("Failed to retrieve a valid token");
1438
+ }
1439
+ return token;
1440
+ });
1477
1441
  }
1478
1442
  }
1479
1443
 
@@ -1547,7 +1511,7 @@ const cliCredentialInternals = {
1547
1511
  });
1548
1512
  },
1549
1513
  };
1550
- const logger$h = credentialLogger("AzureCliCredential");
1514
+ const logger$i = credentialLogger("AzureCliCredential");
1551
1515
  /**
1552
1516
  * This credential will use the currently logged-in user login information
1553
1517
  * via the Azure CLI ('az') commandline tool.
@@ -1574,56 +1538,57 @@ class AzureCliCredential {
1574
1538
  * @param options - The options used to configure any requests this
1575
1539
  * TokenCredential implementation might make.
1576
1540
  */
1577
- async getToken(scopes, options) {
1541
+ async getToken(scopes, options = {}) {
1578
1542
  const tenantId = processMultiTenantRequest(this.tenantId, options);
1579
1543
  if (tenantId) {
1580
- checkTenantId(logger$h, tenantId);
1544
+ checkTenantId(logger$i, tenantId);
1581
1545
  }
1582
1546
  const scope = typeof scopes === "string" ? scopes : scopes[0];
1583
- logger$h.getToken.info(`Using the scope ${scope}`);
1584
- ensureValidScope(scope, logger$h);
1547
+ logger$i.getToken.info(`Using the scope ${scope}`);
1548
+ ensureValidScope(scope, logger$i);
1585
1549
  const resource = getScopeResource(scope);
1586
- let responseData = "";
1587
- const { span } = createSpan(`${this.constructor.name}.getToken`, options);
1588
- try {
1589
- const obj = await cliCredentialInternals.getAzureCliAccessToken(resource, tenantId);
1590
- if (obj.stderr) {
1591
- const isLoginError = obj.stderr.match("(.*)az login(.*)");
1592
- const isNotInstallError = obj.stderr.match("az:(.*)not found") || obj.stderr.startsWith("'az' is not recognized");
1550
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {
1551
+ var _a, _b, _c, _d;
1552
+ try {
1553
+ const obj = await cliCredentialInternals.getAzureCliAccessToken(resource, tenantId);
1554
+ const specificScope = (_a = obj.stderr) === null || _a === void 0 ? void 0 : _a.match("(.*)az login --scope(.*)");
1555
+ const isLoginError = ((_b = obj.stderr) === null || _b === void 0 ? void 0 : _b.match("(.*)az login(.*)")) && !specificScope;
1556
+ const isNotInstallError = ((_c = obj.stderr) === null || _c === void 0 ? void 0 : _c.match("az:(.*)not found")) || ((_d = obj.stderr) === null || _d === void 0 ? void 0 : _d.startsWith("'az' is not recognized"));
1593
1557
  if (isNotInstallError) {
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'.");
1595
- logger$h.getToken.info(formatError(scopes, error));
1558
+ 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$i.getToken.info(formatError(scopes, error));
1596
1560
  throw error;
1597
1561
  }
1598
- else if (isLoginError) {
1562
+ if (isLoginError) {
1599
1563
  const error = new CredentialUnavailableError("Please run 'az login' from a command prompt to authenticate before using this credential.");
1600
- logger$h.getToken.info(formatError(scopes, error));
1564
+ logger$i.getToken.info(formatError(scopes, error));
1601
1565
  throw error;
1602
1566
  }
1603
- const error = new CredentialUnavailableError(obj.stderr);
1604
- logger$h.getToken.info(formatError(scopes, error));
1605
- throw error;
1567
+ try {
1568
+ const responseData = obj.stdout;
1569
+ const response = JSON.parse(responseData);
1570
+ logger$i.getToken.info(formatSuccess(scopes));
1571
+ const returnValue = {
1572
+ token: response.accessToken,
1573
+ expiresOnTimestamp: new Date(response.expiresOn).getTime(),
1574
+ };
1575
+ return returnValue;
1576
+ }
1577
+ catch (e) {
1578
+ if (obj.stderr) {
1579
+ throw new CredentialUnavailableError(obj.stderr);
1580
+ }
1581
+ throw e;
1582
+ }
1606
1583
  }
1607
- else {
1608
- responseData = obj.stdout;
1609
- const response = JSON.parse(responseData);
1610
- logger$h.getToken.info(formatSuccess(scopes));
1611
- const returnValue = {
1612
- token: response.accessToken,
1613
- expiresOnTimestamp: new Date(response.expiresOn).getTime(),
1614
- };
1615
- return returnValue;
1584
+ catch (err) {
1585
+ const error = err.name === "CredentialUnavailableError"
1586
+ ? err
1587
+ : new CredentialUnavailableError(err.message || "Unknown error while trying to retrieve the access token");
1588
+ logger$i.getToken.info(formatError(scopes, error));
1589
+ throw error;
1616
1590
  }
1617
- }
1618
- catch (err) {
1619
- const error = new Error(err.message || "Unknown error while trying to retrieve the access token");
1620
- span.setStatus({
1621
- code: coreTracing.SpanStatusCode.ERROR,
1622
- message: error.message,
1623
- });
1624
- logger$h.getToken.info(formatError(scopes, error));
1625
- throw error;
1626
- }
1591
+ });
1627
1592
  }
1628
1593
  }
1629
1594
 
@@ -1658,7 +1623,7 @@ const processUtils = {
1658
1623
  };
1659
1624
 
1660
1625
  // Copyright (c) Microsoft Corporation.
1661
- const logger$g = credentialLogger("AzurePowerShellCredential");
1626
+ const logger$h = credentialLogger("AzurePowerShellCredential");
1662
1627
  const isWindows = process.platform === "win32";
1663
1628
  /**
1664
1629
  * Returns a platform-appropriate command name by appending ".exe" on Windows.
@@ -1786,18 +1751,18 @@ class AzurePowerShellCredential {
1786
1751
  * @param options - The options used to configure any requests this TokenCredential implementation might make.
1787
1752
  */
1788
1753
  async getToken(scopes, options = {}) {
1789
- return trace(`${this.constructor.name}.getToken`, options, async () => {
1754
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {
1790
1755
  const tenantId = processMultiTenantRequest(this.tenantId, options);
1791
1756
  if (tenantId) {
1792
- checkTenantId(logger$g, tenantId);
1757
+ checkTenantId(logger$h, tenantId);
1793
1758
  }
1794
1759
  const scope = typeof scopes === "string" ? scopes : scopes[0];
1795
- ensureValidScope(scope, logger$g);
1796
- logger$g.getToken.info(`Using the scope ${scope}`);
1760
+ ensureValidScope(scope, logger$h);
1761
+ logger$h.getToken.info(`Using the scope ${scope}`);
1797
1762
  const resource = getScopeResource(scope);
1798
1763
  try {
1799
1764
  const response = await this.getAzurePowerShellAccessToken(resource, tenantId);
1800
- logger$g.getToken.info(formatSuccess(scopes));
1765
+ logger$h.getToken.info(formatSuccess(scopes));
1801
1766
  return {
1802
1767
  token: response.Token,
1803
1768
  expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),
@@ -1806,16 +1771,16 @@ class AzurePowerShellCredential {
1806
1771
  catch (err) {
1807
1772
  if (isNotInstalledError(err)) {
1808
1773
  const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);
1809
- logger$g.getToken.info(formatError(scope, error));
1774
+ logger$h.getToken.info(formatError(scope, error));
1810
1775
  throw error;
1811
1776
  }
1812
1777
  else if (isLoginError(err)) {
1813
1778
  const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);
1814
- logger$g.getToken.info(formatError(scope, error));
1779
+ logger$h.getToken.info(formatError(scope, error));
1815
1780
  throw error;
1816
1781
  }
1817
1782
  const error = new CredentialUnavailableError(`${err}. ${powerShellPublicErrorMessages.troubleshoot}`);
1818
- logger$g.getToken.info(formatError(scope, error));
1783
+ logger$h.getToken.info(formatError(scope, error));
1819
1784
  throw error;
1820
1785
  }
1821
1786
  });
@@ -1853,7 +1818,7 @@ class MsalClientSecret extends MsalNode {
1853
1818
  }
1854
1819
 
1855
1820
  // Copyright (c) Microsoft Corporation.
1856
- const logger$f = credentialLogger("ClientSecretCredential");
1821
+ const logger$g = credentialLogger("ClientSecretCredential");
1857
1822
  /**
1858
1823
  * Enables authentication to Azure Active Directory using a client secret
1859
1824
  * that was generated for an App Registration. More information on how
@@ -1877,7 +1842,7 @@ class ClientSecretCredential {
1877
1842
  if (!tenantId || !clientId || !clientSecret) {
1878
1843
  throw new Error("ClientSecretCredential: tenantId, clientId, and clientSecret are required parameters. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");
1879
1844
  }
1880
- this.msalFlow = new MsalClientSecret(Object.assign(Object.assign({}, options), { logger: logger$f,
1845
+ this.msalFlow = new MsalClientSecret(Object.assign(Object.assign({}, options), { logger: logger$g,
1881
1846
  clientId,
1882
1847
  tenantId,
1883
1848
  clientSecret, tokenCredentialOptions: options }));
@@ -1891,7 +1856,7 @@ class ClientSecretCredential {
1891
1856
  * TokenCredential implementation might make.
1892
1857
  */
1893
1858
  async getToken(scopes, options = {}) {
1894
- return trace(`${this.constructor.name}.getToken`, options, async (newOptions) => {
1859
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
1895
1860
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
1896
1861
  return this.msalFlow.getToken(arrayScopes, newOptions);
1897
1862
  });
@@ -1967,13 +1932,14 @@ class MsalClientCertificate extends MsalNode {
1967
1932
  }
1968
1933
  async doGetToken(scopes, options = {}) {
1969
1934
  try {
1970
- const result = await this.confidentialApp.acquireTokenByClientCredential({
1935
+ const clientCredReq = {
1971
1936
  scopes,
1972
1937
  correlationId: options.correlationId,
1973
1938
  azureRegion: this.azureRegion,
1974
1939
  authority: options.authority,
1975
1940
  claims: options.claims,
1976
- });
1941
+ };
1942
+ const result = await this.confidentialApp.acquireTokenByClientCredential(clientCredReq);
1977
1943
  // Even though we're providing the same default in memory persistence cache that we use for DeviceCodeCredential,
1978
1944
  // The Client Credential flow does not return the account information from the authentication service,
1979
1945
  // so each time getToken gets called, we will have to acquire a new token through the service.
@@ -1987,7 +1953,7 @@ class MsalClientCertificate extends MsalNode {
1987
1953
 
1988
1954
  // Copyright (c) Microsoft Corporation.
1989
1955
  const credentialName$2 = "ClientCertificateCredential";
1990
- const logger$e = credentialLogger(credentialName$2);
1956
+ const logger$f = credentialLogger(credentialName$2);
1991
1957
  /**
1992
1958
  * Enables authentication to Azure Active Directory using a PEM-encoded
1993
1959
  * certificate that is assigned to an App Registration. More information
@@ -2016,7 +1982,7 @@ class ClientCertificateCredential {
2016
1982
  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.`);
2017
1983
  }
2018
1984
  this.msalFlow = new MsalClientCertificate(Object.assign(Object.assign({}, options), { configuration,
2019
- logger: logger$e,
1985
+ logger: logger$f,
2020
1986
  clientId,
2021
1987
  tenantId, sendCertificateChain: options.sendCertificateChain, tokenCredentialOptions: options }));
2022
1988
  }
@@ -2029,7 +1995,7 @@ class ClientCertificateCredential {
2029
1995
  * TokenCredential implementation might make.
2030
1996
  */
2031
1997
  async getToken(scopes, options = {}) {
2032
- return trace(`${credentialName$2}.getToken`, options, async (newOptions) => {
1998
+ return tracingClient.withSpan(`${credentialName$2}.getToken`, options, async (newOptions) => {
2033
1999
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
2034
2000
  return this.msalFlow.getToken(arrayScopes, newOptions);
2035
2001
  });
@@ -2067,7 +2033,7 @@ class MsalUsernamePassword extends MsalNode {
2067
2033
  }
2068
2034
 
2069
2035
  // Copyright (c) Microsoft Corporation.
2070
- const logger$d = credentialLogger("UsernamePasswordCredential");
2036
+ const logger$e = credentialLogger("UsernamePasswordCredential");
2071
2037
  /**
2072
2038
  * Enables authentication to Azure Active Directory with a user's
2073
2039
  * username and password. This credential requires a high degree of
@@ -2090,7 +2056,7 @@ class UsernamePasswordCredential {
2090
2056
  if (!tenantId || !clientId || !username || !password) {
2091
2057
  throw new Error("UsernamePasswordCredential: tenantId, clientId, username and password are required parameters. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");
2092
2058
  }
2093
- this.msalFlow = new MsalUsernamePassword(Object.assign(Object.assign({}, options), { logger: logger$d,
2059
+ this.msalFlow = new MsalUsernamePassword(Object.assign(Object.assign({}, options), { logger: logger$e,
2094
2060
  clientId,
2095
2061
  tenantId,
2096
2062
  username,
@@ -2109,7 +2075,7 @@ class UsernamePasswordCredential {
2109
2075
  * TokenCredential implementation might make.
2110
2076
  */
2111
2077
  async getToken(scopes, options = {}) {
2112
- return trace(`${this.constructor.name}.getToken`, options, async (newOptions) => {
2078
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
2113
2079
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
2114
2080
  return this.msalFlow.getToken(arrayScopes, newOptions);
2115
2081
  });
@@ -2133,7 +2099,7 @@ const AllSupportedEnvironmentVariables = [
2133
2099
  "AZURE_PASSWORD",
2134
2100
  ];
2135
2101
  const credentialName$1 = "EnvironmentCredential";
2136
- const logger$c = credentialLogger(credentialName$1);
2102
+ const logger$d = credentialLogger(credentialName$1);
2137
2103
  /**
2138
2104
  * Enables authentication to Azure Active Directory using client secret
2139
2105
  * details configured in environment variables
@@ -2163,26 +2129,26 @@ class EnvironmentCredential {
2163
2129
  // Keep track of any missing environment variables for error details
2164
2130
  this._credential = undefined;
2165
2131
  const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(", ");
2166
- logger$c.info(`Found the following environment variables: ${assigned}`);
2132
+ logger$d.info(`Found the following environment variables: ${assigned}`);
2167
2133
  const tenantId = process.env.AZURE_TENANT_ID, clientId = process.env.AZURE_CLIENT_ID, clientSecret = process.env.AZURE_CLIENT_SECRET;
2168
2134
  if (tenantId) {
2169
- checkTenantId(logger$c, tenantId);
2135
+ checkTenantId(logger$d, tenantId);
2170
2136
  }
2171
2137
  if (tenantId && clientId && clientSecret) {
2172
- logger$c.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`);
2138
+ logger$d.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`);
2173
2139
  this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
2174
2140
  return;
2175
2141
  }
2176
2142
  const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;
2177
2143
  if (tenantId && clientId && certificatePath) {
2178
- logger$c.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`);
2144
+ logger$d.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`);
2179
2145
  this._credential = new ClientCertificateCredential(tenantId, clientId, { certificatePath }, options);
2180
2146
  return;
2181
2147
  }
2182
2148
  const username = process.env.AZURE_USERNAME;
2183
2149
  const password = process.env.AZURE_PASSWORD;
2184
2150
  if (tenantId && clientId && username && password) {
2185
- logger$c.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`);
2151
+ logger$d.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`);
2186
2152
  this._credential = new UsernamePasswordCredential(tenantId, clientId, username, password, options);
2187
2153
  }
2188
2154
  }
@@ -2193,11 +2159,11 @@ class EnvironmentCredential {
2193
2159
  * @param options - Optional parameters. See {@link GetTokenOptions}.
2194
2160
  */
2195
2161
  async getToken(scopes, options = {}) {
2196
- return trace(`${credentialName$1}.getToken`, options, async (newOptions) => {
2162
+ return tracingClient.withSpan(`${credentialName$1}.getToken`, options, async (newOptions) => {
2197
2163
  if (this._credential) {
2198
2164
  try {
2199
2165
  const result = await this._credential.getToken(scopes, newOptions);
2200
- logger$c.getToken.info(formatSuccess(scopes));
2166
+ logger$d.getToken.info(formatSuccess(scopes));
2201
2167
  return result;
2202
2168
  }
2203
2169
  catch (err) {
@@ -2205,7 +2171,7 @@ class EnvironmentCredential {
2205
2171
  error: `${credentialName$1} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,
2206
2172
  error_description: err.message.toString().split("More details:").join(""),
2207
2173
  });
2208
- logger$c.getToken.info(formatError(scopes, authenticationError));
2174
+ logger$d.getToken.info(formatError(scopes, authenticationError));
2209
2175
  throw authenticationError;
2210
2176
  }
2211
2177
  }
@@ -2252,7 +2218,7 @@ function mapScopesToResource(scopes) {
2252
2218
 
2253
2219
  // Copyright (c) Microsoft Corporation.
2254
2220
  const msiName$6 = "ManagedIdentityCredential - AppServiceMSI 2017";
2255
- const logger$b = credentialLogger(msiName$6);
2221
+ const logger$c = credentialLogger(msiName$6);
2256
2222
  /**
2257
2223
  * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.
2258
2224
  */
@@ -2299,22 +2265,22 @@ const appServiceMsi2017 = {
2299
2265
  async isAvailable({ scopes }) {
2300
2266
  const resource = mapScopesToResource(scopes);
2301
2267
  if (!resource) {
2302
- logger$b.info(`${msiName$6}: Unavailable. Multiple scopes are not supported.`);
2268
+ logger$c.info(`${msiName$6}: Unavailable. Multiple scopes are not supported.`);
2303
2269
  return false;
2304
2270
  }
2305
2271
  const env = process.env;
2306
2272
  const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);
2307
2273
  if (!result) {
2308
- logger$b.info(`${msiName$6}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`);
2274
+ logger$c.info(`${msiName$6}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`);
2309
2275
  }
2310
2276
  return result;
2311
2277
  },
2312
2278
  async getToken(configuration, getTokenOptions = {}) {
2313
2279
  const { identityClient, scopes, clientId, resourceId } = configuration;
2314
2280
  if (resourceId) {
2315
- logger$b.warning(`${msiName$6}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
2281
+ logger$c.warning(`${msiName$6}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
2316
2282
  }
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].`);
2283
+ logger$c.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
2284
  const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$6(scopes, clientId)), {
2319
2285
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
2320
2286
  allowInsecureConnection: true }));
@@ -2325,7 +2291,7 @@ const appServiceMsi2017 = {
2325
2291
 
2326
2292
  // Copyright (c) Microsoft Corporation.
2327
2293
  const msiName$5 = "ManagedIdentityCredential - CloudShellMSI";
2328
- const logger$a = credentialLogger(msiName$5);
2294
+ const logger$b = credentialLogger(msiName$5);
2329
2295
  /**
2330
2296
  * Generates the options used on the request for an access token.
2331
2297
  */
@@ -2367,24 +2333,24 @@ const cloudShellMsi = {
2367
2333
  async isAvailable({ scopes }) {
2368
2334
  const resource = mapScopesToResource(scopes);
2369
2335
  if (!resource) {
2370
- logger$a.info(`${msiName$5}: Unavailable. Multiple scopes are not supported.`);
2336
+ logger$b.info(`${msiName$5}: Unavailable. Multiple scopes are not supported.`);
2371
2337
  return false;
2372
2338
  }
2373
2339
  const result = Boolean(process.env.MSI_ENDPOINT);
2374
2340
  if (!result) {
2375
- logger$a.info(`${msiName$5}: Unavailable. The environment variable MSI_ENDPOINT is needed.`);
2341
+ logger$b.info(`${msiName$5}: Unavailable. The environment variable MSI_ENDPOINT is needed.`);
2376
2342
  }
2377
2343
  return result;
2378
2344
  },
2379
2345
  async getToken(configuration, getTokenOptions = {}) {
2380
2346
  const { identityClient, scopes, clientId, resourceId } = configuration;
2381
2347
  if (clientId) {
2382
- logger$a.warning(`${msiName$5}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
2348
+ logger$b.warning(`${msiName$5}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
2383
2349
  }
2384
2350
  if (resourceId) {
2385
- logger$a.warning(`${msiName$5}: user defined managed Identity by resource Id not supported. The argument resourceId might be ignored by the service.`);
2351
+ logger$b.warning(`${msiName$5}: user defined managed Identity by resource Id not supported. The argument resourceId might be ignored by the service.`);
2386
2352
  }
2387
- logger$a.info(`${msiName$5}: Using the endpoint coming form the environment variable MSI_ENDPOINT = ${process.env.MSI_ENDPOINT}.`);
2353
+ logger$b.info(`${msiName$5}: Using the endpoint coming form the environment variable MSI_ENDPOINT = ${process.env.MSI_ENDPOINT}.`);
2388
2354
  const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$5(scopes, clientId, resourceId)), {
2389
2355
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
2390
2356
  allowInsecureConnection: true }));
@@ -2395,7 +2361,7 @@ const cloudShellMsi = {
2395
2361
 
2396
2362
  // Copyright (c) Microsoft Corporation.
2397
2363
  const msiName$4 = "ManagedIdentityCredential - IMDS";
2398
- const logger$9 = credentialLogger(msiName$4);
2364
+ const logger$a = credentialLogger(msiName$4);
2399
2365
  /**
2400
2366
  * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.
2401
2367
  */
@@ -2403,13 +2369,13 @@ function expiresOnParser$2(requestBody) {
2403
2369
  if (requestBody.expires_on) {
2404
2370
  // Use the expires_on timestamp if it's available
2405
2371
  const expires = +requestBody.expires_on * 1000;
2406
- logger$9.info(`${msiName$4}: Using expires_on: ${expires} (original value: ${requestBody.expires_on})`);
2372
+ logger$a.info(`${msiName$4}: Using expires_on: ${expires} (original value: ${requestBody.expires_on})`);
2407
2373
  return expires;
2408
2374
  }
2409
2375
  else {
2410
2376
  // If these aren't possible, use expires_in and calculate a timestamp
2411
2377
  const expires = Date.now() + requestBody.expires_in * 1000;
2412
- logger$9.info(`${msiName$4}: IMDS using expires_in: ${expires} (original value: ${requestBody.expires_in})`);
2378
+ logger$a.info(`${msiName$4}: IMDS using expires_in: ${expires} (original value: ${requestBody.expires_in})`);
2413
2379
  return expires;
2414
2380
  }
2415
2381
  }
@@ -2466,14 +2432,12 @@ const imdsMsiRetryConfig = {
2466
2432
  * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.
2467
2433
  */
2468
2434
  const imdsMsi = {
2469
- async isAvailable({ scopes, identityClient, clientId, resourceId, getTokenOptions, }) {
2470
- var _a, _b;
2435
+ async isAvailable({ scopes, identityClient, clientId, resourceId, getTokenOptions = {}, }) {
2471
2436
  const resource = mapScopesToResource(scopes);
2472
2437
  if (!resource) {
2473
- logger$9.info(`${msiName$4}: Unavailable. Multiple scopes are not supported.`);
2438
+ logger$a.info(`${msiName$4}: Unavailable. Multiple scopes are not supported.`);
2474
2439
  return false;
2475
2440
  }
2476
- const { span, updatedOptions: options } = createSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions);
2477
2441
  // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist
2478
2442
  if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {
2479
2443
  return true;
@@ -2485,57 +2449,49 @@ const imdsMsi = {
2485
2449
  skipMetadataHeader: true,
2486
2450
  skipQuery: true,
2487
2451
  });
2488
- requestOptions.tracingOptions = options.tracingOptions;
2489
- try {
2490
- // Create a request with a timeout since we expect that
2491
- // not having a "Metadata" header should cause an error to be
2492
- // returned quickly from the endpoint, proving its availability.
2493
- const request = coreRestPipeline.createPipelineRequest(requestOptions);
2494
- request.timeout = (_b = (_a = options.requestOptions) === null || _a === void 0 ? void 0 : _a.timeout) !== null && _b !== void 0 ? _b : 300;
2495
- // This MSI uses the imdsEndpoint to get the token, which only uses http://
2496
- request.allowInsecureConnection = true;
2452
+ return tracingClient.withSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions, async (options) => {
2453
+ var _a, _b;
2454
+ requestOptions.tracingOptions = options.tracingOptions;
2497
2455
  try {
2498
- logger$9.info(`${msiName$4}: Pinging the Azure IMDS endpoint`);
2499
- await identityClient.sendRequest(request);
2456
+ // Create a request with a timeout since we expect that
2457
+ // not having a "Metadata" header should cause an error to be
2458
+ // returned quickly from the endpoint, proving its availability.
2459
+ const request = coreRestPipeline.createPipelineRequest(requestOptions);
2460
+ request.timeout = (_b = (_a = options.requestOptions) === null || _a === void 0 ? void 0 : _a.timeout) !== null && _b !== void 0 ? _b : 300;
2461
+ // This MSI uses the imdsEndpoint to get the token, which only uses http://
2462
+ request.allowInsecureConnection = true;
2463
+ try {
2464
+ logger$a.info(`${msiName$4}: Pinging the Azure IMDS endpoint`);
2465
+ await identityClient.sendRequest(request);
2466
+ }
2467
+ catch (err) {
2468
+ if ((err.name === "RestError" && err.code === coreRestPipeline.RestError.REQUEST_SEND_ERROR) ||
2469
+ err.name === "AbortError" ||
2470
+ err.code === "ENETUNREACH" || // Network unreachable
2471
+ err.code === "ECONNREFUSED" || // connection refused
2472
+ err.code === "EHOSTDOWN" // host is down
2473
+ ) {
2474
+ // If the request failed, or Node.js was unable to establish a connection,
2475
+ // or the host was down, we'll assume the IMDS endpoint isn't available.
2476
+ logger$a.info(`${msiName$4}: The Azure IMDS endpoint is unavailable`);
2477
+ return false;
2478
+ }
2479
+ }
2480
+ // If we received any response, the endpoint is available
2481
+ logger$a.info(`${msiName$4}: The Azure IMDS endpoint is available`);
2482
+ return true;
2500
2483
  }
2501
2484
  catch (err) {
2502
- if ((err.name === "RestError" && err.code === coreRestPipeline.RestError.REQUEST_SEND_ERROR) ||
2503
- err.name === "AbortError" ||
2504
- err.code === "ENETUNREACH" || // Network unreachable
2505
- err.code === "ECONNREFUSED" || // connection refused
2506
- err.code === "EHOSTDOWN" // host is down
2507
- ) {
2508
- // If the request failed, or Node.js was unable to establish a connection,
2509
- // or the host was down, we'll assume the IMDS endpoint isn't available.
2510
- logger$9.info(`${msiName$4}: The Azure IMDS endpoint is unavailable`);
2511
- span.setStatus({
2512
- code: coreTracing.SpanStatusCode.ERROR,
2513
- message: err.message,
2514
- });
2515
- return false;
2516
- }
2485
+ // createWebResource failed.
2486
+ // This error should bubble up to the user.
2487
+ logger$a.info(`${msiName$4}: Error when creating the WebResource for the Azure IMDS endpoint: ${err.message}`);
2488
+ throw err;
2517
2489
  }
2518
- // If we received any response, the endpoint is available
2519
- logger$9.info(`${msiName$4}: The Azure IMDS endpoint is available`);
2520
- return true;
2521
- }
2522
- catch (err) {
2523
- // createWebResource failed.
2524
- // This error should bubble up to the user.
2525
- logger$9.info(`${msiName$4}: Error when creating the WebResource for the Azure IMDS endpoint: ${err.message}`);
2526
- span.setStatus({
2527
- code: coreTracing.SpanStatusCode.ERROR,
2528
- message: err.message,
2529
- });
2530
- throw err;
2531
- }
2532
- finally {
2533
- span.end();
2534
- }
2490
+ });
2535
2491
  },
2536
2492
  async getToken(configuration, getTokenOptions = {}) {
2537
2493
  const { identityClient, scopes, clientId, resourceId } = configuration;
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.`);
2494
+ logger$a.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.`);
2539
2495
  let nextDelayInMs = imdsMsiRetryConfig.startDelayInMs;
2540
2496
  for (let retries = 0; retries < imdsMsiRetryConfig.maxRetries; retries++) {
2541
2497
  try {
@@ -2558,7 +2514,7 @@ const imdsMsi = {
2558
2514
 
2559
2515
  // Copyright (c) Microsoft Corporation.
2560
2516
  const msiName$3 = "ManagedIdentityCredential - Azure Arc MSI";
2561
- const logger$8 = credentialLogger(msiName$3);
2517
+ const logger$9 = credentialLogger(msiName$3);
2562
2518
  /**
2563
2519
  * Generates the options used on the request for an access token.
2564
2520
  */
@@ -2631,12 +2587,12 @@ const arcMsi = {
2631
2587
  async isAvailable({ scopes }) {
2632
2588
  const resource = mapScopesToResource(scopes);
2633
2589
  if (!resource) {
2634
- logger$8.info(`${msiName$3}: Unavailable. Multiple scopes are not supported.`);
2590
+ logger$9.info(`${msiName$3}: Unavailable. Multiple scopes are not supported.`);
2635
2591
  return false;
2636
2592
  }
2637
2593
  const result = Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);
2638
2594
  if (!result) {
2639
- logger$8.info(`${msiName$3}: The environment variables needed are: IMDS_ENDPOINT and IDENTITY_ENDPOINT`);
2595
+ logger$9.info(`${msiName$3}: The environment variables needed are: IMDS_ENDPOINT and IDENTITY_ENDPOINT`);
2640
2596
  }
2641
2597
  return result;
2642
2598
  },
@@ -2644,12 +2600,12 @@ const arcMsi = {
2644
2600
  var _a;
2645
2601
  const { identityClient, scopes, clientId, resourceId } = configuration;
2646
2602
  if (clientId) {
2647
- logger$8.warning(`${msiName$3}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
2603
+ logger$9.warning(`${msiName$3}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
2648
2604
  }
2649
2605
  if (resourceId) {
2650
- logger$8.warning(`${msiName$3}: user defined managed Identity by resource Id is not supported. Argument resourceId will be ignored.`);
2606
+ logger$9.warning(`${msiName$3}: user defined managed Identity by resource Id is not supported. Argument resourceId will be ignored.`);
2651
2607
  }
2652
- logger$8.info(`${msiName$3}: Authenticating.`);
2608
+ logger$9.info(`${msiName$3}: Authenticating.`);
2653
2609
  const requestOptions = Object.assign(Object.assign({ disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions$3(scopes, clientId, resourceId)), { allowInsecureConnection: true });
2654
2610
  const filePath = await filePathRequest(identityClient, requestOptions);
2655
2611
  if (!filePath) {
@@ -2667,7 +2623,7 @@ const arcMsi = {
2667
2623
 
2668
2624
  // Copyright (c) Microsoft Corporation.
2669
2625
  const msiName$2 = "ManagedIdentityCredential - Token Exchange";
2670
- const logger$7 = credentialLogger(msiName$2);
2626
+ const logger$8 = credentialLogger(msiName$2);
2671
2627
  const readFileAsync = util.promisify(fs__default["default"].readFile);
2672
2628
  /**
2673
2629
  * Generates the options used on the request for an access token.
@@ -2723,13 +2679,13 @@ function tokenExchangeMsi() {
2723
2679
  const env = process.env;
2724
2680
  const result = Boolean((clientId || env.AZURE_CLIENT_ID) && env.AZURE_TENANT_ID && azureFederatedTokenFilePath);
2725
2681
  if (!result) {
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`);
2682
+ logger$8.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`);
2727
2683
  }
2728
2684
  return result;
2729
2685
  },
2730
2686
  async getToken(configuration, getTokenOptions = {}) {
2731
2687
  const { identityClient, scopes, clientId } = configuration;
2732
- logger$7.info(`${msiName$2}: Using the client assertion coming from environment variables.`);
2688
+ logger$8.info(`${msiName$2}: Using the client assertion coming from environment variables.`);
2733
2689
  let assertion;
2734
2690
  try {
2735
2691
  assertion = await readAssertion();
@@ -2758,7 +2714,7 @@ function tokenExchangeMsi() {
2758
2714
  // curl --insecure $IDENTITY_ENDPOINT'?api-version=2019-07-01-preview&resource=https://vault.azure.net/' -H "Secret: $IDENTITY_HEADER"
2759
2715
  //
2760
2716
  const msiName$1 = "ManagedIdentityCredential - Fabric MSI";
2761
- const logger$6 = credentialLogger(msiName$1);
2717
+ const logger$7 = credentialLogger(msiName$1);
2762
2718
  /**
2763
2719
  * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.
2764
2720
  */
@@ -2808,22 +2764,22 @@ const fabricMsi = {
2808
2764
  async isAvailable({ scopes }) {
2809
2765
  const resource = mapScopesToResource(scopes);
2810
2766
  if (!resource) {
2811
- logger$6.info(`${msiName$1}: Unavailable. Multiple scopes are not supported.`);
2767
+ logger$7.info(`${msiName$1}: Unavailable. Multiple scopes are not supported.`);
2812
2768
  return false;
2813
2769
  }
2814
2770
  const env = process.env;
2815
2771
  const result = Boolean(env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER && env.IDENTITY_SERVER_THUMBPRINT);
2816
2772
  if (!result) {
2817
- logger$6.info(`${msiName$1}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT, IDENTITY_HEADER and IDENTITY_SERVER_THUMBPRINT`);
2773
+ logger$7.info(`${msiName$1}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT, IDENTITY_HEADER and IDENTITY_SERVER_THUMBPRINT`);
2818
2774
  }
2819
2775
  return result;
2820
2776
  },
2821
2777
  async getToken(configuration, getTokenOptions = {}) {
2822
2778
  const { scopes, identityClient, clientId, resourceId } = configuration;
2823
2779
  if (resourceId) {
2824
- logger$6.warning(`${msiName$1}: user defined managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
2780
+ logger$7.warning(`${msiName$1}: user defined managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
2825
2781
  }
2826
- logger$6.info([
2782
+ logger$7.info([
2827
2783
  `${msiName$1}:`,
2828
2784
  "Using the endpoint and the secret coming from the environment variables:",
2829
2785
  `IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT},`,
@@ -2843,7 +2799,7 @@ const fabricMsi = {
2843
2799
 
2844
2800
  // Copyright (c) Microsoft Corporation.
2845
2801
  const msiName = "ManagedIdentityCredential - AppServiceMSI 2019";
2846
- const logger$5 = credentialLogger(msiName);
2802
+ const logger$6 = credentialLogger(msiName);
2847
2803
  /**
2848
2804
  * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.
2849
2805
  */
@@ -2893,19 +2849,19 @@ const appServiceMsi2019 = {
2893
2849
  async isAvailable({ scopes }) {
2894
2850
  const resource = mapScopesToResource(scopes);
2895
2851
  if (!resource) {
2896
- logger$5.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
2852
+ logger$6.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
2897
2853
  return false;
2898
2854
  }
2899
2855
  const env = process.env;
2900
2856
  const result = Boolean(env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER);
2901
2857
  if (!result) {
2902
- logger$5.info(`${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT and IDENTITY_HEADER.`);
2858
+ logger$6.info(`${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT and IDENTITY_HEADER.`);
2903
2859
  }
2904
2860
  return result;
2905
2861
  },
2906
2862
  async getToken(configuration, getTokenOptions = {}) {
2907
2863
  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].`);
2864
+ logger$6.info(`${msiName}: Using the endpoint and the secret coming form the environment variables: IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT} and IDENTITY_HEADER=[REDACTED].`);
2909
2865
  const request = coreRestPipeline.createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)), {
2910
2866
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
2911
2867
  allowInsecureConnection: true }));
@@ -2915,7 +2871,7 @@ const appServiceMsi2019 = {
2915
2871
  };
2916
2872
 
2917
2873
  // Copyright (c) Microsoft Corporation.
2918
- const logger$4 = credentialLogger("ManagedIdentityCredential");
2874
+ const logger$5 = credentialLogger("ManagedIdentityCredential");
2919
2875
  /**
2920
2876
  * Attempts authentication using a managed identity available at the deployment environment.
2921
2877
  * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,
@@ -2930,7 +2886,6 @@ class ManagedIdentityCredential {
2930
2886
  * @hidden
2931
2887
  */
2932
2888
  constructor(clientIdOrOptions, options) {
2933
- var _a, _b;
2934
2889
  this.isEndpointUnavailable = null;
2935
2890
  let _options;
2936
2891
  if (typeof clientIdOrOptions === "string") {
@@ -2938,10 +2893,10 @@ class ManagedIdentityCredential {
2938
2893
  _options = options;
2939
2894
  }
2940
2895
  else {
2941
- this.clientId = (_a = clientIdOrOptions) === null || _a === void 0 ? void 0 : _a.clientId;
2896
+ this.clientId = clientIdOrOptions === null || clientIdOrOptions === void 0 ? void 0 : clientIdOrOptions.clientId;
2942
2897
  _options = clientIdOrOptions;
2943
2898
  }
2944
- this.resourceId = (_b = _options) === null || _b === void 0 ? void 0 : _b.resourceId;
2899
+ this.resourceId = _options === null || _options === void 0 ? void 0 : _options.resourceId;
2945
2900
  // For JavaScript users.
2946
2901
  if (this.clientId && this.resourceId) {
2947
2902
  throw new Error(`${ManagedIdentityCredential.name} - Client Id and Resource Id can't be provided at the same time.`);
@@ -2956,11 +2911,11 @@ class ManagedIdentityCredential {
2956
2911
  return this.cachedMSI;
2957
2912
  }
2958
2913
  const MSIs = [
2914
+ arcMsi,
2959
2915
  fabricMsi,
2960
2916
  appServiceMsi2019,
2961
2917
  appServiceMsi2017,
2962
2918
  cloudShellMsi,
2963
- arcMsi,
2964
2919
  tokenExchangeMsi(),
2965
2920
  imdsMsi,
2966
2921
  ];
@@ -2979,7 +2934,7 @@ class ManagedIdentityCredential {
2979
2934
  throw new CredentialUnavailableError(`${ManagedIdentityCredential.name} - No MSI credential available`);
2980
2935
  }
2981
2936
  async authenticateManagedIdentity(scopes, getTokenOptions) {
2982
- const { span, updatedOptions } = createSpan(`${ManagedIdentityCredential.name}.authenticateManagedIdentity`, getTokenOptions);
2937
+ const { span, updatedOptions } = tracingClient.startSpan(`${ManagedIdentityCredential.name}.authenticateManagedIdentity`, getTokenOptions);
2983
2938
  try {
2984
2939
  // Determining the available MSI, and avoiding checking for other MSIs while the program is running.
2985
2940
  const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);
@@ -2992,8 +2947,8 @@ class ManagedIdentityCredential {
2992
2947
  }
2993
2948
  catch (err) {
2994
2949
  span.setStatus({
2995
- code: coreTracing.SpanStatusCode.ERROR,
2996
- message: err.message,
2950
+ status: "error",
2951
+ error: err,
2997
2952
  });
2998
2953
  throw err;
2999
2954
  }
@@ -3012,7 +2967,7 @@ class ManagedIdentityCredential {
3012
2967
  */
3013
2968
  async getToken(scopes, options) {
3014
2969
  let result = null;
3015
- const { span, updatedOptions } = createSpan(`${ManagedIdentityCredential.name}.getToken`, options);
2970
+ const { span, updatedOptions } = tracingClient.startSpan(`${ManagedIdentityCredential.name}.getToken`, options);
3016
2971
  try {
3017
2972
  // isEndpointAvailable can be true, false, or null,
3018
2973
  // If it's null, it means we don't yet know whether
@@ -3027,7 +2982,7 @@ class ManagedIdentityCredential {
3027
2982
  // It also means that the endpoint answered with either 200 or 201 (see the sendTokenRequest method),
3028
2983
  // yet we had no access token. For this reason, we'll throw once with a specific message:
3029
2984
  const error = new CredentialUnavailableError("The managed identity endpoint was reached, yet no tokens were received.");
3030
- logger$4.getToken.info(formatError(scopes, error));
2985
+ logger$5.getToken.info(formatError(scopes, error));
3031
2986
  throw error;
3032
2987
  }
3033
2988
  // Since `authenticateManagedIdentity` didn't throw, and the result was not null,
@@ -3039,10 +2994,10 @@ class ManagedIdentityCredential {
3039
2994
  // We've previously determined that the endpoint was unavailable,
3040
2995
  // either because it was unreachable or permanently unable to authenticate.
3041
2996
  const error = new CredentialUnavailableError("The managed identity endpoint is not currently available");
3042
- logger$4.getToken.info(formatError(scopes, error));
2997
+ logger$5.getToken.info(formatError(scopes, error));
3043
2998
  throw error;
3044
2999
  }
3045
- logger$4.getToken.info(formatSuccess(scopes));
3000
+ logger$5.getToken.info(formatSuccess(scopes));
3046
3001
  return result;
3047
3002
  }
3048
3003
  catch (err) {
@@ -3057,21 +3012,21 @@ class ManagedIdentityCredential {
3057
3012
  // if the status code was 400, it means that the endpoint is working,
3058
3013
  // but no identity is available.
3059
3014
  span.setStatus({
3060
- code: coreTracing.SpanStatusCode.ERROR,
3061
- message: err.message,
3015
+ status: "error",
3016
+ error: err,
3062
3017
  });
3063
3018
  // If either the network is unreachable,
3064
3019
  // we can safely assume the credential is unavailable.
3065
3020
  if (err.code === "ENETUNREACH") {
3066
3021
  const error = new CredentialUnavailableError(`${ManagedIdentityCredential.name}: Unavailable. Network unreachable. Message: ${err.message}`);
3067
- logger$4.getToken.info(formatError(scopes, error));
3022
+ logger$5.getToken.info(formatError(scopes, error));
3068
3023
  throw error;
3069
3024
  }
3070
3025
  // If either the host was unreachable,
3071
3026
  // we can safely assume the credential is unavailable.
3072
3027
  if (err.code === "EHOSTUNREACH") {
3073
3028
  const error = new CredentialUnavailableError(`${ManagedIdentityCredential.name}: Unavailable. No managed identity endpoint found. Message: ${err.message}`);
3074
- logger$4.getToken.info(formatError(scopes, error));
3029
+ logger$5.getToken.info(formatError(scopes, error));
3075
3030
  throw error;
3076
3031
  }
3077
3032
  // If err.statusCode has a value of 400, it comes from sendTokenRequest,
@@ -3108,9 +3063,9 @@ class DefaultManagedIdentityCredential extends ManagedIdentityCredential {
3108
3063
  // Constructor overload with just the other default options
3109
3064
  // Last constructor overload with Union of all options not required since the above two constructor overloads have optional properties
3110
3065
  constructor(options) {
3111
- var _a, _b, _c;
3112
- const managedIdentityClientId = (_b = (_a = options) === null || _a === void 0 ? void 0 : _a.managedIdentityClientId) !== null && _b !== void 0 ? _b : process.env.AZURE_CLIENT_ID;
3113
- const managedResourceId = (_c = options) === null || _c === void 0 ? void 0 : _c.managedIdentityResourceId;
3066
+ var _a;
3067
+ const managedIdentityClientId = (_a = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _a !== void 0 ? _a : process.env.AZURE_CLIENT_ID;
3068
+ const managedResourceId = options === null || options === void 0 ? void 0 : options.managedIdentityResourceId;
3114
3069
  // ManagedIdentityCredential throws if both the resourceId and the clientId are provided.
3115
3070
  if (managedResourceId) {
3116
3071
  const managedIdentityResourceIdOptions = Object.assign(Object.assign({}, options), { resourceId: managedResourceId });
@@ -3144,6 +3099,86 @@ class DefaultAzureCredential extends ChainedTokenCredential {
3144
3099
  }
3145
3100
  }
3146
3101
 
3102
+ // Copyright (c) Microsoft Corporation.
3103
+ /**
3104
+ * MSAL client assertion client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.
3105
+ * @internal
3106
+ */
3107
+ class MsalClientAssertion extends MsalNode {
3108
+ constructor(options) {
3109
+ super(options);
3110
+ this.requiresConfidential = true;
3111
+ this.getAssertion = options.getAssertion;
3112
+ }
3113
+ async doGetToken(scopes, options = {}) {
3114
+ try {
3115
+ const assertion = await this.getAssertion();
3116
+ const result = await this.confidentialApp.acquireTokenByClientCredential({
3117
+ scopes,
3118
+ correlationId: options.correlationId,
3119
+ azureRegion: this.azureRegion,
3120
+ authority: options.authority,
3121
+ claims: options.claims,
3122
+ clientAssertion: assertion,
3123
+ });
3124
+ // The Client Credential flow does not return an account,
3125
+ // so each time getToken gets called, we will have to acquire a new token through the service.
3126
+ return this.handleResult(scopes, this.clientId, result || undefined);
3127
+ }
3128
+ catch (err) {
3129
+ let err2 = err;
3130
+ if (err === null || err === undefined) {
3131
+ err2 = new Error(JSON.stringify(err));
3132
+ }
3133
+ else {
3134
+ err2 = coreUtil.isError(err) ? err : new Error(String(err));
3135
+ }
3136
+ throw this.handleError(scopes, err2, options);
3137
+ }
3138
+ }
3139
+ }
3140
+
3141
+ // Copyright (c) Microsoft Corporation.
3142
+ const logger$4 = credentialLogger("ClientAssertionCredential");
3143
+ /**
3144
+ * Authenticates a service principal with a JWT assertion.
3145
+ */
3146
+ class ClientAssertionCredential {
3147
+ /**
3148
+ * Creates an instance of the ClientAssertionCredential with the details
3149
+ * needed to authenticate against Azure Active Directory with a client
3150
+ * assertion provided by the developer through the `getAssertion` function parameter.
3151
+ *
3152
+ * @param tenantId - The Azure Active Directory tenant (directory) ID.
3153
+ * @param clientId - The client (application) ID of an App Registration in the tenant.
3154
+ * @param getAssertion - A function that retrieves the assertion for the credential to use.
3155
+ * @param options - Options for configuring the client which makes the authentication request.
3156
+ */
3157
+ constructor(tenantId, clientId, getAssertion, options = {}) {
3158
+ if (!tenantId || !clientId || !getAssertion) {
3159
+ throw new Error("ClientAssertionCredential: tenantId, clientId, and clientAssertion are required parameters.");
3160
+ }
3161
+ this.tenantId = tenantId;
3162
+ this.clientId = clientId;
3163
+ this.options = options;
3164
+ this.msalFlow = new MsalClientAssertion(Object.assign(Object.assign({}, options), { logger: logger$4, clientId: this.clientId, tenantId: this.tenantId, tokenCredentialOptions: this.options, getAssertion }));
3165
+ }
3166
+ /**
3167
+ * Authenticates with Azure Active Directory and returns an access token if successful.
3168
+ * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
3169
+ *
3170
+ * @param scopes - The list of scopes for which the token will have access.
3171
+ * @param options - The options used to configure any requests this
3172
+ * TokenCredential implementation might make.
3173
+ */
3174
+ async getToken(scopes, options = {}) {
3175
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3176
+ const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
3177
+ return this.msalFlow.getToken(arrayScopes, newOptions);
3178
+ });
3179
+ }
3180
+ }
3181
+
3147
3182
  // Copyright (c) Microsoft Corporation.
3148
3183
  /**
3149
3184
  * A call to open(), but mockable
@@ -3295,7 +3330,8 @@ class MsalOpenBrowser extends MsalNode {
3295
3330
  };
3296
3331
  const response = await this.publicApp.getAuthCodeUrl(authCodeUrlParameters);
3297
3332
  try {
3298
- await interactiveBrowserMockable.open(response, { wait: true });
3333
+ // A new instance on macOS only which allows it to not hang, does not fix the issue on linux
3334
+ await interactiveBrowserMockable.open(response, { wait: true, newInstance: true });
3299
3335
  }
3300
3336
  catch (e) {
3301
3337
  throw new CredentialUnavailableError(`InteractiveBrowserCredential: Could not open a browser window. Error: ${e.message}`);
@@ -3343,7 +3379,7 @@ class InteractiveBrowserCredential {
3343
3379
  * TokenCredential implementation might make.
3344
3380
  */
3345
3381
  async getToken(scopes, options = {}) {
3346
- return trace(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3382
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3347
3383
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
3348
3384
  return this.msalFlow.getToken(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
3349
3385
  });
@@ -3362,7 +3398,7 @@ class InteractiveBrowserCredential {
3362
3398
  * TokenCredential implementation might make.
3363
3399
  */
3364
3400
  async authenticate(scopes, options = {}) {
3365
- return trace(`${this.constructor.name}.authenticate`, options, async (newOptions) => {
3401
+ return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => {
3366
3402
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
3367
3403
  await this.msalFlow.getToken(arrayScopes, newOptions);
3368
3404
  return this.msalFlow.getActiveAccount();
@@ -3453,7 +3489,7 @@ class DeviceCodeCredential {
3453
3489
  * TokenCredential implementation might make.
3454
3490
  */
3455
3491
  async getToken(scopes, options = {}) {
3456
- return trace(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3492
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3457
3493
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
3458
3494
  return this.msalFlow.getToken(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
3459
3495
  });
@@ -3469,7 +3505,7 @@ class DeviceCodeCredential {
3469
3505
  * TokenCredential implementation might make.
3470
3506
  */
3471
3507
  async authenticate(scopes, options = {}) {
3472
- return trace(`${this.constructor.name}.authenticate`, options, async (newOptions) => {
3508
+ return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => {
3473
3509
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
3474
3510
  await this.msalFlow.getToken(arrayScopes, newOptions);
3475
3511
  return this.msalFlow.getActiveAccount();
@@ -3495,12 +3531,12 @@ class MsalAuthorizationCode extends MsalNode {
3495
3531
  }
3496
3532
  async getAuthCodeUrl(options) {
3497
3533
  await this.init();
3498
- return this.confidentialApp.getAuthCodeUrl(options);
3534
+ return (this.confidentialApp || this.publicApp).getAuthCodeUrl(options);
3499
3535
  }
3500
3536
  async doGetToken(scopes, options) {
3501
3537
  var _a;
3502
3538
  try {
3503
- const result = await ((_a = this.confidentialApp) === null || _a === void 0 ? void 0 : _a.acquireTokenByCode({
3539
+ const result = await ((_a = (this.confidentialApp || this.publicApp)) === null || _a === void 0 ? void 0 : _a.acquireTokenByCode({
3504
3540
  scopes,
3505
3541
  redirectUri: this.redirectUri,
3506
3542
  code: this.authorizationCode,
@@ -3549,7 +3585,8 @@ class AuthorizationCodeCredential {
3549
3585
  options = redirectUriOrOptions;
3550
3586
  }
3551
3587
  this.msalFlow = new MsalAuthorizationCode(Object.assign(Object.assign({}, options), { clientSecret,
3552
- clientId, tokenCredentialOptions: options || {}, logger: logger$1, redirectUri: this.redirectUri, authorizationCode: this.authorizationCode }));
3588
+ clientId,
3589
+ tenantId, tokenCredentialOptions: options || {}, logger: logger$1, redirectUri: this.redirectUri, authorizationCode: this.authorizationCode }));
3553
3590
  }
3554
3591
  /**
3555
3592
  * Authenticates with Azure Active Directory and returns an access token if successful.
@@ -3560,7 +3597,7 @@ class AuthorizationCodeCredential {
3560
3597
  * TokenCredential implementation might make.
3561
3598
  */
3562
3599
  async getToken(scopes, options = {}) {
3563
- return trace(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3600
+ return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => {
3564
3601
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
3565
3602
  return this.msalFlow.getToken(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication }));
3566
3603
  });
@@ -3645,7 +3682,7 @@ class OnBehalfOfCredential {
3645
3682
  * @param options - The options used to configure the underlying network requests.
3646
3683
  */
3647
3684
  async getToken(scopes, options = {}) {
3648
- return trace(`${credentialName}.getToken`, options, async (newOptions) => {
3685
+ return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {
3649
3686
  const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
3650
3687
  return this.msalFlow.getToken(arrayScopes, newOptions);
3651
3688
  });
@@ -3669,6 +3706,7 @@ exports.AuthorizationCodeCredential = AuthorizationCodeCredential;
3669
3706
  exports.AzureCliCredential = AzureCliCredential;
3670
3707
  exports.AzurePowerShellCredential = AzurePowerShellCredential;
3671
3708
  exports.ChainedTokenCredential = ChainedTokenCredential;
3709
+ exports.ClientAssertionCredential = ClientAssertionCredential;
3672
3710
  exports.ClientCertificateCredential = ClientCertificateCredential;
3673
3711
  exports.ClientSecretCredential = ClientSecretCredential;
3674
3712
  exports.CredentialUnavailableError = CredentialUnavailableError;
@@ -3683,7 +3721,7 @@ exports.UsernamePasswordCredential = UsernamePasswordCredential;
3683
3721
  exports.VisualStudioCodeCredential = VisualStudioCodeCredential;
3684
3722
  exports.deserializeAuthenticationRecord = deserializeAuthenticationRecord;
3685
3723
  exports.getDefaultAzureCredential = getDefaultAzureCredential;
3686
- exports.logger = logger$k;
3724
+ exports.logger = logger$l;
3687
3725
  exports.serializeAuthenticationRecord = serializeAuthenticationRecord;
3688
3726
  exports.useIdentityPlugin = useIdentityPlugin;
3689
3727
  //# sourceMappingURL=index.js.map