@azure/identity 4.5.1-alpha.20241031.1 → 4.5.1-alpha.20241112.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (30) hide show
  1. package/dist/index.js +67 -121
  2. package/dist/index.js.map +1 -1
  3. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js +12 -34
  4. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js.map +1 -1
  5. package/dist-esm/src/credentials/managedIdentityCredential/index.browser.js.map +1 -1
  6. package/dist-esm/src/credentials/managedIdentityCredential/index.js +188 -8
  7. package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
  8. package/dist-esm/src/credentials/managedIdentityCredential/models.js.map +1 -1
  9. package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js +4 -1
  10. package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +1 -1
  11. package/dist-esm/src/credentials/managedIdentityCredential/utils.js +1 -1
  12. package/dist-esm/src/credentials/managedIdentityCredential/utils.js.map +1 -1
  13. package/package.json +3 -4
  14. package/types/identity.d.ts +11 -1
  15. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js +0 -71
  16. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js.map +0 -1
  17. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js +0 -71
  18. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js.map +0 -1
  19. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js +0 -140
  20. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js.map +0 -1
  21. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js +0 -75
  22. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js.map +0 -1
  23. package/dist-esm/src/credentials/managedIdentityCredential/constants.js +0 -9
  24. package/dist-esm/src/credentials/managedIdentityCredential/constants.js.map +0 -1
  25. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js +0 -95
  26. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js.map +0 -1
  27. package/dist-esm/src/credentials/managedIdentityCredential/legacyMsiProvider.js +0 -309
  28. package/dist-esm/src/credentials/managedIdentityCredential/legacyMsiProvider.js.map +0 -1
  29. package/dist-esm/src/credentials/managedIdentityCredential/msalMsiProvider.js +0 -212
  30. package/dist-esm/src/credentials/managedIdentityCredential/msalMsiProvider.js.map +0 -1
@@ -1,14 +1,15 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
3
  import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline";
4
- import { delay, isError } from "@azure/core-util";
5
- import { imdsApiVersion, imdsEndpointPath, imdsHost } from "./constants";
6
- import { AuthenticationError } from "../../errors";
4
+ import { isError } from "@azure/core-util";
7
5
  import { credentialLogger } from "../../util/logging";
8
6
  import { mapScopesToResource } from "./utils";
9
7
  import { tracingClient } from "../../util/tracing";
10
8
  const msiName = "ManagedIdentityCredential - IMDS";
11
9
  const logger = credentialLogger(msiName);
10
+ const imdsHost = "http://169.254.169.254";
11
+ const imdsEndpointPath = "/metadata/identity/oauth2/token";
12
+ const imdsApiVersion = "2018-02-01";
12
13
  /**
13
14
  * Generates the options used on the request for an access token.
14
15
  */
@@ -53,11 +54,14 @@ function prepareRequestOptions(scopes, clientId, resourceId, options) {
53
54
  };
54
55
  }
55
56
  /**
56
- * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.
57
+ * Defines how to determine whether the Azure IMDS MSI is available.
58
+ *
59
+ * Actually getting the token once we determine IMDS is available is handled by MSAL.
57
60
  */
58
61
  export const imdsMsi = {
59
62
  name: "imdsMsi",
60
- async isAvailable({ scopes, identityClient, clientId, resourceId, getTokenOptions = {}, }) {
63
+ async isAvailable(options) {
64
+ const { scopes, identityClient, clientId, resourceId, getTokenOptions } = options;
61
65
  const resource = mapScopesToResource(scopes);
62
66
  if (!resource) {
63
67
  logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
@@ -74,16 +78,16 @@ export const imdsMsi = {
74
78
  skipMetadataHeader: true,
75
79
  skipQuery: true,
76
80
  });
77
- return tracingClient.withSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions, async (options) => {
81
+ return tracingClient.withSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions !== null && getTokenOptions !== void 0 ? getTokenOptions : {}, async (updatedOptions) => {
78
82
  var _a, _b;
79
- requestOptions.tracingOptions = options.tracingOptions;
83
+ requestOptions.tracingOptions = updatedOptions.tracingOptions;
80
84
  // Create a request with a timeout since we expect that
81
85
  // not having a "Metadata" header should cause an error to be
82
86
  // returned quickly from the endpoint, proving its availability.
83
87
  const request = createPipelineRequest(requestOptions);
84
88
  // Default to 1000 if the default of 0 is used.
85
89
  // Negative values can still be used to disable the timeout.
86
- request.timeout = ((_a = options.requestOptions) === null || _a === void 0 ? void 0 : _a.timeout) || 1000;
90
+ request.timeout = ((_a = updatedOptions.requestOptions) === null || _a === void 0 ? void 0 : _a.timeout) || 1000;
87
91
  // This MSI uses the imdsEndpoint to get the token, which only uses http://
88
92
  request.allowInsecureConnection = true;
89
93
  let response;
@@ -114,31 +118,5 @@ export const imdsMsi = {
114
118
  return true;
115
119
  });
116
120
  },
117
- async getToken(configuration, getTokenOptions = {}) {
118
- const { identityClient, scopes, clientId, resourceId } = configuration;
119
- if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {
120
- logger.info(`${msiName}: Using the Azure IMDS endpoint coming from the environment variable AZURE_POD_IDENTITY_AUTHORITY_HOST=${process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST}.`);
121
- }
122
- else {
123
- logger.info(`${msiName}: Using the default Azure IMDS endpoint ${imdsHost}.`);
124
- }
125
- let nextDelayInMs = configuration.retryConfig.startDelayInMs;
126
- for (let retries = 0; retries < configuration.retryConfig.maxRetries; retries++) {
127
- try {
128
- const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)), { allowInsecureConnection: true }));
129
- const tokenResponse = await identityClient.sendTokenRequest(request);
130
- return (tokenResponse && tokenResponse.accessToken) || null;
131
- }
132
- catch (error) {
133
- if (error.statusCode === 404) {
134
- await delay(nextDelayInMs);
135
- nextDelayInMs *= configuration.retryConfig.intervalIncrement;
136
- continue;
137
- }
138
- throw error;
139
- }
140
- }
141
- throw new AuthenticationError(404, `${msiName}: Failed to retrieve IMDS token after ${configuration.retryConfig.maxRetries} retries.`);
142
- },
143
121
  };
