@azure/identity-cache-persistence 1.1.2-alpha.20241031.1 → 1.1.2-alpha.20241112.1

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.
Files changed (26) hide show
  1. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsMsi.js +13 -37
  2. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsMsi.js.map +1 -1
  3. package/dist-esm/identity/src/credentials/managedIdentityCredential/index.js +189 -9
  4. package/dist-esm/identity/src/credentials/managedIdentityCredential/index.js.map +1 -1
  5. package/dist-esm/identity/src/credentials/managedIdentityCredential/models.js.map +1 -1
  6. package/dist-esm/identity/src/credentials/managedIdentityCredential/tokenExchangeMsi.js +5 -2
  7. package/dist-esm/identity/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +1 -1
  8. package/dist-esm/identity/src/credentials/managedIdentityCredential/utils.js +1 -1
  9. package/dist-esm/identity/src/credentials/managedIdentityCredential/utils.js.map +1 -1
  10. package/package.json +1 -2
  11. package/dist-esm/identity/src/credentials/managedIdentityCredential/appServiceMsi2017.js +0 -76
  12. package/dist-esm/identity/src/credentials/managedIdentityCredential/appServiceMsi2017.js.map +0 -1
  13. package/dist-esm/identity/src/credentials/managedIdentityCredential/appServiceMsi2019.js +0 -76
  14. package/dist-esm/identity/src/credentials/managedIdentityCredential/appServiceMsi2019.js.map +0 -1
  15. package/dist-esm/identity/src/credentials/managedIdentityCredential/arcMsi.js +0 -147
  16. package/dist-esm/identity/src/credentials/managedIdentityCredential/arcMsi.js.map +0 -1
  17. package/dist-esm/identity/src/credentials/managedIdentityCredential/cloudShellMsi.js +0 -80
  18. package/dist-esm/identity/src/credentials/managedIdentityCredential/cloudShellMsi.js.map +0 -1
  19. package/dist-esm/identity/src/credentials/managedIdentityCredential/constants.js +0 -9
  20. package/dist-esm/identity/src/credentials/managedIdentityCredential/constants.js.map +0 -1
  21. package/dist-esm/identity/src/credentials/managedIdentityCredential/fabricMsi.js +0 -100
  22. package/dist-esm/identity/src/credentials/managedIdentityCredential/fabricMsi.js.map +0 -1
  23. package/dist-esm/identity/src/credentials/managedIdentityCredential/legacyMsiProvider.js +0 -316
  24. package/dist-esm/identity/src/credentials/managedIdentityCredential/legacyMsiProvider.js.map +0 -1
  25. package/dist-esm/identity/src/credentials/managedIdentityCredential/msalMsiProvider.js +0 -215
  26. package/dist-esm/identity/src/credentials/managedIdentityCredential/msalMsiProvider.js.map +0 -1
@@ -2,14 +2,15 @@
2
2
  // Licensed under the MIT License.
3
3
  import { __awaiter } from "tslib";
4
4
  import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline";
5
- import { delay, isError } from "@azure/core-util";
6
- import { imdsApiVersion, imdsEndpointPath, imdsHost } from "./constants";
7
- import { AuthenticationError } from "../../errors";
5
+ import { isError } from "@azure/core-util";
8
6
  import { credentialLogger } from "../../util/logging";
9
7
  import { mapScopesToResource } from "./utils";
10
8
  import { tracingClient } from "../../util/tracing";
11
9
  const msiName = "ManagedIdentityCredential - IMDS";
12
10
  const logger = credentialLogger(msiName);
11
+ const imdsHost = "http://169.254.169.254";
12
+ const imdsEndpointPath = "/metadata/identity/oauth2/token";
13
+ const imdsApiVersion = "2018-02-01";
13
14
  /**
14
15
  * Generates the options used on the request for an access token.
15
16
  */
@@ -54,12 +55,15 @@ function prepareRequestOptions(scopes, clientId, resourceId, options) {
54
55
  };
55
56
  }
56
57
  /**
57
- * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.
58
+ * Defines how to determine whether the Azure IMDS MSI is available.
59
+ *
60
+ * Actually getting the token once we determine IMDS is available is handled by MSAL.
58
61
  */