144
122
  //# sourceMappingURL=imdsMsi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"imdsMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/imdsMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AACrF,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,MAAM,OAAO,GAAG,kCAAkC,CAAC;AACnD,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,SAAS,qBAAqB,CAC5B,MAAyB,EACzB,QAAiB,EACjB,UAAmB,EACnB,OAGC;;IAED,MAAM,QAAQ,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,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a,CAAC,WAAW,CAAC,cAAc,CAAC;QAC7D,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,aAAa,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,EAAE,EAAE,CAAC;YAChF,IAAI,CAAC;gBACH,MAAM,OAAO,GAAG,qBAAqB,+BACnC,WAAW,EAAE,eAAe,CAAC,WAAW,IACrC,qBAAqB,CAAC,MAAM,EAAE,QAAQ,EAAE,UAAU,CAAC,KACtD,uBAAuB,EAAE,IAAI,IAC7B,CAAC;gBACH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;gBAErE,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;YAC9D,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG,EAAE,CAAC;oBAC7B,MAAM,KAAK,CAAC,aAAa,CAAC,CAAC;oBAC3B,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,iBAAiB,CAAC;oBAC7D,SAAS;gBACX,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;QAED,MAAM,IAAI,mBAAmB,CAC3B,GAAG,EACH,GAAG,OAAO,yCAAyC,aAAa,CAAC,WAAW,CAAC,UAAU,WAAW,CACnG,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport type { PipelineRequestOptions, PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\nimport { delay, isError } from \"@azure/core-util\";\nimport { imdsApiVersion, imdsEndpointPath, imdsHost } from \"./constants\";\n\nimport { AuthenticationError } from \"../../errors\";\nimport type { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst msiName = \"ManagedIdentityCredential - IMDS\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string,\n options?: {\n skipQuery?: boolean;\n skipMetadataHeader?: boolean;\n },\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const { skipQuery, skipMetadataHeader } = options || {};\n let query = \"\";\n\n // Pod Identity will try to process this request even if the Metadata header is missing.\n // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request.\n if (!skipQuery) {\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": imdsApiVersion,\n };\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const params = new URLSearchParams(queryParameters);\n query = `?${params.toString()}`;\n }\n\n const url = new URL(imdsEndpointPath, process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST ?? imdsHost);\n\n const rawHeaders: Record<string, string> = {\n Accept: \"application/json\",\n Metadata: \"true\",\n };\n\n // Remove the Metadata header to invoke a request error from some IMDS endpoints.\n if (skipMetadataHeader) {\n delete rawHeaders.Metadata;\n }\n\n return {\n // In this case, the `?` should be added in the \"query\" variable `skipQuery` is not set.\n url: `${url}${query}`,\n method: \"GET\",\n headers: createHttpHeaders(rawHeaders),\n };\n}\n\n/**\n * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.\n */\nexport const imdsMsi: MSI = {\n name: \"imdsMsi\",\n async isAvailable({\n scopes,\n identityClient,\n clientId,\n resourceId,\n getTokenOptions = {},\n }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n\n // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n return true;\n }\n\n if (!identityClient) {\n throw new Error(\"Missing IdentityClient\");\n }\n\n const requestOptions = prepareRequestOptions(resource, clientId, resourceId, {\n skipMetadataHeader: true,\n skipQuery: true,\n });\n\n return tracingClient.withSpan(\n \"ManagedIdentityCredential-pingImdsEndpoint\",\n getTokenOptions,\n async (options) => {\n requestOptions.tracingOptions = options.tracingOptions;\n\n // Create a request with a timeout since we expect that\n // not having a \"Metadata\" header should cause an error to be\n // returned quickly from the endpoint, proving its availability.\n const request = createPipelineRequest(requestOptions);\n\n // Default to 1000 if the default of 0 is used.\n // Negative values can still be used to disable the timeout.\n request.timeout = options.requestOptions?.timeout || 1000;\n\n // This MSI uses the imdsEndpoint to get the token, which only uses http://\n request.allowInsecureConnection = true;\n let response: PipelineResponse;\n try {\n logger.info(`${msiName}: Pinging the Azure IMDS endpoint`);\n response = await identityClient.sendRequest(request);\n } catch (err: unknown) {\n // If the request failed, or Node.js was unable to establish a connection,\n // or the host was down, we'll assume the IMDS endpoint isn't available.\n if (isError(err)) {\n logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`);\n }\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n return false;\n }\n if (response.status === 403) {\n if (response.bodyAsText?.includes(\"unreachable\")) {\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n logger.info(`${msiName}: ${response.bodyAsText}`);\n return false;\n }\n }\n // If we received any response, the endpoint is available\n logger.info(`${msiName}: The Azure IMDS endpoint is available`);\n return true;\n },\n );\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n logger.info(\n `${msiName}: Using the Azure IMDS endpoint coming from the environment variable AZURE_POD_IDENTITY_AUTHORITY_HOST=${process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST}.`,\n );\n } else {\n logger.info(`${msiName}: Using the default Azure IMDS endpoint ${imdsHost}.`);\n }\n\n let nextDelayInMs = configuration.retryConfig.startDelayInMs;\n for (let retries = 0; retries < configuration.retryConfig.maxRetries; retries++) {\n try {\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (error: any) {\n if (error.statusCode === 404) {\n await delay(nextDelayInMs);\n nextDelayInMs *= configuration.retryConfig.intervalIncrement;\n continue;\n }\n throw error;\n }\n }\n\n throw new AuthenticationError(\n 404,\n `${msiName}: Failed to retrieve IMDS token after ${configuration.retryConfig.maxRetries} retries.`,\n );\n },\n};\n"]}