59
62
  export const imdsMsi = {
60
63
  name: "imdsMsi",
61
- isAvailable(_a) {
62
- return __awaiter(this, arguments, void 0, function* ({ scopes, identityClient, clientId, resourceId, getTokenOptions = {}, }) {
64
+ isAvailable(options) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ const { scopes, identityClient, clientId, resourceId, getTokenOptions } = options;
63
67
  const resource = mapScopesToResource(scopes);
64
68
  if (!resource) {
65
69
  logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
@@ -76,16 +80,16 @@ export const imdsMsi = {
76
80
  skipMetadataHeader: true,
77
81
  skipQuery: true,
78
82
  });
79
- return tracingClient.withSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions, (options) => __awaiter(this, void 0, void 0, function* () {
83
+ return tracingClient.withSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions !== null && getTokenOptions !== void 0 ? getTokenOptions : {}, (updatedOptions) => __awaiter(this, void 0, void 0, function* () {
80
84
  var _a, _b;
81
- requestOptions.tracingOptions = options.tracingOptions;
85
+ requestOptions.tracingOptions = updatedOptions.tracingOptions;
82
86
  // Create a request with a timeout since we expect that
83
87
  // not having a "Metadata" header should cause an error to be
84
88
  // returned quickly from the endpoint, proving its availability.
85
89
  const request = createPipelineRequest(requestOptions);
86
90
  // Default to 1000 if the default of 0 is used.
87
91
  // Negative values can still be used to disable the timeout.
88
- request.timeout = ((_a = options.requestOptions) === null || _a === void 0 ? void 0 : _a.timeout) || 1000;
92
+ request.timeout = ((_a = updatedOptions.requestOptions) === null || _a === void 0 ? void 0 : _a.timeout) || 1000;
89
93
  // This MSI uses the imdsEndpoint to get the token, which only uses http://
90
94
  request.allowInsecureConnection = true;
91
95
  let response;
@@ -117,33 +121,5 @@ export const imdsMsi = {
117
121
  }));
118
122
  });
119
123
  },
120
- getToken(configuration_1) {
121
- return __awaiter(this, arguments, void 0, function* (configuration, getTokenOptions = {}) {
122
- const { identityClient, scopes, clientId, resourceId } = configuration;
123
- if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {
124
- 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}.`);
125
- }
126
- else {
127
- logger.info(`${msiName}: Using the default Azure IMDS endpoint ${imdsHost}.`);
128
- }
129
- let nextDelayInMs = configuration.retryConfig.startDelayInMs;
130
- for (let retries = 0; retries < configuration.retryConfig.maxRetries; retries++) {
131
- try {
132
- const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)), { allowInsecureConnection: true }));
133
- const tokenResponse = yield identityClient.sendTokenRequest(request);
134
- return (tokenResponse && tokenResponse.accessToken) || null;
135
- }
136
- catch (error) {
137
- if (error.statusCode === 404) {
138
- yield delay(nextDelayInMs);
139
- nextDelayInMs *= configuration.retryConfig.intervalIncrement;
140
- continue;
141
- }
142
- throw error;
143
- }
144
- }
145
- throw new AuthenticationError(404, `${msiName}: Failed to retrieve IMDS token after ${configuration.retryConfig.maxRetries} retries.`);
146
- });
147
- },
148
124
  };
149
125
  //# sourceMappingURL=imdsMsi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"imdsMsi.js","sourceRoot":"","sources":["../../../../../../identity/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;A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AAG,OAAO,0GAA0G,OAAO,CAAC,GAAG,CAAC,iCAAiC,GAAG,CACrK,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,2CAA2C,QAAQ,GAAG,CAAC,CAAC;YAChF,CAAC;YAED,IAAI,aAAa,GAAG,aAAa,CAAC,WAAW,CAAC,cAAc,CAAC;YAC7D,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,aAAa,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,EAAE,EAAE,CAAC;gBAChF,IAAI,CAAC;oBACH,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;oBACH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;oBAErE,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;gBAC9D,CAAC;gBAAC,OAAO,KAAU,EAAE,CAAC;oBACpB,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG,EAAE,CAAC;wBAC7B,MAAM,KAAK,CAAC,aAAa,CAAC,CAAC;wBAC3B,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,iBAAiB,CAAC;wBAC7D,SAAS;oBACX,CAAC;oBACD,MAAM,KAAK,CAAC;gBACd,CAAC;YACH,CAAC;YAED,MAAM,IAAI,mBAAmB,CAC3B,GAAG,EACH,GAAG,OAAO,yCAAyC,aAAa,CAAC,WAAW,CAAC,UAAU,WAAW,CACnG,CAAC;QACJ,CAAC;KAAA;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":["../../../../../../identity/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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;gBACH,CAAC;gBACD,yDAAyD;gBACzD,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,wCAAwC,CAAC,CAAC;gBAChE,OAAO,IAAI,CAAC;YACd,CAAC,CAAA,CACF,CAAC;QACJ,CAAC;KAAA;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,7 +1,18 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
3
  import { __awaiter } from "tslib";
4
- import { MsalMsiProvider } from "./msalMsiProvider";
4
+ import { getLogLevel } from "@azure/logger";
5
+ import { ManagedIdentityApplication } from "@azure/msal-node";
6
+ import { IdentityClient } from "../../client/identityClient";
7
+ import { AuthenticationRequiredError, CredentialUnavailableError } from "../../errors";
8
+ import { getMSALLogLevel, defaultLoggerCallback } from "../../msal/utils";
9
+ import { imdsRetryPolicy } from "./imdsRetryPolicy";
10
+ import { formatSuccess, formatError, credentialLogger } from "../../util/logging";
11
+ import { tracingClient } from "../../util/tracing";
12
+ import { imdsMsi } from "./imdsMsi";
13
+ import { tokenExchangeMsi } from "./tokenExchangeMsi";
14
+ import { mapScopesToResource } from "./utils";
15
+ const logger = credentialLogger("ManagedIdentityCredential");
5
16
  /**
6
17
  * Attempts authentication using a managed identity available at the deployment environment.
7
18
  * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,
@@ -16,11 +27,64 @@ export class ManagedIdentityCredential {
16
27
  * @hidden
17
28
  */
18
29
  constructor(clientIdOrOptions, options) {
19
- // https://github.com/Azure/azure-sdk-for-js/issues/30189
20
- // If needed, you may release a hotfix to quickly rollback to the legacy implementation by changing the following line to:
21
- // this.implProvider = new LegacyMsiProvider(clientIdOrOptions, options);
22
- // Once stabilized, you can remove the legacy implementation and inline the msalMsiProvider code here as a drop-in replacement.
23
- this.implProvider = new MsalMsiProvider(clientIdOrOptions, options);
30
+ var _a, _b;
31
+ this.msiRetryConfig = {
32
+ maxRetries: 5,
33
+ startDelayInMs: 800,
34
+ intervalIncrement: 2,
35
+ };
36
+ let _options;
37
+ if (typeof clientIdOrOptions === "string") {
38
+ this.clientId = clientIdOrOptions;
39
+ _options = options !== null && options !== void 0 ? options : {};
40
+ }
41
+ else {
42
+ this.clientId = clientIdOrOptions === null || clientIdOrOptions === void 0 ? void 0 : clientIdOrOptions.clientId;
43
+ _options = clientIdOrOptions !== null && clientIdOrOptions !== void 0 ? clientIdOrOptions : {};
44
+ }
45
+ this.resourceId = _options === null || _options === void 0 ? void 0 : _options.resourceId;
46
+ this.objectId = _options === null || _options === void 0 ? void 0 : _options.objectId;
47
+ // For JavaScript users.
48
+ const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);
49
+ if (providedIds.length > 1) {
50
+ 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 })}`);
51
+ }
52
+ // ManagedIdentity uses http for local requests
53
+ _options.allowInsecureConnection = true;
54
+ if (((_a = _options.retryOptions) === null || _a === void 0 ? void 0 : _a.maxRetries) !== undefined) {
55
+ this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;
56
+ }
57
+ this.identityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: "perCall" }] }));
58
+ this.managedIdentityApp = new ManagedIdentityApplication({
59
+ managedIdentityIdParams: {
60
+ userAssignedClientId: this.clientId,
61
+ userAssignedResourceId: this.resourceId,
62
+ userAssignedObjectId: this.objectId,
63
+ },
64
+ system: {
65
+ disableInternalRetries: true,
66
+ networkClient: this.identityClient,
67
+ loggerOptions: {
68
+ logLevel: getMSALLogLevel(getLogLevel()),
69
+ piiLoggingEnabled: (_b = _options.loggingOptions) === null || _b === void 0 ? void 0 : _b.enableUnsafeSupportLogging,
70
+ loggerCallback: defaultLoggerCallback(logger),
71
+ },
72
+ },
73
+ });
74
+ this.isAvailableIdentityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { retryOptions: {
75
+ maxRetries: 0,
76
+ } }));
77
+ // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.
78
+ if (this.managedIdentityApp.getManagedIdentitySource() === "CloudShell") {
79
+ if (this.clientId || this.resourceId || this.objectId) {
80
+ logger.warning(`CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify({
81
+ clientId: this.clientId,
82
+ resourceId: this.resourceId,
83
+ objectId: this.objectId,
84
+ })}.`);
85
+ 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.");
86
+ }
87
+ }
24
88
  }
25
89
  /**
26
90
  * Authenticates with Microsoft Entra ID and returns an access token if successful.
@@ -31,10 +95,126 @@ export class ManagedIdentityCredential {
31
95
  * @param options - The options used to configure any requests this
32
96
  * TokenCredential implementation might make.
33
97
  */
34
- getToken(scopes, options) {
35
- return __awaiter(this, void 0, void 0, function* () {
36
- return this.implProvider.getToken(scopes, options);
98
+ getToken(scopes_1) {
99
+ return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
100
+ logger.getToken.info("Using the MSAL provider for Managed Identity.");
101
+ const resource = mapScopesToResource(scopes);
102
+ if (!resource) {
103
+ throw new CredentialUnavailableError(`ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`);
104
+ }
105
+ return tracingClient.withSpan("ManagedIdentityCredential.getToken", options, () => __awaiter(this, void 0, void 0, function* () {
106
+ var _a;
107
+ try {
108
+ const isTokenExchangeMsi = yield tokenExchangeMsi.isAvailable(this.clientId);
109
+ // Most scenarios are handled by MSAL except for two:
110
+ // AKS pod identity - MSAL does not implement the token exchange flow.
111
+ // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.
112
+ // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token
113
+ // We will continue to implement these features in the Identity library.
114
+ const identitySource = this.managedIdentityApp.getManagedIdentitySource();
115
+ 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.
116
+ logger.getToken.info(`MSAL Identity source: ${identitySource}`);
117
+ if (isTokenExchangeMsi) {
118
+ // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.
119
+ logger.getToken.info("Using the token exchange managed identity.");
120
+ const result = yield tokenExchangeMsi.getToken({
121
+ scopes,
122
+ clientId: this.clientId,
123
+ identityClient: this.identityClient,
124
+ retryConfig: this.msiRetryConfig,
125
+ resourceId: this.resourceId,
126
+ });
127
+ if (result === null) {
128
+ throw new CredentialUnavailableError("Attempted to use the token exchange managed identity, but received a null response.");
129
+ }
130
+ return result;
131
+ }
132
+ else if (isImdsMsi) {
133
+ // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.
134
+ // 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.
135
+ logger.getToken.info("Using the IMDS endpoint to probe for availability.");
136
+ const isAvailable = yield imdsMsi.isAvailable({
137
+ scopes,
138
+ clientId: this.clientId,
139
+ getTokenOptions: options,
140
+ identityClient: this.isAvailableIdentityClient,
141
+ resourceId: this.resourceId,
142
+ });
143
+ if (!isAvailable) {
144
+ throw new CredentialUnavailableError(`Attempted to use the IMDS endpoint, but it is not available.`);
145
+ }
146
+ }
147
+ // If we got this far, it means:
148
+ // - This is not a tokenExchangeMsi,
149
+ // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.
150
+ // We can proceed normally by calling MSAL for a token.
151
+ logger.getToken.info("Calling into MSAL for managed identity token.");
152
+ const token = yield this.managedIdentityApp.acquireToken({
153
+ resource,
154
+ });
155
+ this.ensureValidMsalToken(scopes, token, options);
156
+ logger.getToken.info(formatSuccess(scopes));
157
+ return {
158
+ expiresOnTimestamp: token.expiresOn.getTime(),
159
+ token: token.accessToken,
160
+ refreshAfterTimestamp: (_a = token.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(),
161
+ tokenType: "Bearer",
162
+ };
163
+ }
164
+ catch (err) {
165
+ logger.getToken.error(formatError(scopes, err));
166
+ // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.
167
+ // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?
168
+ if (err.name === "AuthenticationRequiredError") {
169
+ throw err;
170
+ }
171
+ if (isNetworkError(err)) {
172
+ throw new CredentialUnavailableError(`ManagedIdentityCredential: Network unreachable. Message: ${err.message}`, { cause: err });
173
+ }
174
+ throw new CredentialUnavailableError(`ManagedIdentityCredential: Authentication failed. Message ${err.message}`, { cause: err });
175
+ }
176
+ }));
37
177
  });
38
178
  }
179
+ /**
180
+ * Ensures the validity of the MSAL token
181
+ */
182
+ ensureValidMsalToken(scopes, msalToken, getTokenOptions) {
183
+ const createError = (message) => {
184
+ logger.getToken.info(message);
185
+ return new AuthenticationRequiredError({
186
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
187
+ getTokenOptions,
188
+ message,
189
+ });
190
+ };
191
+ if (!msalToken) {
192
+ throw createError("No response.");
193
+ }
194
+ if (!msalToken.expiresOn) {
195
+ throw createError(`Response had no "expiresOn" property.`);
196
+ }
197
+ if (!msalToken.accessToken) {
198
+ throw createError(`Response had no "accessToken" property.`);
199
+ }
200
+ }
201
+ }
202
+ function isNetworkError(err) {
203
+ // MSAL error
204
+ if (err.errorCode === "network_error") {
205
+ return true;
206
+ }
207
+ // Probe errors
208
+ if (err.code === "ENETUNREACH" || err.code === "EHOSTUNREACH") {
209
+ return true;
210
+ }
211
+ // 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"
212
+ // rather than just timing out, as expected.
213
+ if (err.statusCode === 403 || err.code === 403) {
214
+ if (err.message.includes("unreachable")) {
215
+ return true;
216
+ }
217
+ }
218
+ return false;
39
219
  }
40
220
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../identity/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;IACU,QAAQ,CACnB,MAAyB,EACzB,OAAyB;;YAEzB,OAAO,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACrD,CAAC;KAAA;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":["../../../../../../identity/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;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AAC;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":["../../../../../../identity/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":["../../../../../../identity/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"]}
@@ -7,11 +7,14 @@ const msiName = "ManagedIdentityCredential - Token Exchange";
7
7
  const logger = credentialLogger(msiName);
8
8
  /**
9
9
  * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.
10
+ *
11
+ * Token exchange MSI (used by AKS) is the only MSI implementation handled entirely by Azure Identity.
12
+ * The rest have been migrated to MSAL.
10
13
  */
11
14
  export const tokenExchangeMsi = {
12
15
  name: "tokenExchangeMsi",
13
- isAvailable(_a) {
14
- return __awaiter(this, arguments, void 0, function* ({ clientId }) {
16
+ isAvailable(clientId) {
17
+ return __awaiter(this, void 0, void 0, function* () {
15
18
  const env = process.env;
16
19
  const result = Boolean((clientId || env.AZURE_CLIENT_ID) &&
17
20
  env.AZURE_TENANT_ID &&
@@ -1 +1 @@
1
- {"version":3,"file":"tokenExchangeMsi.js","sourceR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KAAA;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":["../../../../../../identity/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;IAClB,WAAW,CAAC,QAAiB;;YACjC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;YACxB,MAAM,MAAM,GAAG,OAAO,CACpB,CAAC,QAAQ,IAAI,GAAG,CAAC,eAAe,CAAC;gBAC/B,GAAG,CAAC,eAAe;gBACnB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CACzC,CAAC;YACF,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,qKAAqK,CAChL,CAAC;YACJ,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;KAAA;IACK,QAAQ;6DACZ,aAA+B,EAC/B,kBAAmC,EAAE;YAErC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,aAAa,CAAC;YAC3C,MAAM,oCAAoC,GAAG,EAAE,CAAC;YAChD,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;YACxC,OAAO,0BAA0B,CAAC,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;QACtE,CAAC;KAAA;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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K,CAAC,MAAM,CAAC,EAAE,CAAC;YACnB,OAAO,MAAM,CAAC;QAChB,CAAC;IACH,CAAC;IAED,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;IAC7C,CAAC;IAED,MAAM,IAAI,KAAK,CACb,2DAA2D,IAAI,CAAC,UAAU,kBAAkB,IAAI,CAAC,UAAU,GAAG,CAC/G,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAA6B;IACjE,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC,UAAU,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\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":["../../../../../../identity/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;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;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAA6B;IACpE,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;IAChC,CAAC;IAED,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;QACxC,MAAM,QAAQ,GAAG,CAAC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,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,6 +1,6 @@
1
1
  {
2
2
  "name": "@azure/identity-cache-persistence",
3
- "version": "1.1.2-alpha.20241031.1",
3
+ "version": "1.1.2-alpha.20241112.1",
4
4
  "sdk-type": "client",
5
5
  "description": "A secure, persistent token cache for Azure Identity credentials that uses the OS secret-management API",
6
6
  "main": "dist/index.js",
@@ -78,7 +78,6 @@
78
78
  "@types/node": "^18.0.0",
79
79
  "@types/qs": "^6.5.3",
80
80
  "@types/sinon": "^17.0.0",
81
- "cross-env": "^7.0.2",
82
81
  "dotenv": "^16.0.0",
83
82
  "eslint": "^9.9.0",
84
83
  "inherits": "^2.0.3",
@@ -1,76 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import { __awaiter } from "tslib";
4
- import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline";
5
- import { credentialLogger } from "../../util/logging";
6
- import { mapScopesToResource } from "./utils";
7
- const msiName = "ManagedIdentityCredential - AppServiceMSI 2017";
8
- const logger = credentialLogger(msiName);
9
- /**
10
- * Generates the options used on the request for an access token.
11
- */
12
- function prepareRequestOptions(scopes, clientId) {
13
- const resource = mapScopesToResource(scopes);
14
- if (!resource) {
15
- throw new Error(`${msiName}: Multiple scopes are not supported.`);
16
- }
17
- const queryParameters = {
18
- resource,
19
- "api-version": "2017-09-01",
20
- };
21
- if (clientId) {
22
- queryParameters.clientid = clientId;
23
- }
24
- const query = new URLSearchParams(queryParameters);
25
- // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
26
- if (!process.env.MSI_ENDPOINT) {
27
- throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);
28
- }
29
- if (!process.env.MSI_SECRET) {
30
- throw new Error(`${msiName}: Missing environment variable: MSI_SECRET`);
31
- }
32
- return {
33
- url: `${process.env.MSI_ENDPOINT}?${query.toString()}`,
34
- method: "GET",
35
- headers: createHttpHeaders({
36
- Accept: "application/json",
37
- secret: process.env.MSI_SECRET,
38
- }),
39
- };
40
- }
41
- /**
42
- * Defines how to determine whether the Azure App Service MSI is available, and also how to retrieve a token from the Azure App Service MSI.
43
- */
44
- export const appServiceMsi2017 = {
45
- name: "appServiceMsi2017",
46
- isAvailable(_a) {
47
- return __awaiter(this, arguments, void 0, function* ({ scopes }) {
48
- const resource = mapScopesToResource(scopes);
49
- if (!resource) {
50
- logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
51
- return false;
52
- }
53
- const env = process.env;
54
- const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);
55
- if (!result) {
56
- logger.info(`${msiName}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`);
57
- }
58
- return result;
59
- });
60
- },
61
- getToken(configuration_1) {
62
- return __awaiter(this, arguments, void 0, function* (configuration, getTokenOptions = {}) {
63
- const { identityClient, scopes, clientId, resourceId } = configuration;
64
- if (resourceId) {
65
- logger.warning(`${msiName}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
66
- }
67
- logger.info(`${msiName}: Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`);
68
- const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId)), {
69
- // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
70
- allowInsecureConnection: true }));
71
- const tokenResponse = yield identityClient.sendTokenRequest(request);
72
- return (tokenResponse && tokenResponse.accessToken) || null;
73
- });
74
- },
75
- };
76
- //# sourceMappingURL=appServiceMsi2017.js.map