1
+ {"version":3,"file":"imdsMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/imdsMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AACrF,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAG3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnD,MAAM,OAAO,GAAG,kCAAkC,CAAC;AACnD,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC,MAAM,QAAQ,GAAG,wBAAwB,CAAC;AAC1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,cAAc,CAAC,cAAc,0CAAE,OAAO,KAAI,IAAI,CAAC;YAEjE,2EAA2E;YAC3E,OAAO,CAAC,uBAAuB,GAAG,IAAI,CAAC;YACvC,IAAI,QAA0B,CAAC;YAC/B,IAAI,CAAC;gBACH,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,mCAAmC,CAAC,CAAC;gBAC3D,QAAQ,GAAG,MAAM,cAAc,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YACvD,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACtB,0EAA0E;gBAC1E,wEAAwE;gBACxE,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;oBACjB,MAAM,CAAC,OAAO,CAAC,GAAG,OAAO,kBAAkB,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;gBACzE,CAAC;gBACD,6NAA6N;gBAC7N,4CAA4C;gBAC5C,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,0CAA0C,CAAC,CAAC;gBAClE,OAAO,KAAK,CAAC;YACf,CAAC;YACD,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBAC5B,IAAI,MAAA,QAAQ,CAAC,UAAU,0CAAE,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;oBACjD,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,0CAA0C,CAAC,CAAC;oBAClE,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,KAAK,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;oBAClD,OAAO,KAAK,CAAC;gBACf,CAAC;YACH,CAAC;YACD,yDAAyD;YACzD,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,wCAAwC,CAAC,CAAC;YAChE,OAAO,IAAI,CAAC;QACd,CAAC,CACF,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRequestOptions, PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\nimport { isError } from \"@azure/core-util\";\n\nimport type { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tracingClient } from \"../../util/tracing\";\nimport { IdentityClient } from \"../../client/identityClient\";\n\nconst msiName = \"ManagedIdentityCredential - IMDS\";\nconst logger = credentialLogger(msiName);\n\nconst imdsHost = \"http://169.254.169.254\";\nconst imdsEndpointPath = \"/metadata/identity/oauth2/token\";\nconst imdsApiVersion = \"2018-02-01\";\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string,\n options?: {\n skipQuery?: boolean;\n skipMetadataHeader?: boolean;\n },\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const { skipQuery, skipMetadataHeader } = options || {};\n let query = \"\";\n\n // Pod Identity will try to process this request even if the Metadata header is missing.\n // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request.\n if (!skipQuery) {\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": imdsApiVersion,\n };\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const params = new URLSearchParams(queryParameters);\n query = `?${params.toString()}`;\n }\n\n const url = new URL(imdsEndpointPath, process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST ?? imdsHost);\n\n const rawHeaders: Record<string, string> = {\n Accept: \"application/json\",\n Metadata: \"true\",\n };\n\n // Remove the Metadata header to invoke a request error from some IMDS endpoints.\n if (skipMetadataHeader) {\n delete rawHeaders.Metadata;\n }\n\n return {\n // In this case, the `?` should be added in the \"query\" variable `skipQuery` is not set.\n url: `${url}${query}`,\n method: \"GET\",\n headers: createHttpHeaders(rawHeaders),\n };\n}\n\n/**\n * Defines how to determine whether the Azure IMDS MSI is available.\n *\n * Actually getting the token once we determine IMDS is available is handled by MSAL.\n */\nexport const imdsMsi = {\n name: \"imdsMsi\",\n async isAvailable(options: {\n scopes: string | string[];\n identityClient?: IdentityClient;\n clientId?: string;\n resourceId?: string;\n getTokenOptions?: GetTokenOptions;\n }): Promise<boolean> {\n const { scopes, identityClient, clientId, resourceId, getTokenOptions } = options;\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n\n // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n return true;\n }\n\n if (!identityClient) {\n throw new Error(\"Missing IdentityClient\");\n }\n\n const requestOptions = prepareRequestOptions(resource, clientId, resourceId, {\n skipMetadataHeader: true,\n skipQuery: true,\n });\n\n return tracingClient.withSpan(\n \"ManagedIdentityCredential-pingImdsEndpoint\",\n getTokenOptions ?? {},\n async (updatedOptions) => {\n requestOptions.tracingOptions = updatedOptions.tracingOptions;\n\n // Create a request with a timeout since we expect that\n // not having a \"Metadata\" header should cause an error to be\n // returned quickly from the endpoint, proving its availability.\n const request = createPipelineRequest(requestOptions);\n\n // Default to 1000 if the default of 0 is used.\n // Negative values can still be used to disable the timeout.\n request.timeout = updatedOptions.requestOptions?.timeout || 1000;\n\n // This MSI uses the imdsEndpoint to get the token, which only uses http://\n request.allowInsecureConnection = true;\n let response: PipelineResponse;\n try {\n logger.info(`${msiName}: Pinging the Azure IMDS endpoint`);\n response = await identityClient.sendRequest(request);\n } catch (err: unknown) {\n // If the request failed, or Node.js was unable to establish a connection,\n // or the host was down, we'll assume the IMDS endpoint isn't available.\n if (isError(err)) {\n logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`);\n }\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n return false;\n }\n if (response.status === 403) {\n if (response.bodyAsText?.includes(\"unreachable\")) {\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n logger.info(`${msiName}: ${response.bodyAsText}`);\n return false;\n }\n }\n // If we received any response, the endpoint is available\n logger.info(`${msiName}: The Azure IMDS endpoint is available`);\n return true;\n },\n );\n },\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEnE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,4DAA4D,CAC7D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D,MAAM,OAAO,yBAAyB;IAGpC;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,KAAK,CAAC,QAAQ;QACnB,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, TokenCredential } from \"@azure/core-auth\";\n\nimport type { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { credentialLogger, formatError } from \"../../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"ManagedIdentityCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\nexport class ManagedIdentityCredential implements TokenCredential {\n constructor(clientId: string, options?: TokenCredentialOptions);\n constructor(options?: TokenCredentialOptions);\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public async getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}
1
+ {"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEnE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,4DAA4D,CAC7D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D,MAAM,OAAO,yBAAyB;IACpC;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,KAAK,CAAC,QAAQ;QACnB,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, TokenCredential } from \"@azure/core-auth\";\n\nimport { credentialLogger, formatError } from \"../../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"ManagedIdentityCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\nexport class ManagedIdentityCredential implements TokenCredential {\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public async getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}
@@ -1,6 +1,17 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
- import { MsalMsiProvider } from "./msalMsiProvider";
3
+ import { getLogLevel } from "@azure/logger";
4
+ import { ManagedIdentityApplication } from "@azure/msal-node";
5
+ import { IdentityClient } from "../../client/identityClient";
6
+ import { AuthenticationRequiredError, CredentialUnavailableError } from "../../errors";
7
+ import { getMSALLogLevel, defaultLoggerCallback } from "../../msal/utils";
8
+ import { imdsRetryPolicy } from "./imdsRetryPolicy";
9
+ import { formatSuccess, formatError, credentialLogger } from "../../util/logging";
10
+ import { tracingClient } from "../../util/tracing";
11
+ import { imdsMsi } from "./imdsMsi";
12
+ import { tokenExchangeMsi } from "./tokenExchangeMsi";
13
+ import { mapScopesToResource } from "./utils";
14
+ const logger = credentialLogger("ManagedIdentityCredential");
4
15
  /**
5
16
  * Attempts authentication using a managed identity available at the deployment environment.
6
17
  * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,
@@ -15,11 +26,64 @@ export class ManagedIdentityCredential {
15
26
  * @hidden
16
27
  */
17
28
  constructor(clientIdOrOptions, options) {
18
- // https://github.com/Azure/azure-sdk-for-js/issues/30189
19
- // If needed, you may release a hotfix to quickly rollback to the legacy implementation by changing the following line to:
20
- // this.implProvider = new LegacyMsiProvider(clientIdOrOptions, options);
21
- // Once stabilized, you can remove the legacy implementation and inline the msalMsiProvider code here as a drop-in replacement.
22
- this.implProvider = new MsalMsiProvider(clientIdOrOptions, options);
29
+ var _a, _b;
30
+ this.msiRetryConfig = {
31
+ maxRetries: 5,
32
+ startDelayInMs: 800,
33
+ intervalIncrement: 2,
34
+ };
35
+ let _options;
36
+ if (typeof clientIdOrOptions === "string") {
37
+ this.clientId = clientIdOrOptions;
38
+ _options = options !== null && options !== void 0 ? options : {};
39
+ }
40
+ else {
41
+ this.clientId = clientIdOrOptions === null || clientIdOrOptions === void 0 ? void 0 : clientIdOrOptions.clientId;
42
+ _options = clientIdOrOptions !== null && clientIdOrOptions !== void 0 ? clientIdOrOptions : {};
43
+ }
44
+ this.resourceId = _options === null || _options === void 0 ? void 0 : _options.resourceId;
45
+ this.objectId = _options === null || _options === void 0 ? void 0 : _options.objectId;
46
+ // For JavaScript users.
47
+ const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);
48
+ if (providedIds.length > 1) {
49
+ throw new Error(`ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify({ clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId })}`);
50
+ }
51
+ // ManagedIdentity uses http for local requests
52
+ _options.allowInsecureConnection = true;
53
+ if (((_a = _options.retryOptions) === null || _a === void 0 ? void 0 : _a.maxRetries) !== undefined) {
54
+ this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;
55
+ }
56
+ this.identityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: "perCall" }] }));
57
+ this.managedIdentityApp = new ManagedIdentityApplication({
58
+ managedIdentityIdParams: {
59
+ userAssignedClientId: this.clientId,
60
+ userAssignedResourceId: this.resourceId,
61
+ userAssignedObjectId: this.objectId,
62
+ },
63
+ system: {
64
+ disableInternalRetries: true,
65
+ networkClient: this.identityClient,
66
+ loggerOptions: {
67
+ logLevel: getMSALLogLevel(getLogLevel()),
68
+ piiLoggingEnabled: (_b = _options.loggingOptions) === null || _b === void 0 ? void 0 : _b.enableUnsafeSupportLogging,
69
+ loggerCallback: defaultLoggerCallback(logger),
70
+ },
71
+ },
72
+ });
73
+ this.isAvailableIdentityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { retryOptions: {
74
+ maxRetries: 0,
75
+ } }));
76
+ // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.
77
+ if (this.managedIdentityApp.getManagedIdentitySource() === "CloudShell") {
78
+ if (this.clientId || this.resourceId || this.objectId) {
79
+ logger.warning(`CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify({
80
+ clientId: this.clientId,
81
+ resourceId: this.resourceId,
82
+ objectId: this.objectId,
83
+ })}.`);
84
+ throw new CredentialUnavailableError("ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.");
85
+ }
86
+ }
23
87
  }
24
88
  /**
25
89
  * Authenticates with Microsoft Entra ID and returns an access token if successful.
@@ -30,8 +94,124 @@ export class ManagedIdentityCredential {
30
94
  * @param options - The options used to configure any requests this
31
95
  * TokenCredential implementation might make.
32
96
  */
33
- async getToken(scopes, options) {
34
- return this.implProvider.getToken(scopes, options);
97
+ async getToken(scopes, options = {}) {
98
+ logger.getToken.info("Using the MSAL provider for Managed Identity.");
99
+ const resource = mapScopesToResource(scopes);
100
+ if (!resource) {
101
+ throw new CredentialUnavailableError(`ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`);
102
+ }
103
+ return tracingClient.withSpan("ManagedIdentityCredential.getToken", options, async () => {
104
+ var _a;
105
+ try {
106
+ const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable(this.clientId);
107
+ // Most scenarios are handled by MSAL except for two:
108
+ // AKS pod identity - MSAL does not implement the token exchange flow.
109
+ // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.
110
+ // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token
111
+ // We will continue to implement these features in the Identity library.
112
+ const identitySource = this.managedIdentityApp.getManagedIdentitySource();
113
+ const isImdsMsi = identitySource === "DefaultToImds" || identitySource === "Imds"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.
114
+ logger.getToken.info(`MSAL Identity source: ${identitySource}`);
115
+ if (isTokenExchangeMsi) {
116
+ // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.
117
+ logger.getToken.info("Using the token exchange managed identity.");
118
+ const result = await tokenExchangeMsi.getToken({
119
+ scopes,
120
+ clientId: this.clientId,
121
+ identityClient: this.identityClient,
122
+ retryConfig: this.msiRetryConfig,
123
+ resourceId: this.resourceId,
124
+ });
125
+ if (result === null) {
126
+ throw new CredentialUnavailableError("Attempted to use the token exchange managed identity, but received a null response.");
127
+ }
128
+ return result;
129
+ }
130
+ else if (isImdsMsi) {
131
+ // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.
132
+ // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.
133
+ logger.getToken.info("Using the IMDS endpoint to probe for availability.");
134
+ const isAvailable = await imdsMsi.isAvailable({
135
+ scopes,
136
+ clientId: this.clientId,
137
+ getTokenOptions: options,
138
+ identityClient: this.isAvailableIdentityClient,
139
+ resourceId: this.resourceId,
140
+ });
141
+ if (!isAvailable) {
142
+ throw new CredentialUnavailableError(`Attempted to use the IMDS endpoint, but it is not available.`);
143
+ }
144
+ }
145
+ // If we got this far, it means:
146
+ // - This is not a tokenExchangeMsi,
147
+ // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.
148
+ // We can proceed normally by calling MSAL for a token.
149
+ logger.getToken.info("Calling into MSAL for managed identity token.");
150
+ const token = await this.managedIdentityApp.acquireToken({
151
+ resource,
152
+ });
153
+ this.ensureValidMsalToken(scopes, token, options);
154
+ logger.getToken.info(formatSuccess(scopes));
155
+ return {
156
+ expiresOnTimestamp: token.expiresOn.getTime(),
157
+ token: token.accessToken,
158
+ refreshAfterTimestamp: (_a = token.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(),
159
+ tokenType: "Bearer",
160
+ };
161
+ }
162
+ catch (err) {
163
+ logger.getToken.error(formatError(scopes, err));
164
+ // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.
165
+ // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?
166
+ if (err.name === "AuthenticationRequiredError") {
167
+ throw err;
168
+ }
169
+ if (isNetworkError(err)) {
170
+ throw new CredentialUnavailableError(`ManagedIdentityCredential: Network unreachable. Message: ${err.message}`, { cause: err });
171
+ }
172
+ throw new CredentialUnavailableError(`ManagedIdentityCredential: Authentication failed. Message ${err.message}`, { cause: err });
173
+ }
174
+ });
35
175
  }
176
+ /**
177
+ * Ensures the validity of the MSAL token
178
+ */
179
+ ensureValidMsalToken(scopes, msalToken, getTokenOptions) {
180
+ const createError = (message) => {
181
+ logger.getToken.info(message);
182
+ return new AuthenticationRequiredError({
183
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
184
+ getTokenOptions,
185
+ message,
186
+ });
187
+ };
188
+ if (!msalToken) {
189
+ throw createError("No response.");
190
+ }
191
+ if (!msalToken.expiresOn) {
192
+ throw createError(`Response had no "expiresOn" property.`);
193
+ }
194
+ if (!msalToken.accessToken) {
195
+ throw createError(`Response had no "accessToken" property.`);
196
+ }
197
+ }
198
+ }
199
+ function isNetworkError(err) {
200
+ // MSAL error
201
+ if (err.errorCode === "network_error") {
202
+ return true;
203
+ }
204
+ // Probe errors
205
+ if (err.code === "ENETUNREACH" || err.code === "EHOSTUNREACH") {
206
+ return true;
207
+ }
208
+ // This is a special case for Docker Desktop which responds with a 403 with a message that contains "A socket operation was attempted to an unreachable network" or "A socket operation was attempted to an unreachable host"
209
+ // rather than just timing out, as expected.
210
+ if (err.statusCode === 403 || err.code === 403) {
211
+ if (err.message.includes("unreachable")) {
212
+ return true;
213
+ }
214
+ }
215
+ return false;
36
216
  }
37
217
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAwCpD;;;;;;;GAOG;AACH,MAAM,OAAO,yBAAyB;IA6BpC;;;OAGG;IACH,YACE,iBAI4C,EAC5C,OAAgC;QAEhC,yDAAyD;QACzD,0HAA0H;QAC1H,yEAAyE;QACzE,+HAA+H;QAC/H,IAAI,CAAC,YAAY,GAAG,IAAI,eAAe,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;IAED;;;;;;;;OAQG;IACI,KAAK,CAAC,QAAQ,CACnB,MAAyB,EACzB,OAAyB;QAEzB,OAAO,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrD,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport type { LegacyMsiProvider } from \"./legacyMsiProvider\";\nimport type { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { MsalMsiProvider } from \"./msalMsiProvider\";\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `clientId` and not `resourceId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `resourceId` and not `clientId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialResourceIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `objectId` as a constructor argument.\n */\nexport interface ManagedIdentityCredentialObjectIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID or resource ID and is not required for system-assigned managed identities.\n */\n objectId: string;\n}\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private implProvider: LegacyMsiProvider | MsalMsiProvider;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a client ID\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a resource ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with an object ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialObjectIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions\n | ManagedIdentityCredentialObjectIdOptions,\n options?: TokenCredentialOptions,\n ) {\n // https://github.com/Azure/azure-sdk-for-js/issues/30189\n // If needed, you may release a hotfix to quickly rollback to the legacy implementation by changing the following line to:\n // this.implProvider = new LegacyMsiProvider(clientIdOrOptions, options);\n // Once stabilized, you can remove the legacy implementation and inline the msalMsiProvider code here as a drop-in replacement.\n this.implProvider = new MsalMsiProvider(clientIdOrOptions, options);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n return this.implProvider.getToken(scopes, options);\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AACvF,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAG9C,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAwC7D;;;;;;;GAOG;AACH,MAAM,OAAO,yBAAyB;IAuCpC;;;OAGG;IACH,YACE,iBAI4C,EAC5C,OAAgC;;QA3C1B,mBAAc,GAAoC;YACxD,UAAU,EAAE,CAAC;YACb,cAAc,EAAE,GAAG;YACnB,iBAAiB,EAAE,CAAC;SACrB,CAAC;Q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AAE,CAAC;YAC3B,MAAM,WAAW,CAAC,yCAAyC,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC;CACF;AAED,SAAS,cAAc,CAAC,GAAQ;IAC9B,aAAa;IACb,IAAI,GAAG,CAAC,SAAS,KAAK,eAAe,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,eAAe;IACf,IAAI,GAAG,CAAC,IAAI,KAAK,aAAa,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;QAC9D,OAAO,IAAI,CAAC;IACd,CAAC;IAED,6NAA6N;IAC7N,4CAA4C;IAC5C,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE,CAAC;QAC/C,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport type { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { getMSALLogLevel, defaultLoggerCallback } from \"../../msal/utils\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy\";\nimport { MSIConfiguration } from \"./models\";\nimport { formatSuccess, formatError, credentialLogger } from \"../../util/logging\";\nimport { tracingClient } from \"../../util/tracing\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { mapScopesToResource } from \"./utils\";\nimport { MsalToken, ValidMsalToken } from \"../../msal/types\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `clientId` and not `resourceId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `resourceId` and not `clientId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialResourceIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `objectId` as a constructor argument.\n */\nexport interface ManagedIdentityCredentialObjectIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID or resource ID and is not required for system-assigned managed identities.\n */\n objectId: string;\n}\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private objectId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a client ID\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a resource ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with an object ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialObjectIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions\n | ManagedIdentityCredentialObjectIdOptions,\n options?: TokenCredentialOptions,\n ) {\n let _options: TokenCredentialOptions;\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options ?? {};\n } else {\n this.clientId = (clientIdOrOptions as ManagedIdentityCredentialClientIdOptions)?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = (_options as ManagedIdentityCredentialResourceIdOptions)?.resourceId;\n this.objectId = (_options as ManagedIdentityCredentialObjectIdOptions)?.objectId;\n\n // For JavaScript users.\n const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);\n if (providedIds.length > 1) {\n throw new Error(\n `ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify(\n { clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId },\n )}`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n userAssignedObjectId: this.objectId,\n },\n system: {\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: _options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.\n if (this.managedIdentityApp.getManagedIdentitySource() === \"CloudShell\") {\n if (this.clientId || this.resourceId || this.objectId) {\n logger.warning(\n `CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify(\n {\n clientId: this.clientId,\n resourceId: this.resourceId,\n objectId: this.objectId,\n },\n )}.`,\n );\n throw new CredentialUnavailableError(\n \"ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.\",\n );\n }\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(\n scopes,\n )}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable(this.clientId);\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n logger.getToken.info(`MSAL Identity source: ${identitySource}`);\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"Attempted to use the token exchange managed identity, but received a null response.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `Attempted to use the IMDS endpoint, but it is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n refreshAfterTimestamp: token.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n { cause: err },\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n { cause: err },\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw createError(\"No response.\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"models.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\n\nimport type { IdentityClient } from \"../../client/identityClient\";\n\n/**\n * @internal\n */\nexport interface MSIConfiguration {\n retryConfig: {\n maxRetries: number;\n startDelayInMs: number;\n intervalIncrement: number;\n };\n identityClient: IdentityClient;\n scopes: string | string[];\n clientId?: string;\n resourceId?: string;\n}\n\n/**\n * @internal\n * Represents an access token for {@link ManagedIdentity} for internal usage,\n * with an expiration time and the time in which token should refresh.\n */\nexport declare interface MSIToken extends AccessToken {}\n\n/**\n * @internal\n */\nexport interface MSI {\n name: string;\n isAvailable(options: {\n scopes: string | string[];\n identityClient?: IdentityClient;\n clientId?: string;\n resourceId?: string;\n getTokenOptions?: GetTokenOptions;\n }): Promise<boolean>;\n getToken(\n configuration: MSIConfiguration,\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSIToken | null>;\n}\n"]}
1
+ {"version":3,"file":"models.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken } from \"@azure/core-auth\";\n\nimport type { IdentityClient } from \"../../client/identityClient\";\n\n/**\n * @internal\n */\nexport interface MSIConfiguration {\n retryConfig: {\n maxRetries: number;\n startDelayInMs: number;\n intervalIncrement: number;\n };\n identityClient: IdentityClient;\n scopes: string | string[];\n clientId?: string;\n resourceId?: string;\n}\n\n/**\n * @internal\n * Represents an access token for {@link ManagedIdentity} for internal usage,\n * with an expiration time and the time in which token should refresh.\n */\nexport declare interface MSIToken extends AccessToken {}\n"]}
@@ -6,10 +6,13 @@ const msiName = "ManagedIdentityCredential - Token Exchange";
6
6
  const logger = credentialLogger(msiName);
7
7
  /**
8
8
  * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.
9
+ *
10
+ * Token exchange MSI (used by AKS) is the only MSI implementation handled entirely by Azure Identity.
11
+ * The rest have been migrated to MSAL.
9
12
  */
10
13
  export const tokenExchangeMsi = {
11
14
  name: "tokenExchangeMsi",
12
- async isAvailable({ clientId }) {
15
+ async isAvailable(clientId) {
13
16
  const env = process.env;
14
17
  const result = Boolean((clientId || env.AZURE_CLIENT_ID) &&
15
18
  env.AZURE_TENANT_ID &&
@@ -1 +1 @@
1
- {"version":3,"file":"tokenExchangeMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/tokenExchangeMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD,MAAM,OAAO,GAAG,4CAA4C,CAAC;AAC7D,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAQ;IACnC,IAAI,EAAE,kBAAkB;IACxB,KAAK,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE;QAC5B,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACxB,MAAM,MAAM,GAAG,OAAO,CACpB,CAAC,QAAQ,IAAI,GAAG,CAAC,eAAe,CAAC;YAC/B,GAAG,CAAC,eAAe;YACnB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CACzC,CAAC;QACF,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,qKAAqK,CAChL,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,KAAK,CAAC,QAAQ,CACZ,aAA+B,EAC/B,kBAAmC,EAAE;QAErC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,aAAa,CAAC;QAC3C,MAAM,oCAAoC,GAAG,EAAE,CAAC;QAChD,MAAM,0BAA0B,GAAG,IAAI,0BAA0B,CAAC,8BAChE,QAAQ,EACR,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,EACrC,aAAa,EAAE,OAAO,CAAC,GAAG,CAAC,0BAA0B,IAClD,oCAAoC,KACvC,wBAAwB,EAAE,IAAI,GACM,CAAC,CAAC;QACxC,OAAO,0BAA0B,CAAC,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACtE,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { MSI, MSIConfiguration } from \"./models\";\nimport { WorkloadIdentityCredential } from \"../workloadIdentityCredential\";\nimport { credentialLogger } from \"../../util/logging\";\nimport type { WorkloadIdentityCredentialOptions } from \"../workloadIdentityCredentialOptions\";\n\nconst msiName = \"ManagedIdentityCredential - Token Exchange\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.\n */\nexport const tokenExchangeMsi: MSI = {\n name: \"tokenExchangeMsi\",\n async isAvailable({ clientId }): Promise<boolean> {\n const env = process.env;\n const result = Boolean(\n (clientId || env.AZURE_CLIENT_ID) &&\n env.AZURE_TENANT_ID &&\n process.env.AZURE_FEDERATED_TOKEN_FILE,\n );\n if (!result) {\n logger.info(\n `${msiName}: 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`,\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<AccessToken | null> {\n const { scopes, clientId } = configuration;\n const identityClientTokenCredentialOptions = {};\n const workloadIdentityCredential = new WorkloadIdentityCredential({\n clientId,\n tenantId: process.env.AZURE_TENANT_ID,\n tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE,\n ...identityClientTokenCredentialOptions,\n disableInstanceDiscovery: true,\n } as WorkloadIdentityCredentialOptions);\n return workloadIdentityCredential.getToken(scopes, getTokenOptions);\n },\n};\n"]}
1
+ {"version":3,"file":"tokenExchangeMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/tokenExchangeMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD,MAAM,OAAO,GAAG,4CAA4C,CAAC;AAC7D,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,IAAI,EAAE,kBAAkB;IACxB,KAAK,CAAC,WAAW,CAAC,QAAiB;QACjC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACxB,MAAM,MAAM,GAAG,OAAO,CACpB,CAAC,QAAQ,IAAI,GAAG,CAAC,eAAe,CAAC;YAC/B,GAAG,CAAC,eAAe;YACnB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CACzC,CAAC;QACF,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,qKAAqK,CAChL,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,KAAK,CAAC,QAAQ,CACZ,aAA+B,EAC/B,kBAAmC,EAAE;QAErC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,aAAa,CAAC;QAC3C,MAAM,oCAAoC,GAAG,EAAE,CAAC;QAChD,MAAM,0BAA0B,GAAG,IAAI,0BAA0B,CAAC,8BAChE,QAAQ,EACR,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,EACrC,aAAa,EAAE,OAAO,CAAC,GAAG,CAAC,0BAA0B,IAClD,oCAAoC,KACvC,wBAAwB,EAAE,IAAI,GACM,CAAC,CAAC;QACxC,OAAO,0BAA0B,CAAC,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACtE,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { MSIConfiguration } from \"./models\";\nimport { WorkloadIdentityCredential } from \"../workloadIdentityCredential\";\nimport { credentialLogger } from \"../../util/logging\";\nimport type { WorkloadIdentityCredentialOptions } from \"../workloadIdentityCredentialOptions\";\n\nconst msiName = \"ManagedIdentityCredential - Token Exchange\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.\n *\n * Token exchange MSI (used by AKS) is the only MSI implementation handled entirely by Azure Identity.\n * The rest have been migrated to MSAL.\n */\nexport const tokenExchangeMsi = {\n name: \"tokenExchangeMsi\",\n async isAvailable(clientId?: string): Promise<boolean> {\n const env = process.env;\n const result = Boolean(\n (clientId || env.AZURE_CLIENT_ID) &&\n env.AZURE_TENANT_ID &&\n process.env.AZURE_FEDERATED_TOKEN_FILE,\n );\n if (!result) {\n logger.info(\n `${msiName}: 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`,\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<AccessToken | null> {\n const { scopes, clientId } = configuration;\n const identityClientTokenCredentialOptions = {};\n const workloadIdentityCredential = new WorkloadIdentityCredential({\n clientId,\n tenantId: process.env.AZURE_TENANT_ID,\n tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE,\n ...identityClientTokenCredentialOptions,\n disableInstanceDiscovery: true,\n } as WorkloadIdentityCredentialOptions);\n return workloadIdentityCredential.getToken(scopes, getTokenOptions);\n },\n};\n"]}
@@ -1,6 +1,6 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
- import { DefaultScopeSuffix } from "./constants";
3
+ const DefaultScopeSuffix = "/.default";
4
4
  /**
5
5
  * Most MSIs send requests to the IMDS endpoint, or a similar endpoint.
6
6
  * These are GET requests that require sending a `resource` parameter on the query.
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAyB;IAC3D,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxB,OAAO;QACT,CAAC;QAED,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;SAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QACtC,KAAK,GAAG,MAAM,CAAC;IACjB,CAAC;IAED,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC,CAAC;AAChE,CAAC;AAeD;;;GAG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GAAG,IAAI,CAAC;YACzB,CAAC;YAED,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC3C,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;gBACnB,OAAO,MAAM,CAAC;YAChB,CAAC;QACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,qDAAqD,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC;IAC3F,CAAC;SAAM,CAAC;QACN,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { DefaultScopeSuffix } from \"./constants\";\n\n/**\n * Most MSIs send requests to the IMDS endpoint, or a similar endpoint.\n * These are GET requests that require sending a `resource` parameter on the query.\n * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received.\n * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case.\n *\n * For that reason, when we encounter multiple scopes, we return undefined.\n * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors).\n */\nexport function mapScopesToResource(scopes: string | string[]): string | undefined {\n let scope = \"\";\n if (Array.isArray(scopes)) {\n if (scopes.length !== 1) {\n return;\n }\n\n scope = scopes[0];\n } else if (typeof scopes === \"string\") {\n scope = scopes;\n }\n\n if (!scope.endsWith(DefaultScopeSuffix)) {\n return scope;\n }\n\n return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n refresh_on?: number | string;\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseExpirationTimestamp(body: TokenResponseParsedBody): number {\n if (typeof body.expires_on === \"number\") {\n return body.expires_on * 1000;\n }\n\n if (typeof body.expires_on === \"string\") {\n const asNumber = +body.expires_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.expires_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n\n if (typeof body.expires_in === \"number\") {\n return Date.now() + body.expires_in * 1000;\n }\n\n throw new Error(\n `Failed to parse token expiration from body. expires_in=\"${body.expires_in}\", expires_on=\"${body.expires_on}\"`,\n );\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseRefreshTimestamp(body: TokenResponseParsedBody): number | undefined {\n if (body.refresh_on) {\n if (typeof body.refresh_on === \"number\") {\n return body.refresh_on * 1000;\n }\n\n if (typeof body.refresh_on === \"string\") {\n const asNumber = +body.refresh_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.refresh_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n throw new Error(`Failed to parse refresh_on from body. refresh_on=\"${body.refresh_on}\"`);\n } else {\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,kBAAkB,GAAG,WAAW,CAAC;AAEvC;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAyB;IAC3D,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxB,OAAO;QACT,CAAC;QAED,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;SAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QACtC,KAAK,GAAG,MAAM,CAAC;IACjB,CAAC;I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U,GAAG,IAAI,CAAC;QAChC,CAAC;QAED,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;YACxC,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC;YAClC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACrB,OAAO,QAAQ,GAAG,IAAI,CAAC;YACzB,CAAC;YAED,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC3C,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;gBACnB,OAAO,MAAM,CAAC;YAChB,CAAC;QACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,qDAAqD,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC;IAC3F,CAAC;SAAM,CAAC;QACN,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nconst DefaultScopeSuffix = \"/.default\";\n\n/**\n * Most MSIs send requests to the IMDS endpoint, or a similar endpoint.\n * These are GET requests that require sending a `resource` parameter on the query.\n * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received.\n * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case.\n *\n * For that reason, when we encounter multiple scopes, we return undefined.\n * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors).\n */\nexport function mapScopesToResource(scopes: string | string[]): string | undefined {\n let scope = \"\";\n if (Array.isArray(scopes)) {\n if (scopes.length !== 1) {\n return;\n }\n\n scope = scopes[0];\n } else if (typeof scopes === \"string\") {\n scope = scopes;\n }\n\n if (!scope.endsWith(DefaultScopeSuffix)) {\n return scope;\n }\n\n return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n refresh_on?: number | string;\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseExpirationTimestamp(body: TokenResponseParsedBody): number {\n if (typeof body.expires_on === \"number\") {\n return body.expires_on * 1000;\n }\n\n if (typeof body.expires_on === \"string\") {\n const asNumber = +body.expires_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.expires_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n\n if (typeof body.expires_in === \"number\") {\n return Date.now() + body.expires_in * 1000;\n }\n\n throw new Error(\n `Failed to parse token expiration from body. expires_in=\"${body.expires_in}\", expires_on=\"${body.expires_on}\"`,\n );\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseRefreshTimestamp(body: TokenResponseParsedBody): number | undefined {\n if (body.refresh_on) {\n if (typeof body.refresh_on === \"number\") {\n return body.refresh_on * 1000;\n }\n\n if (typeof body.refresh_on === \"string\") {\n const asNumber = +body.refresh_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.refresh_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n throw new Error(`Failed to parse refresh_on from body. refresh_on=\"${body.refresh_on}\"`);\n } else {\n return undefined;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@azure/identity",
3
3
  "sdk-type": "client",
4
- "version": "4.5.1-alpha.20241031.1",
4
+ "version": "4.5.1-alpha.20241112.1",
5
5
  "description": "Provides credential implementations for Azure SDK libraries that can authenticate with Microsoft Entra ID",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist-esm/src/index.js",
@@ -109,11 +109,11 @@
109
109
  "sideEffects": false,
110
110
  "dependencies": {
111
111
  "@azure/abort-controller": "^2.0.0",
112
- "@azure/core-auth": ">=1.9.0-alpha <1.9.0-alphb",
112
+ "@azure/core-auth": "^1.9.0",
113
113
  "@azure/core-client": "^1.9.2",
114
114
  "@azure/core-rest-pipeline": "^1.17.0",
115
115
  "@azure/core-tracing": "^1.0.0",
116
- "@azure/core-util": ">=1.11.0-alpha <1.11.0-alphb",
116
+ "@azure/core-util": "^1.11.0",
117
117
  "@azure/logger": "^1.0.0",
118
118
  "@azure/msal-node": "^2.15.0",
119
119
  "@azure/msal-browser": "^3.26.1",
@@ -139,7 +139,6 @@
139
139
  "@types/stoppable": "^1.1.0",
140
140
  "@types/uuid": "^8.0.0",
141
141
  "chai": "^4.2.0",
142
- "cross-env": "^7.0.3",
143
142
  "dotenv": "^16.0.0",
144
143
  "eslint": "^9.9.0",
145
144
  "inherits": "^2.0.3",
@@ -1312,7 +1312,13 @@ export declare const logger: AzureLogger;
1312
1312
  * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview
1313
1313
  */
1314
1314
  export declare class ManagedIdentityCredential implements TokenCredential {
1315
- private implProvider;
1315
+ private managedIdentityApp;
1316
+ private identityClient;
1317
+ private clientId?;
1318
+ private resourceId?;
1319
+ private objectId?;
1320
+ private msiRetryConfig;
1321
+ private isAvailableIdentityClient;
1316
1322
  /**
1317
1323
  * Creates an instance of ManagedIdentityCredential with the client ID of a
1318
1324
  * user-assigned identity, or app registration (when working with AKS pod-identity).
@@ -1349,6 +1355,10 @@ export declare class ManagedIdentityCredential implements TokenCredential {
1349
1355
  * TokenCredential implementation might make.
1350
1356
  */
1351
1357
  getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken>;
1358
+ /**
1359
+ * Ensures the validity of the MSAL token
1360
+ */
1361
+ private ensureValidMsalToken;
1352
1362
  }
1353
1363
 
1354
1364
  /**