@azure/identity 2.0.5-alpha.20220221.1 → 2.1.0-alpha.20220308.3

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

Potentially problematic release.


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

Files changed (27) hide show
  1. package/CHANGELOG.md +11 -10
  2. package/README.md +2 -1
  3. package/dist/index.js +81 -41
  4. package/dist/index.js.map +1 -1
  5. package/dist-esm/src/client/identityClient.js +1 -1
  6. package/dist-esm/src/client/identityClient.js.map +1 -1
  7. package/dist-esm/src/credentials/defaultAzureCredential.js +7 -9
  8. package/dist-esm/src/credentials/defaultAzureCredential.js.map +1 -1
  9. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js +5 -2
  10. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js.map +1 -1
  11. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js +16 -7
  12. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js.map +1 -1
  13. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js +11 -5
  14. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js.map +1 -1
  15. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js +10 -4
  16. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js.map +1 -1
  17. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js +11 -5
  18. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js.map +1 -1
  19. package/dist-esm/src/credentials/managedIdentityCredential/index.js +20 -8
  20. package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
  21. package/dist-esm/src/credentials/managedIdentityCredential/models.js.map +1 -1
  22. package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js +1 -1
  23. package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +1 -1
  24. package/dist-esm/src/index.js +1 -1
  25. package/dist-esm/src/index.js.map +1 -1
  26. package/package.json +1 -1
  27. package/types/identity.d.ts +60 -2
@@ -34,7 +34,7 @@ export function getIdentityClientAuthorityHost(options) {
34
34
  export class IdentityClient extends ServiceClient {
35
35
  constructor(options) {
36
36
  var _a;
37
- const packageDetails = `azsdk-js-identity/2.0.5`;
37
+ const packageDetails = `azsdk-js-identity/2.1.0-beta.1`;
38
38
  const userAgentPrefix = ((_a = options === null || options === void 0 ? void 0 : options.userAgentOptions) === null || _a === void 0 ? void 0 : _a.userAgentPrefix)
39
39
  ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
40
40
  : `${packageDetails}`;
@@ -1 +1 @@
1
- {"version":3,"file":"identityClient.js","sourceRoot":"","sources":["../../../src/client/identityClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,eAAe,EAAmB,MAAM,yBAAyB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AACzE,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGzC,MAAM,eAAe,GAAG,iBAAiB,CAAC;AA+B1C;;GAEG;AACH,MAAM,UAAU,8BAA8B,CAAC,OAAgC;IAC7E,iGAAiG;IACjG,IAAI,aAAa,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa,CAAC;IAE3C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I,CAAC,mBAAmB,CAAC,eAAe,CAAC;SACvD,CAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACjD,OAAO;YACL,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS;YACvE,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE;YAClC,MAAM,EAAE,QAAQ,CAAC,MAAM;SACxB,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,oBAAoB,CACxB,GAAW,EACX,OAA+B;QAE/B,MAAM,OAAO,GAAG,qBAAqB,CAAC;YACpC,GAAG;YACH,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI;YACnB,OAAO,EAAE,iBAAiB,CAAC,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,CAAC;YAC5C,4DAA4D;YAC5D,WAAW,EAAE,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;SACtE,CAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACjD,OAAO;YACL,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS;YACvE,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE;YAClC,MAAM,EAAE,QAAQ,CAAC,MAAM;SACxB,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortController, AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost } from \"../constants\";\nimport { createSpan } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\n\nconst noCorrelationId = \"noCorrelationId\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the access token.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken;\n\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string;\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n token?: string;\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n}\n\n/**\n * @internal\n */\nexport function getIdentityClientAuthorityHost(options?: TokenCredentialOptions): string {\n // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.\n let authorityHost = options?.authorityHost;\n\n // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.\n if (isNode) {\n authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;\n }\n\n // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * The network module used by the Identity credentials.\n *\n * It allows for credentials to abort any pending request independently of the MSAL flow,\n * by calling to the `abortRequests()` method.\n *\n */\nexport class IdentityClient extends ServiceClient implements INetworkModule {\n public authorityHost: string;\n private abortControllers: Map<string, AbortController[] | undefined>;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/2.0.5`;\n const userAgentPrefix = options?.userAgentOptions?.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const baseUri = getIdentityClientAuthorityHost(options);\n if (!baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n\n super({\n requestContentType: \"application/json; charset=utf-8\",\n retryOptions: {\n maxRetries: 3,\n },\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n baseUri,\n });\n\n this.authorityHost = baseUri;\n this.abortControllers = new Map();\n }\n\n async sendTokenRequest(\n request: PipelineRequest,\n expiresOnParser?: (responseBody: TokenResponseParsedBody) => number\n ): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\n\n expiresOnParser =\n expiresOnParser ||\n ((responseBody: TokenResponseParsedBody) => {\n return Date.now() + responseBody.expires_in * 1000;\n });\n\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: TokenResponseParsedBody = JSON.parse(response.bodyAsText);\n\n if (!parsedBody.access_token) {\n return null;\n }\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: expiresOnParser(parsedBody),\n },\n refreshToken: parsedBody.refresh_token,\n };\n\n logger.info(\n `IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`\n );\n return token;\n } else {\n const error = new AuthenticationError(response.status, response.bodyAsText);\n logger.warning(\n `IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`\n );\n throw error;\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n expiresOnParser?: (responseBody: TokenResponseParsedBody) => number,\n options?: GetTokenOptions\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n logger.info(\n `IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`\n );\n\n const { span, updatedOptions } = createSpan(\"IdentityClient-refreshAccessToken\", options);\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes,\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const query = new URLSearchParams(refreshParams);\n\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);\n const request = createPipelineRequest({\n url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: query.toString(),\n abortSignal: options && options.abortSignal,\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n tracingOptions: updatedOptions?.tracingOptions,\n });\n\n const response = await this.sendTokenRequest(request, expiresOnParser);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err) {\n if (\n err.name === AuthenticationErrorName &&\n err.errorResponse.error === \"interaction_required\"\n ) {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n\n return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`\n );\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n }\n } finally {\n span.end();\n }\n }\n\n // Here is a custom layer that allows us to abort requests that go through MSAL,\n // since MSAL doesn't allow us to pass options all the way through.\n\n generateAbortSignal(correlationId: string): AbortSignalLike {\n const controller = new AbortController();\n const controllers = this.abortControllers.get(correlationId) || [];\n controllers.push(controller);\n this.abortControllers.set(correlationId, controllers);\n const existingOnAbort = controller.signal.onabort;\n controller.signal.onabort = (...params) => {\n this.abortControllers.set(correlationId, undefined);\n if (existingOnAbort) {\n existingOnAbort(...params);\n }\n };\n return controller.signal;\n }\n\n abortRequests(correlationId?: string): void {\n const key = correlationId || noCorrelationId;\n const controllers = [\n ...(this.abortControllers.get(key) || []),\n // MSAL passes no correlation ID to the get requests...\n ...(this.abortControllers.get(noCorrelationId) || []),\n ];\n if (!controllers.length) {\n return;\n }\n for (const controller of controllers) {\n controller.abort();\n }\n this.abortControllers.set(key, undefined);\n }\n\n getCorrelationId(options?: NetworkRequestOptions): string {\n const parameter = options?.body\n ?.split(\"&\")\n .map((part) => part.split(\"=\"))\n .find(([key]) => key === \"client-request-id\");\n return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;\n }\n\n // The MSAL network module methods follow\n\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"GET\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"POST\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n // MSAL doesn't send the correlation ID on the get requests.\n abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),\n });\n\n const response = await this.sendRequest(request);\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"identityClient.js","sourceRoot":"","sources":["../../../src/client/identityClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAA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iB,CAAC,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,CAAC;YAC5C,4DAA4D;YAC5D,WAAW,EAAE,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;SACtE,CAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACjD,OAAO;YACL,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS;YACvE,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE;YAClC,MAAM,EAAE,QAAQ,CAAC,MAAM;SACxB,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-common\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortController, AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost } from \"../constants\";\nimport { createSpan } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\n\nconst noCorrelationId = \"noCorrelationId\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the access token.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken;\n\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string;\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n token?: string;\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n}\n\n/**\n * @internal\n */\nexport function getIdentityClientAuthorityHost(options?: TokenCredentialOptions): string {\n // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.\n let authorityHost = options?.authorityHost;\n\n // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.\n if (isNode) {\n authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;\n }\n\n // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * The network module used by the Identity credentials.\n *\n * It allows for credentials to abort any pending request independently of the MSAL flow,\n * by calling to the `abortRequests()` method.\n *\n */\nexport class IdentityClient extends ServiceClient implements INetworkModule {\n public authorityHost: string;\n private abortControllers: Map<string, AbortController[] | undefined>;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/2.1.0-beta.1`;\n const userAgentPrefix = options?.userAgentOptions?.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const baseUri = getIdentityClientAuthorityHost(options);\n if (!baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n\n super({\n requestContentType: \"application/json; charset=utf-8\",\n retryOptions: {\n maxRetries: 3,\n },\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n baseUri,\n });\n\n this.authorityHost = baseUri;\n this.abortControllers = new Map();\n }\n\n async sendTokenRequest(\n request: PipelineRequest,\n expiresOnParser?: (responseBody: TokenResponseParsedBody) => number\n ): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\n\n expiresOnParser =\n expiresOnParser ||\n ((responseBody: TokenResponseParsedBody) => {\n return Date.now() + responseBody.expires_in * 1000;\n });\n\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: TokenResponseParsedBody = JSON.parse(response.bodyAsText);\n\n if (!parsedBody.access_token) {\n return null;\n }\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: expiresOnParser(parsedBody),\n },\n refreshToken: parsedBody.refresh_token,\n };\n\n logger.info(\n `IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`\n );\n return token;\n } else {\n const error = new AuthenticationError(response.status, response.bodyAsText);\n logger.warning(\n `IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`\n );\n throw error;\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n expiresOnParser?: (responseBody: TokenResponseParsedBody) => number,\n options?: GetTokenOptions\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n logger.info(\n `IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`\n );\n\n const { span, updatedOptions } = createSpan(\"IdentityClient-refreshAccessToken\", options);\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes,\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const query = new URLSearchParams(refreshParams);\n\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);\n const request = createPipelineRequest({\n url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: query.toString(),\n abortSignal: options && options.abortSignal,\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n tracingOptions: updatedOptions?.tracingOptions,\n });\n\n const response = await this.sendTokenRequest(request, expiresOnParser);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err) {\n if (\n err.name === AuthenticationErrorName &&\n err.errorResponse.error === \"interaction_required\"\n ) {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n\n return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`\n );\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n }\n } finally {\n span.end();\n }\n }\n\n // Here is a custom layer that allows us to abort requests that go through MSAL,\n // since MSAL doesn't allow us to pass options all the way through.\n\n generateAbortSignal(correlationId: string): AbortSignalLike {\n const controller = new AbortController();\n const controllers = this.abortControllers.get(correlationId) || [];\n controllers.push(controller);\n this.abortControllers.set(correlationId, controllers);\n const existingOnAbort = controller.signal.onabort;\n controller.signal.onabort = (...params) => {\n this.abortControllers.set(correlationId, undefined);\n if (existingOnAbort) {\n existingOnAbort(...params);\n }\n };\n return controller.signal;\n }\n\n abortRequests(correlationId?: string): void {\n const key = correlationId || noCorrelationId;\n const controllers = [\n ...(this.abortControllers.get(key) || []),\n // MSAL passes no correlation ID to the get requests...\n ...(this.abortControllers.get(noCorrelationId) || []),\n ];\n if (!controllers.length) {\n return;\n }\n for (const controller of controllers) {\n controller.abort();\n }\n this.abortControllers.set(key, undefined);\n }\n\n getCorrelationId(options?: NetworkRequestOptions): string {\n const parameter = options?.body\n ?.split(\"&\")\n .map((part) => part.split(\"=\"))\n .find(([key]) => key === \"client-request-id\");\n return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;\n }\n\n // The MSAL network module methods follow\n\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"GET\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"POST\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n // MSAL doesn't send the correlation ID on the get requests.\n abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),\n });\n\n const response = await this.sendRequest(request);\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n}\n"]}
@@ -4,7 +4,7 @@ import { ChainedTokenCredential } from "./chainedTokenCredential";
4
4
  import { AzureCliCredential } from "./azureCliCredential";
5
5
  import { AzurePowerShellCredential } from "./azurePowerShellCredential";
6
6
  import { EnvironmentCredential } from "./environmentCredential";
7
- import { ManagedIdentityCredential } from "./managedIdentityCredential";
7
+ import { ManagedIdentityCredential, } from "./managedIdentityCredential";
8
8
  import { VisualStudioCodeCredential } from "./visualStudioCodeCredential";
9
9
  /**
10
10
  * A shim around ManagedIdentityCredential that adapts it to accept
@@ -14,14 +14,12 @@ import { VisualStudioCodeCredential } from "./visualStudioCodeCredential";
14
14
  */
15
15
  export class DefaultManagedIdentityCredential extends ManagedIdentityCredential {
16
16
  constructor(options) {
17
- var _a;
18
- const managedIdentityClientId = (_a = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _a !== void 0 ? _a : process.env.AZURE_CLIENT_ID;
19
- if (managedIdentityClientId !== undefined) {
20
- super(managedIdentityClientId, options);
21
- }
22
- else {
23
- super(options);
24
- }
17
+ var _a, _b, _c;
18
+ const managedIdentityClientId = (_b = (_a = options) === null || _a === void 0 ? void 0 : _a.managedIdentityClientId) !== null && _b !== void 0 ? _b : process.env.AZURE_CLIENT_ID;
19
+ const managedResourceId = (_c = options) === null || _c === void 0 ? void 0 : _c.managedIdentityResourceId;
20
+ // ManagedIdentityCredential throws if both the resourceId and the clientId are provided.
21
+ const managedIdentityOptions = Object.assign({ resourceId: managedResourceId, clientId: managedIdentityClientId }, options);
22
+ super(managedIdentityOptions);
25
23
  }
26
24
  }
27
25
  export const defaultCredentials = [
@@ -1 +1 @@
1
- {"version":3,"file":"defaultAzureCredential.js","sourceRoot":"","sources":["../../../src/credentials/defaultAzureCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AA0B1E;;;;;GAKG;AACH,MAAM,OAAO,gCAAiC,SAAQ,yBAAyB;IAC7E,YAAY,OAAuC;;QACjD,MAAM,uBAAuB,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,uBAAuB,mCAAI,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC;QAChG,IAAI,uBAAuB,KAAK,SAAS,EAAE;YACzC,KAAK,CAAC,uBAAuB,EAAE,OAAO,CAAC,CAAC;SACzC;aAAM;YACL,KAAK,CAAC,OAAO,CAAC,CAAC;SAChB;IACH,CAAC;CACF;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAmC;IAChE,qBAAqB;IACrB,gCAAgC;IAChC,0BAA0B;IAC1B,kBAAkB;IAClB,yBAAyB;CAC1B,CAAC;AAEF;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,sBAAsB;IAChE;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,YAAY,OAAuC;QACjD,KAAK,CAAC,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QAC9D,IAAI,CAAC,kBAAkB;YACrB,kLAAkL,CAAC;IACvL,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TokenCredential } from \"@azure/core-auth\";\n\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\n\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\n\nimport { AzureCliCredential } from \"./azureCliCredential\";\nimport { AzurePowerShellCredential } from \"./azurePowerShellCredential\";\nimport { EnvironmentCredential } from \"./environmentCredential\";\nimport { ManagedIdentityCredential } from \"./managedIdentityCredential\";\nimport { VisualStudioCodeCredential } from \"./visualStudioCodeCredential\";\n\n/**\n * Provides options to configure the {@link DefaultAzureCredential} class.\n */\nexport interface DefaultAzureCredentialOptions extends TokenCredentialOptions {\n /**\n * Optionally pass in a Tenant ID to be used as part of the credential.\n * By default it may use a generic tenant ID depending on the underlying credential.\n */\n tenantId?: string;\n /**\n * Optionally pass in a user assigned client ID to be used by the {@link ManagedIdentityCredential}.\n * This client ID can also be passed through to the {@link ManagedIdentityCredential} through the environment variable: AZURE_CLIENT_ID.\n */\n managedIdentityClientId?: string;\n}\n\n/**\n * The type of a class that implements TokenCredential and accepts\n * `DefaultAzureCredentialOptions`.\n */\ninterface DefaultCredentialConstructor {\n new (options?: DefaultAzureCredentialOptions): TokenCredential;\n}\n\n/**\n * A shim around ManagedIdentityCredential that adapts it to accept\n * `DefaultAzureCredentialOptions`.\n *\n * @internal\n */\nexport class DefaultManagedIdentityCredential extends ManagedIdentityCredential {\n constructor(options?: DefaultAzureCredentialOptions) {\n const managedIdentityClientId = options?.managedIdentityClientId ?? process.env.AZURE_CLIENT_ID;\n if (managedIdentityClientId !== undefined) {\n super(managedIdentityClientId, options);\n } else {\n super(options);\n }\n }\n}\n\nexport const defaultCredentials: DefaultCredentialConstructor[] = [\n EnvironmentCredential,\n DefaultManagedIdentityCredential,\n VisualStudioCodeCredential,\n AzureCliCredential,\n AzurePowerShellCredential,\n];\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n */\nexport class DefaultAzureCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the DefaultAzureCredential class.\n *\n * This credential provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n *\n * The following credential types will be tried, in order:\n *\n * - {@link EnvironmentCredential}\n * - {@link ManagedIdentityCredential}\n * - {@link VisualStudioCodeCredential}\n * - {@link AzureCliCredential}\n * - {@link AzurePowerShellCredential}\n *\n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n *\n * **Note**: `VisualStudioCodeCredential` is provided by a plugin package:\n * `@azure/identity-vscode`. If this package is not installed and registered\n * using the plugin API (`useIdentityPlugin`), then authentication using\n * `VisualStudioCodeCredential` will not be available.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialOptions}.\n */\n constructor(options?: DefaultAzureCredentialOptions) {\n super(...defaultCredentials.map((ctor) => new ctor(options)));\n this.UnavailableMessage =\n \"DefaultAzureCredential => failed to retrieve a token from the included credentials. To troubleshoot, visit https://aka.ms/azsdk/js/identity/defaultazurecredential/troubleshoot.\";\n }\n}\n"]}
1
+ {"version":3,"file":"defaultAzureCredential.js","sourceRoot":"","sources":["../../../src/credentials/defaultAzureCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EACL,yBAAyB,GAE1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAsD1E;;;;;GAKG;AACH,MAAM,OAAO,gCAAiC,SAAQ,yBAAyB;IAC7E,YAAY,OAAuC;;QACjD,MAAM,uBAAuB,GAC3B,MAAA,MAAC,OAAiD,0CAAE,uBAAuB,mCAC3E,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC;QAC9B,MAAM,iBAAiB,GAAG,MAAC,OAAuD,0CAC9E,yBAAyB,CAAC;QAE9B,yFAAyF;QACzF,MAAM,sBAAsB,mBAC1B,UAAU,EAAE,iBAAiB,EAC7B,QAAQ,EAAE,uBAAuB,IAC9B,OAAO,CACX,CAAC;QAEF,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAChC,CAAC;CACF;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAmC;IAChE,qBAAqB;IACrB,gCAAgC;IAChC,0BAA0B;IAC1B,kBAAkB;IAClB,yBAAyB;CAC1B,CAAC;AAEF;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,sBAAsB;IAChE;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,YAAY,OAAuC;QACjD,KAAK,CAAC,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QAC9D,IAAI,CAAC,kBAAkB;YACrB,kLAAkL,CAAC;IACvL,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TokenCredential } from \"@azure/core-auth\";\n\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\n\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\n\nimport { AzureCliCredential } from \"./azureCliCredential\";\nimport { AzurePowerShellCredential } from \"./azurePowerShellCredential\";\nimport { EnvironmentCredential } from \"./environmentCredential\";\nimport {\n ManagedIdentityCredential,\n ManagedIdentityCredentialOptions,\n} from \"./managedIdentityCredential\";\nimport { VisualStudioCodeCredential } from \"./visualStudioCodeCredential\";\n\n/**\n * Provides options to configure the {@link DefaultAzureCredential} class.\n * This variation supports `managedIdentityClientId` and not `managedIdentityResourceId`, since only one of both is supported.\n */\nexport interface DefaultAzureCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * Optionally pass in a Tenant ID to be used as part of the credential.\n * By default it may use a generic tenant ID depending on the underlying credential.\n */\n tenantId?: string;\n /**\n * Optionally pass in a user assigned client ID to be used by the {@link ManagedIdentityCredential}.\n * This client ID can also be passed through to the {@link ManagedIdentityCredential} through the environment variable: AZURE_CLIENT_ID.\n */\n managedIdentityClientId?: string;\n}\n\n/**\n * Provides options to configure the {@link DefaultAzureCredential} class.\n * This variation supports `managedIdentityResourceId` and not `managedIdentityClientId`, since only one of both is supported.\n */\nexport interface DefaultAzureCredentialOptionsWithResourceId extends TokenCredentialOptions {\n /**\n * Optionally pass in a Tenant ID to be used as part of the credential.\n * By default it may use a generic tenant ID depending on the underlying credential.\n */\n tenantId?: string;\n /**\n * Optionally pass in a resource ID to be used by the {@link ManagedIdentityCredential}.\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 managedIdentityResourceId?: string;\n}\n\n/**\n * Provides options to configure the {@link DefaultAzureCredential} class.\n */\nexport type DefaultAzureCredentialOptions =\n | DefaultAzureCredentialClientIdOptions\n | DefaultAzureCredentialOptionsWithResourceId;\n\n/**\n * The type of a class that implements TokenCredential and accepts\n * `DefaultAzureCredentialOptions`.\n */\ninterface DefaultCredentialConstructor {\n new (options?: DefaultAzureCredentialOptions): TokenCredential;\n}\n\n/**\n * A shim around ManagedIdentityCredential that adapts it to accept\n * `DefaultAzureCredentialOptions`.\n *\n * @internal\n */\nexport class DefaultManagedIdentityCredential extends ManagedIdentityCredential {\n constructor(options?: DefaultAzureCredentialOptions) {\n const managedIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.managedIdentityClientId ??\n process.env.AZURE_CLIENT_ID;\n const managedResourceId = (options as DefaultAzureCredentialOptionsWithResourceId)\n ?.managedIdentityResourceId;\n\n // ManagedIdentityCredential throws if both the resourceId and the clientId are provided.\n const managedIdentityOptions: ManagedIdentityCredentialOptions = {\n resourceId: managedResourceId,\n clientId: managedIdentityClientId,\n ...options,\n };\n\n super(managedIdentityOptions);\n }\n}\n\nexport const defaultCredentials: DefaultCredentialConstructor[] = [\n EnvironmentCredential,\n DefaultManagedIdentityCredential,\n VisualStudioCodeCredential,\n AzureCliCredential,\n AzurePowerShellCredential,\n];\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n */\nexport class DefaultAzureCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the DefaultAzureCredential class.\n *\n * This credential provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n *\n * The following credential types will be tried, in order:\n *\n * - {@link EnvironmentCredential}\n * - {@link ManagedIdentityCredential}\n * - {@link VisualStudioCodeCredential}\n * - {@link AzureCliCredential}\n * - {@link AzurePowerShellCredential}\n *\n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n *\n * **Note**: `VisualStudioCodeCredential` is provided by a plugin package:\n * `@azure/identity-vscode`. If this package is not installed and registered\n * using the plugin API (`useIdentityPlugin`), then authentication using\n * `VisualStudioCodeCredential` will not be available.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialOptions}.\n */\n constructor(options?: DefaultAzureCredentialOptions) {\n super(...defaultCredentials.map((ctor) => new ctor(options)));\n this.UnavailableMessage =\n \"DefaultAzureCredential => failed to retrieve a token from the included credentials. To troubleshoot, visit https://aka.ms/azsdk/js/identity/defaultazurecredential/troubleshoot.\";\n }\n}\n"]}
@@ -48,7 +48,7 @@ function prepareRequestOptions(scopes, clientId) {
48
48
  * 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.
49
49
  */
50
50
  export const appServiceMsi2017 = {
51
- async isAvailable(scopes) {
51
+ async isAvailable({ scopes }) {
52
52
  const resource = mapScopesToResource(scopes);
53
53
  if (!resource) {
54
54
  logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
@@ -62,7 +62,10 @@ export const appServiceMsi2017 = {
62
62
  return result;
63
63
  },
64
64
  async getToken(configuration, getTokenOptions = {}) {
65
- const { identityClient, scopes, clientId } = configuration;
65
+ const { identityClient, scopes, clientId, resourceId } = configuration;
66
+ if (resourceId) {
67
+ logger.warning(`${msiName}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
68
+ }
66
69
  logger.info(`${msiName}: Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`);
67
70
  const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId)), {
68
71
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
@@ -1 +1 @@
1
- {"version":3,"file":"appServiceMsi2017.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/appServiceMsi2017.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,OAAO,GAAG,gDAAgD,CAAC;AACjE,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,SAAS,eAAe,CAAC,WAAoC;IAC3D,uDAAuD;IACvD,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,UAAqB,CA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KAAK,CAAC;SACd;QACD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACxB,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;QAC3D,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,mFAAmF,CAC9F,CAAC;SACH;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,KAAK,CAAC,QAAQ,CACZ,aAA+B,EAC/B,kBAAmC,EAAE;QAErC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,aAAa,CAAC;QAE3D,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,2FAA2F,OAAO,CAAC,GAAG,CAAC,YAAY,6BAA6B,CAC3J,CAAC;QAEF,MAAM,OAAO,GAAG,qBAAqB,+BACnC,WAAW,EAAE,eAAe,CAAC,WAAW,IACrC,qBAAqB,CAAC,MAAM,EAAE,QAAQ,CAAC;YAC1C,0FAA0F;YAC1F,uBAAuB,EAAE,IAAI,IAC7B,CAAC;QACH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QACtF,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;IAC9D,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequestOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { TokenResponseParsedBody } from \"../../client/identityClient\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\n\nconst msiName = \"ManagedIdentityCredential - AppServiceMSI 2017\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.\n */\nfunction expiresOnParser(requestBody: TokenResponseParsedBody): number {\n // App Service always returns string expires_on values.\n return Date.parse(requestBody.expires_on! as string);\n}\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): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": \"2017-09-01\",\n };\n\n if (clientId) {\n queryParameters.clientid = clientId;\n }\n\n const query = new URLSearchParams(queryParameters);\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.MSI_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);\n }\n if (!process.env.MSI_SECRET) {\n throw new Error(`${msiName}: Missing environment variable: MSI_SECRET`);\n }\n\n return {\n url: `${process.env.MSI_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n secret: process.env.MSI_SECRET,\n }),\n };\n}\n\n/**\n * 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.\n */\nexport const appServiceMsi2017: MSI = {\n async isAvailable(scopes): 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 const env = process.env;\n const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { identityClient, scopes, clientId } = configuration;\n\n logger.info(\n `${msiName}: Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId),\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n"]}
1
+ {"version":3,"file":"appServiceMsi2017.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/appServiceMsi2017.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,OAAO,GAAG,gDAAgD,CAAC;AACjE,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,SAAS,eAAe,CAAC,WAAoC;IAC3D,uDAAuD;IACvD,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,UAAqB,CAAC,CAAC;AACvD,CAAC;AAED;;GAEG;AACH,SAAS,qBAAqB,CAC5B,MAAyB,EACzB,QAAiB;IAEjB,MAAM,QAAQ,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,sCAAsC,CAAC,CAAC;KACnE;IAED,MAAM,eAAe,GAA2B;QAC9C,QAAQ;QACR,aAAa,EAAE,YAAY;KAC5B,CAAC;IAEF,IAAI,QAAQ,EAAE;QACZ,eAAe,CAAC,QAAQ,GAAG,QAAQ,CAAC;KACrC;IAED,MAAM,KAAK,GAAG,IAAI,eAAe,CAAC,eAAe,CAAC,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;QAEvE,IAAI,UAAU,EAAE;YACd,MAAM,CAAC,OAAO,CACZ,GAAG,OAAO,0GAA0G,CACrH,CAAC;SACH;QAED,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,2FAA2F,OAAO,CAAC,GAAG,CAAC,YAAY,6BAA6B,CAC3J,CAAC;QAEF,MAAM,OAAO,GAAG,qBAAqB,+BACnC,WAAW,EAAE,eAAe,CAAC,WAAW,IACrC,qBAAqB,CAAC,MAAM,EAAE,QAAQ,CAAC;YAC1C,0FAA0F;YAC1F,uBAAuB,EAAE,IAAI,IAC7B,CAAC;QACH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QACtF,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;IAC9D,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequestOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { TokenResponseParsedBody } from \"../../client/identityClient\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\n\nconst msiName = \"ManagedIdentityCredential - AppServiceMSI 2017\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.\n */\nfunction expiresOnParser(requestBody: TokenResponseParsedBody): number {\n // App Service always returns string expires_on values.\n return Date.parse(requestBody.expires_on! as string);\n}\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): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": \"2017-09-01\",\n };\n\n if (clientId) {\n queryParameters.clientid = clientId;\n }\n\n const query = new URLSearchParams(queryParameters);\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.MSI_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);\n }\n if (!process.env.MSI_SECRET) {\n throw new Error(`${msiName}: Missing environment variable: MSI_SECRET`);\n }\n\n return {\n url: `${process.env.MSI_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n secret: process.env.MSI_SECRET,\n }),\n };\n}\n\n/**\n * 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.\n */\nexport const appServiceMsi2017: MSI = {\n async isAvailable({ scopes }): 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 const env = process.env;\n const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (resourceId) {\n logger.warning(\n `${msiName}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`\n );\n }\n\n logger.info(\n `${msiName}: Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId),\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n"]}
@@ -11,7 +11,7 @@ const logger = credentialLogger(msiName);
11
11
  /**
12
12
  * Generates the options used on the request for an access token.
13
13
  */
14
- function prepareRequestOptions(scopes) {
14
+ function prepareRequestOptions(scopes, clientId, resourceId) {
15
15
  const resource = mapScopesToResource(scopes);
16
16
  if (!resource) {
17
17
  throw new Error(`${msiName}: Multiple scopes are not supported.`);
@@ -20,11 +20,17 @@ function prepareRequestOptions(scopes) {
20
20
  resource,
21
21
  "api-version": azureArcAPIVersion,
22
22
  };
23
- const query = new URLSearchParams(queryParameters);
23
+ if (clientId) {
24
+ queryParameters.client_id = clientId;
25
+ }
26
+ if (resourceId) {
27
+ queryParameters.msi_res_id = resourceId;
28
+ }
24
29
  // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
25
30
  if (!process.env.IDENTITY_ENDPOINT) {
26
31
  throw new Error(`${msiName}: Missing environment variable: IDENTITY_ENDPOINT`);
27
32
  }
33
+ const query = new URLSearchParams(queryParameters);
28
34
  return createPipelineRequest({
29
35
  // Should be similar to: http://localhost:40342/metadata/identity/oauth2/token
30
36
  url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,
@@ -71,7 +77,7 @@ async function filePathRequest(identityClient, requestPrepareOptions) {
71
77
  * Defines how to determine whether the Azure Arc MSI is available, and also how to retrieve a token from the Azure Arc MSI.
72
78
  */
73
79
  export const arcMsi = {
74
- async isAvailable(scopes) {
80
+ async isAvailable({ scopes }) {
75
81
  const resource = mapScopesToResource(scopes);
76
82
  if (!resource) {
77
83
  logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
@@ -85,12 +91,15 @@ export const arcMsi = {
85
91
  },
86
92
  async getToken(configuration, getTokenOptions = {}) {
87
93
  var _a;
88
- const { identityClient, scopes, clientId } = configuration;
89
- logger.info(`${msiName}: Authenticating.`);
94
+ const { identityClient, scopes, clientId, resourceId } = configuration;
90
95
  if (clientId) {
91
- throw new Error(`${msiName}: User assigned identity is not supported by the Azure Arc Managed Identity Endpoint. To authenticate with the system assigned identity, omit the client id when constructing the ManagedIdentityCredential, or if authenticating with the DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set.`);
96
+ logger.warning(`${msiName}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
97
+ }
98
+ if (resourceId) {
99
+ logger.warning(`${msiName}: user defined managed Identity by resource Id is not supported. Argument resourceId will be ignored.`);
92
100
  }
93
- const requestOptions = Object.assign(Object.assign({ disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes)), { allowInsecureConnection: true });
101
+ logger.info(`${msiName}: Authenticating.`);
102
+ const requestOptions = Object.assign(Object.assign({ disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)), { allowInsecureConnection: true });
94
103
  const filePath = await filePathRequest(identityClient, requestOptions);
95
104
  if (!filePath) {
96
105
  throw new Error(`${msiName}: Failed to find the token file.`);
@@ -1 +1 @@
1
- {"version":3,"file":"arcMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/arcMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAC9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAE9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM,OAAO,GAAG,2CAA2C,CAAC;AAC5D,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,S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E,QAAQ,EAAE,GAAG,aAAa,CAAC;QAE3D,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,mBAAmB,CAAC,CAAC;QAE3C,IAAI,QAAQ,EAAE;YACZ,MAAM,IAAI,KAAK,CACb,GAAG,OAAO,+TAA+T,CAC1U,CAAC;SACH;QAED,MAAM,cAAc,iCAClB,0BAA0B,EAAE,IAAI,EAChC,qBAAqB,EAAE,SAAS,EAChC,WAAW,EAAE,eAAe,CAAC,WAAW,IACrC,qBAAqB,CAAC,MAAM,CAAC,KAChC,uBAAuB,EAAE,IAAI,GAC9B,CAAC;QAEF,MAAM,QAAQ,GAAG,MAAM,eAAe,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;QAEvE,IAAI,CAAC,QAAQ,EAAE;YACb,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,kCAAkC,CAAC,CAAC;SAC/D;QAED,MAAM,GAAG,GAAG,MAAM,aAAa,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;QACjE,MAAA,cAAc,CAAC,OAAO,0CAAE,GAAG,CAAC,eAAe,EAAE,SAAS,GAAG,EAAE,CAAC,CAAC;QAE7D,MAAM,OAAO,GAAG,qBAAqB,iCAChC,cAAc;YACjB,0FAA0F;YAC1F,uBAAuB,EAAE,IAAI,IAC7B,CAAC;QACH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACrE,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;IAC9D,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequestOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { readFile } from \"fs\";\nimport { AuthenticationError } from \"../../errors\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { mapScopesToResource } from \"./utils\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { azureArcAPIVersion } from \"./constants\";\n\nconst msiName = \"ManagedIdentityCredential - Azure Arc MSI\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(scopes: string | string[]): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": azureArcAPIVersion,\n };\n\n const query = new URLSearchParams(queryParameters);\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.IDENTITY_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: IDENTITY_ENDPOINT`);\n }\n\n return createPipelineRequest({\n // Should be similar to: http://localhost:40342/metadata/identity/oauth2/token\n url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n Metadata: \"true\",\n }),\n });\n}\n\n/**\n * Retrieves the file contents at the given path using promises.\n * Useful since `fs`'s readFileSync locks the thread, and to avoid extra dependencies.\n */\nfunction readFileAsync(path: string, options: { encoding: string }): Promise<string> {\n return new Promise((resolve, reject) =>\n readFile(path, options, (err, data) => {\n if (err) {\n reject(err);\n }\n resolve(data);\n })\n );\n}\n\n/**\n * Does a request to the authentication provider that results in a file path.\n */\nasync function filePathRequest(\n identityClient: IdentityClient,\n requestPrepareOptions: PipelineRequestOptions\n): Promise<string | undefined> {\n const response = await identityClient.sendRequest(createPipelineRequest(requestPrepareOptions));\n\n if (response.status !== 401) {\n let message = \"\";\n if (response.bodyAsText) {\n message = ` Response: ${response.bodyAsText}`;\n }\n throw new AuthenticationError(\n response.status,\n `${msiName}: To authenticate with Azure Arc MSI, status code 401 is expected on the first request. ${message}`\n );\n }\n\n const authHeader = response.headers.get(\"www-authenticate\") || \"\";\n try {\n return authHeader.split(\"=\").slice(1)[0];\n } catch (e) {\n throw Error(`Invalid www-authenticate header format: ${authHeader}`);\n }\n}\n\n/**\n * Defines how to determine whether the Azure Arc MSI is available, and also how to retrieve a token from the Azure Arc MSI.\n */\nexport const arcMsi: MSI = {\n async isAvailable(scopes): 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 const result = Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);\n if (!result) {\n logger.info(\n `${msiName}: The environment variables needed are: IMDS_ENDPOINT and IDENTITY_ENDPOINT`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { identityClient, scopes, clientId } = configuration;\n\n logger.info(`${msiName}: Authenticating.`);\n\n if (clientId) {\n throw new Error(\n `${msiName}: User assigned identity is not supported by the Azure Arc Managed Identity Endpoint. To authenticate with the system assigned identity, omit the client id when constructing the ManagedIdentityCredential, or if authenticating with the DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set.`\n );\n }\n\n const requestOptions = {\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes),\n allowInsecureConnection: true,\n };\n\n const filePath = await filePathRequest(identityClient, requestOptions);\n\n if (!filePath) {\n throw new Error(`${msiName}: Failed to find the token file.`);\n }\n\n const key = await readFileAsync(filePath, { encoding: \"utf-8\" });\n requestOptions.headers?.set(\"Authorization\", `Basic ${key}`);\n\n const request = createPipelineRequest({\n ...requestOptions,\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n"]}
1
+ {"version":3,"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C;QAEF,MAAM,QAAQ,GAAG,MAAM,eAAe,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;QAEvE,IAAI,CAAC,QAAQ,EAAE;YACb,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,kCAAkC,CAAC,CAAC;SAC/D;QAED,MAAM,GAAG,GAAG,MAAM,aAAa,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;QACjE,MAAA,cAAc,CAAC,OAAO,0CAAE,GAAG,CAAC,eAAe,EAAE,SAAS,GAAG,EAAE,CAAC,CAAC;QAE7D,MAAM,OAAO,GAAG,qBAAqB,iCAChC,cAAc;YACjB,0FAA0F;YAC1F,uBAAuB,EAAE,IAAI,IAC7B,CAAC;QACH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACrE,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;IAC9D,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequestOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { readFile } from \"fs\";\nimport { AuthenticationError } from \"../../errors\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { mapScopesToResource } from \"./utils\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { azureArcAPIVersion } from \"./constants\";\n\nconst msiName = \"ManagedIdentityCredential - Azure Arc MSI\";\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): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": azureArcAPIVersion,\n };\n\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.IDENTITY_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: IDENTITY_ENDPOINT`);\n }\n\n const query = new URLSearchParams(queryParameters);\n\n return createPipelineRequest({\n // Should be similar to: http://localhost:40342/metadata/identity/oauth2/token\n url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n Metadata: \"true\",\n }),\n });\n}\n\n/**\n * Retrieves the file contents at the given path using promises.\n * Useful since `fs`'s readFileSync locks the thread, and to avoid extra dependencies.\n */\nfunction readFileAsync(path: string, options: { encoding: string }): Promise<string> {\n return new Promise((resolve, reject) =>\n readFile(path, options, (err, data) => {\n if (err) {\n reject(err);\n }\n resolve(data);\n })\n );\n}\n\n/**\n * Does a request to the authentication provider that results in a file path.\n */\nasync function filePathRequest(\n identityClient: IdentityClient,\n requestPrepareOptions: PipelineRequestOptions\n): Promise<string | undefined> {\n const response = await identityClient.sendRequest(createPipelineRequest(requestPrepareOptions));\n\n if (response.status !== 401) {\n let message = \"\";\n if (response.bodyAsText) {\n message = ` Response: ${response.bodyAsText}`;\n }\n throw new AuthenticationError(\n response.status,\n `${msiName}: To authenticate with Azure Arc MSI, status code 401 is expected on the first request. ${message}`\n );\n }\n\n const authHeader = response.headers.get(\"www-authenticate\") || \"\";\n try {\n return authHeader.split(\"=\").slice(1)[0];\n } catch (e) {\n throw Error(`Invalid www-authenticate header format: ${authHeader}`);\n }\n}\n\n/**\n * Defines how to determine whether the Azure Arc MSI is available, and also how to retrieve a token from the Azure Arc MSI.\n */\nexport const arcMsi: MSI = {\n async isAvailable({ scopes }): 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 const result = Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);\n if (!result) {\n logger.info(\n `${msiName}: The environment variables needed are: IMDS_ENDPOINT and IDENTITY_ENDPOINT`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (clientId) {\n logger.warning(\n `${msiName}: user-assigned identities not supported. The argument clientId might be ignored by the service.`\n );\n }\n if (resourceId) {\n logger.warning(\n `${msiName}: user defined managed Identity by resource Id is not supported. Argument resourceId will be ignored.`\n );\n }\n\n logger.info(`${msiName}: Authenticating.`);\n\n const requestOptions = {\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n allowInsecureConnection: true,\n };\n\n const filePath = await filePathRequest(identityClient, requestOptions);\n\n if (!filePath) {\n throw new Error(`${msiName}: Failed to find the token file.`);\n }\n\n const key = await readFileAsync(filePath, { encoding: \"utf-8\" });\n requestOptions.headers?.set(\"Authorization\", `Basic ${key}`);\n\n const request = createPipelineRequest({\n ...requestOptions,\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n"]}
@@ -8,7 +8,7 @@ export const logger = credentialLogger(msiName);
8
8
  /**
9
9
  * Generates the options used on the request for an access token.
10
10
  */
11
- function prepareRequestOptions(scopes, clientId) {
11
+ function prepareRequestOptions(scopes, clientId, resourceId) {
12
12
  const resource = mapScopesToResource(scopes);
13
13
  if (!resource) {
14
14
  throw new Error(`${msiName}: Multiple scopes are not supported.`);
@@ -19,6 +19,9 @@ function prepareRequestOptions(scopes, clientId) {
19
19
  if (clientId) {
20
20
  body.client_id = clientId;
21
21
  }
22
+ if (resourceId) {
23
+ body.msi_res_id = resourceId;
24
+ }
22
25
  // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
23
26
  if (!process.env.MSI_ENDPOINT) {
24
27
  throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);
@@ -40,7 +43,7 @@ function prepareRequestOptions(scopes, clientId) {
40
43
  * Since Azure Managed Identities aren't available in the Azure Cloud Shell, we log a warning for users that try to access cloud shell using user assigned identity.
41
44
  */
42
45
  export const cloudShellMsi = {
43
- async isAvailable(scopes) {
46
+ async isAvailable({ scopes }) {
44
47
  const resource = mapScopesToResource(scopes);
45
48
  if (!resource) {
46
49
  logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
@@ -53,12 +56,15 @@ export const cloudShellMsi = {
53
56
  return result;
54
57
  },
55
58
  async getToken(configuration, getTokenOptions = {}) {
56
- const { identityClient, scopes, clientId } = configuration;
59
+ const { identityClient, scopes, clientId, resourceId } = configuration;
57
60
  if (clientId) {
58
- logger.warning(`${msiName}: does not support user-assigned identities in the Cloud Shell environment. Argument clientId will be ignored.`);
61
+ logger.warning(`${msiName}: user-assigned identities not supported. The argument clientId might be ignored by the service.`);
62
+ }
63
+ if (resourceId) {
64
+ logger.warning(`${msiName}: user defined managed Identity by resource Id not supported. The argument resourceId might be ignored by the service.`);
59
65
  }
60
66
  logger.info(`${msiName}: Using the endpoint coming form the environment variable MSI_ENDPOINT = ${process.env.MSI_ENDPOINT}.`);
61
- const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId)), {
67
+ const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)), {
62
68
  // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).
63
69
  allowInsecureConnection: true }));
64
70
  const tokenResponse = await identityClient.sendTokenRequest(request);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\n PipelineRequestOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\n\nconst msiName = \"ManagedIdentityCredential - CloudShellMSI\";\nexport const 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): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const body: Record<string, string> = {\n resource,\n };\n\n if (clientId) {\n body.client_id = clientId;\n }\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.MSI_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);\n }\n const params = new URLSearchParams(body);\n return {\n url: process.env.MSI_ENDPOINT,\n method: \"POST\",\n body: params.toString(),\n headers: createHttpHeaders({\n Accept: \"application/json\",\n Metadata: \"true\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n };\n}\n\n/**\n * Defines how to determine whether the Azure Cloud Shell MSI is available, and also how to retrieve a token from the Azure Cloud Shell MSI.\n * Since Azure Managed Identities aren't available in the Azure Cloud Shell, we log a warning for users that try to access cloud shell using user assigned identity.\n */\nexport const cloudShellMsi: MSI = {\n async isAvailable(scopes): 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 const result = Boolean(process.env.MSI_ENDPOINT);\n if (!result) {\n logger.info(`${msiName}: Unavailable. The environment variable MSI_ENDPOINT is needed.`);\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { identityClient, scopes, clientId } = configuration;\n\n if (clientId) {\n logger.warning(\n `${msiName}: does not support user-assigned identities in the Cloud Shell environment. Argument clientId will be ignored.`\n );\n }\n logger.info(\n `${msiName}: Using the endpoint coming form the environment variable MSI_ENDPOINT = ${process.env.MSI_ENDPOINT}.`\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId),\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n"]}
1
+ {"version":3,"file":"cloudShellMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/cloudShellMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,OAAO,GAAG,2CAA2C,CAAC;AAC5D,MAAM,CAAC,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEhD;;GAEG;AACH,SAAS,qBAAqB,CAC5B,MAAyB,EACzB,QAAiB,EACjB,UAAmB;IAEnB,MAAM,QAAQ,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,sCAAsC,CAAC,CAAC;KACnE;IAED,MAAM,IAAI,GAA2B;QACnC,QAAQ;KACT,CAAC;IAEF,IAAI,QAAQ,EAAE;QACZ,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;KAC3B;IACD,IAAI,UAAU,EAAE;QACd,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;KAC9B;IAED,wIAAwI;IACxI,IAAI,CAAC,O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wHAAwH,CACnI,CAAC;SACH;QAED,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,4EAA4E,OAAO,CAAC,GAAG,CAAC,YAAY,GAAG,CAClH,CAAC;QAEF,MAAM,OAAO,GAAG,qBAAqB,+BACnC,WAAW,EAAE,eAAe,CAAC,WAAW,IACrC,qBAAqB,CAAC,MAAM,EAAE,QAAQ,EAAE,UAAU,CAAC;YACtD,0FAA0F;YAC1F,uBAAuB,EAAE,IAAI,IAC7B,CAAC;QACH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACrE,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;IAC9D,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequestOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\n\nconst msiName = \"ManagedIdentityCredential - CloudShellMSI\";\nexport const 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): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const body: Record<string, string> = {\n resource,\n };\n\n if (clientId) {\n body.client_id = clientId;\n }\n if (resourceId) {\n body.msi_res_id = resourceId;\n }\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.MSI_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);\n }\n const params = new URLSearchParams(body);\n return {\n url: process.env.MSI_ENDPOINT,\n method: \"POST\",\n body: params.toString(),\n headers: createHttpHeaders({\n Accept: \"application/json\",\n Metadata: \"true\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n };\n}\n\n/**\n * Defines how to determine whether the Azure Cloud Shell MSI is available, and also how to retrieve a token from the Azure Cloud Shell MSI.\n * Since Azure Managed Identities aren't available in the Azure Cloud Shell, we log a warning for users that try to access cloud shell using user assigned identity.\n */\nexport const cloudShellMsi: MSI = {\n async isAvailable({ scopes }): 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 const result = Boolean(process.env.MSI_ENDPOINT);\n if (!result) {\n logger.info(`${msiName}: Unavailable. The environment variable MSI_ENDPOINT is needed.`);\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (clientId) {\n logger.warning(\n `${msiName}: user-assigned identities not supported. The argument clientId might be ignored by the service.`\n );\n }\n\n if (resourceId) {\n logger.warning(\n `${msiName}: user defined managed Identity by resource Id not supported. The argument resourceId might be ignored by the service.`\n );\n }\n\n logger.info(\n `${msiName}: Using the endpoint coming form the environment variable MSI_ENDPOINT = ${process.env.MSI_ENDPOINT}.`\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n"]}
@@ -27,7 +27,7 @@ function expiresOnParser(requestBody) {
27
27
  /**
28
28
  * Generates the options used on the request for an access token.
29
29
  */
30
- function prepareRequestOptions(scopes, clientId) {
30
+ function prepareRequestOptions(scopes, clientId, resourceId) {
31
31
  const resource = mapScopesToResource(scopes);
32
32
  if (!resource) {
33
33
  throw new Error(`${msiName}: Multiple scopes are not supported.`);
@@ -39,6 +39,9 @@ function prepareRequestOptions(scopes, clientId) {
39
39
  if (clientId) {
40
40
  queryParameters.client_id = clientId;
41
41
  }
42
+ if (resourceId) {
43
+ queryParameters.msi_res_id = resourceId;
44
+ }
42
45
  const query = new URLSearchParams(queryParameters);
43
46
  // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.
44
47
  if (!process.env.IDENTITY_ENDPOINT) {
@@ -60,7 +63,7 @@ function prepareRequestOptions(scopes, clientId) {
60
63
  * Defines how to determine whether the Azure Service Fabric MSI is available, and also how to retrieve a token from the Azure Service Fabric MSI.
61
64
  */
62
65
  export const fabricMsi = {
63
- async isAvailable(scopes) {
66
+ async isAvailable({ scopes }) {
64
67
  const resource = mapScopesToResource(scopes);
65
68
  if (!resource) {
66
69
  logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);
@@ -74,7 +77,10 @@ export const fabricMsi = {
74
77
  return result;
75
78
  },
76
79
  async getToken(configuration, getTokenOptions = {}) {
77
- const { scopes, identityClient, clientId } = configuration;
80
+ const { scopes, identityClient, clientId, resourceId } = configuration;
81
+ if (resourceId) {
82
+ logger.warning(`${msiName}: user defined managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`);
83
+ }
78
84
  logger.info([
79
85
  `${msiName}:`,
80
86
  "Using the endpoint and the secret coming from the environment variables:",
@@ -82,7 +88,7 @@ export const fabricMsi = {
82
88
  "IDENTITY_HEADER=[REDACTED] and",
83
89
  "IDENTITY_SERVER_THUMBPRINT=[REDACTED].",
84
90
  ].join(" "));
85
- const request = createPipelineRequest(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId)));
91
+ const request = createPipelineRequest(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)));
86
92
  request.agent = new https.Agent({
87
93
  // This is necessary because Service Fabric provides a self-signed certificate.
88
94
  // The alternative path is to verify the certificate using the IDENTITY_SERVER_THUMBPRINT env variable.
@@ -1 +1 @@
1
- {"version":3,"file":"fabricMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/fabricMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,sGAAsG;AACtG,EAAE;AACF,iBAAiB;AACjB,2CAA2C;AAC3C,4BAA4B;AAC5B,EAAE;AACF,kCAAkC;AAClC,EAAE;AACF,wIAAwI;AACxI,EAAE;AAEF,MAAM,OAAO,GAAG,wCAAwC,CAAC;AACzD,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,SAAS,eAAe,CAAC,WAAoC;IAC3D,qFAAqF;IACrF,OAAO,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;AACxC,CAAC;AAED;;GAEG;AACH,SAAS,qBAAqB,CAC5B,MAAyB,EACzB,QAAiB;IAEjB,MAAM,QAAQ,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,sCAAsC,CAAC,CAAC;KACnE;IAED,MAAM,eAAe,GAA2B;QAC9C,QAAQ;QACR,aAAa,EAAE,kBAAkB;KAClC,CAAC;IAEF,IAAI,QAAQ,EAAE;QACZ,eAAe,CAAC,SAAS,GAAG,QAAQ,CAAC;KACtC;IAED,MAAM,KAAK,GAAG,IAAI,eAAe,CAAC,eAAe,CAAC,CAAC;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T;YACE,GAAG,OAAO,GAAG;YACb,0EAA0E;YAC1E,qBAAqB,OAAO,CAAC,GAAG,CAAC,iBAAiB,GAAG;YACrD,gCAAgC;YAChC,wCAAwC;SACzC,CAAC,IAAI,CAAC,GAAG,CAAC,CACZ,CAAC;QAEF,MAAM,OAAO,GAAG,qBAAqB,iBACnC,WAAW,EAAE,eAAe,CAAC,WAAW,IACrC,qBAAqB,CAAC,MAAM,EAAE,QAAQ,CAAC,EAG1C,CAAC;QAEH,OAAO,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC;YAC9B,+EAA+E;YAC/E,uGAAuG;YACvG,kBAAkB,EAAE,KAAK;SAC1B,CAAC,CAAC;QAEH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QACtF,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;IAC9D,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport https from \"https\";\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequestOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { TokenResponseParsedBody } from \"../../client/identityClient\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\nimport { azureFabricVersion } from \"./constants\";\n\n// This MSI can be easily tested by deploying a container to Azure Service Fabric with the Dockerfile:\n//\n// FROM node:12\n// RUN wget https://host.any/path/bash.sh\n// CMD [\"bash\", \"bash.sh\"]\n//\n// Where the bash script contains:\n//\n// curl --insecure $IDENTITY_ENDPOINT'?api-version=2019-07-01-preview&resource=https://vault.azure.net/' -H \"Secret: $IDENTITY_HEADER\"\n//\n\nconst msiName = \"ManagedIdentityCredential - Fabric MSI\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.\n */\nfunction expiresOnParser(requestBody: TokenResponseParsedBody): number {\n // Parses a string representation of the milliseconds since epoch into a number value\n return Number(requestBody.expires_on);\n}\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): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": azureFabricVersion,\n };\n\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n\n const query = new URLSearchParams(queryParameters);\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.IDENTITY_ENDPOINT) {\n throw new Error(\"Missing environment variable: IDENTITY_ENDPOINT\");\n }\n if (!process.env.IDENTITY_HEADER) {\n throw new Error(\"Missing environment variable: IDENTITY_HEADER\");\n }\n\n return {\n url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n secret: process.env.IDENTITY_HEADER,\n }),\n };\n}\n\n/**\n * Defines how to determine whether the Azure Service Fabric MSI is available, and also how to retrieve a token from the Azure Service Fabric MSI.\n */\nexport const fabricMsi: MSI = {\n async isAvailable(scopes): 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 const env = process.env;\n const result = Boolean(\n env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER && env.IDENTITY_SERVER_THUMBPRINT\n );\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT, IDENTITY_HEADER and IDENTITY_SERVER_THUMBPRINT`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { scopes, identityClient, clientId } = configuration;\n\n logger.info(\n [\n `${msiName}:`,\n \"Using the endpoint and the secret coming from the environment variables:\",\n `IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT},`,\n \"IDENTITY_HEADER=[REDACTED] and\",\n \"IDENTITY_SERVER_THUMBPRINT=[REDACTED].\",\n ].join(\" \")\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId),\n // The service fabric MSI endpoint will be HTTPS (however, the certificate will be self-signed).\n // allowInsecureConnection: true\n });\n\n request.agent = new https.Agent({\n // This is necessary because Service Fabric provides a self-signed certificate.\n // The alternative path is to verify the certificate using the IDENTITY_SERVER_THUMBPRINT env variable.\n rejectUnauthorized: false,\n });\n\n const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n"]}
1
+ {"version":3,"file":"fabricMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/fabricMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,sGAAsG;AACtG,EAAE;AACF,iBAAiB;AACjB,2CAA2C;AAC3C,4BAA4B;AAC5B,EAAE;AACF,kCAAkC;AAClC,EAAE;AACF,wIAAwI;AACxI,EAAE;AAEF,MAAM,OAAO,GAAG,wCAAwC,CAAC;AACzD,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,SAAS,eAAe,CA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,eAAe,CAAC,CAAC;QACtF,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;IAC9D,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport https from \"https\";\nimport {\n createHttpHeaders,\n createPipelineRequest,\n PipelineRequestOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { TokenResponseParsedBody } from \"../../client/identityClient\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\nimport { azureFabricVersion } from \"./constants\";\n\n// This MSI can be easily tested by deploying a container to Azure Service Fabric with the Dockerfile:\n//\n// FROM node:12\n// RUN wget https://host.any/path/bash.sh\n// CMD [\"bash\", \"bash.sh\"]\n//\n// Where the bash script contains:\n//\n// curl --insecure $IDENTITY_ENDPOINT'?api-version=2019-07-01-preview&resource=https://vault.azure.net/' -H \"Secret: $IDENTITY_HEADER\"\n//\n\nconst msiName = \"ManagedIdentityCredential - Fabric MSI\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Formats the expiration date of the received token into the number of milliseconds between that date and midnight, January 1, 1970.\n */\nfunction expiresOnParser(requestBody: TokenResponseParsedBody): number {\n // Parses a string representation of the milliseconds since epoch into a number value\n return Number(requestBody.expires_on);\n}\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): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": azureFabricVersion,\n };\n\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const query = new URLSearchParams(queryParameters);\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.IDENTITY_ENDPOINT) {\n throw new Error(\"Missing environment variable: IDENTITY_ENDPOINT\");\n }\n if (!process.env.IDENTITY_HEADER) {\n throw new Error(\"Missing environment variable: IDENTITY_HEADER\");\n }\n\n return {\n url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n secret: process.env.IDENTITY_HEADER,\n }),\n };\n}\n\n/**\n * Defines how to determine whether the Azure Service Fabric MSI is available, and also how to retrieve a token from the Azure Service Fabric MSI.\n */\nexport const fabricMsi: MSI = {\n async isAvailable({ scopes }): 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 const env = process.env;\n const result = Boolean(\n env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER && env.IDENTITY_SERVER_THUMBPRINT\n );\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT, IDENTITY_HEADER and IDENTITY_SERVER_THUMBPRINT`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { scopes, identityClient, clientId, resourceId } = configuration;\n\n if (resourceId) {\n logger.warning(\n `${msiName}: user defined managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`\n );\n }\n\n logger.info(\n [\n `${msiName}:`,\n \"Using the endpoint and the secret coming from the environment variables:\",\n `IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT},`,\n \"IDENTITY_HEADER=[REDACTED] and\",\n \"IDENTITY_SERVER_THUMBPRINT=[REDACTED].\",\n ].join(\" \")\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n // The service fabric MSI endpoint will be HTTPS (however, the certificate will be self-signed).\n // allowInsecureConnection: true\n });\n\n request.agent = new https.Agent({\n // This is necessary because Service Fabric provides a self-signed certificate.\n // The alternative path is to verify the certificate using the IDENTITY_SERVER_THUMBPRINT env variable.\n rejectUnauthorized: false,\n });\n\n const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n"]}
@@ -30,7 +30,7 @@ function expiresOnParser(requestBody) {
30
30
  /**
31
31
  * Generates the options used on the request for an access token.
32
32
  */
33
- function prepareRequestOptions(scopes, clientId, options) {
33
+ function prepareRequestOptions(scopes, clientId, resourceId, options) {
34
34
  var _a;
35
35
  const resource = mapScopesToResource(scopes);
36
36
  if (!resource) {
@@ -48,6 +48,9 @@ function prepareRequestOptions(scopes, clientId, options) {
48
48
  if (clientId) {
49
49
  queryParameters.client_id = clientId;
50
50
  }
51
+ if (resourceId) {
52
+ queryParameters.msi_res_id = resourceId;
53
+ }
51
54
  const params = new URLSearchParams(queryParameters);
52
55
  query = `?${params.toString()}`;
53
56
  }
@@ -77,7 +80,7 @@ export const imdsMsiRetryConfig = {
77
80
  * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.
78
81
  */
79
82
  export const imdsMsi = {
80
- async isAvailable(scopes, identityClient, clientId, getTokenOptions) {
83
+ async isAvailable({ scopes, identityClient, clientId, resourceId, getTokenOptions, }) {
81
84
  var _a, _b;
82
85
  const resource = mapScopesToResource(scopes);
83
86
  if (!resource) {
@@ -89,7 +92,10 @@ export const imdsMsi = {
89
92
  if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {
90
93
  return true;
91
94
  }
92
- const requestOptions = prepareRequestOptions(resource, clientId, {
95
+ if (!identityClient) {
96
+ throw new Error("Missing IdentityClient");
97
+ }
98
+ const requestOptions = prepareRequestOptions(resource, clientId, resourceId, {
93
99
  skipMetadataHeader: true,
94
100
  skipQuery: true,
95
101
  });
@@ -142,12 +148,12 @@ export const imdsMsi = {
142
148
  }
143
149
  },
144
150
  async getToken(configuration, getTokenOptions = {}) {
145
- const { identityClient, scopes, clientId } = configuration;
151
+ const { identityClient, scopes, clientId, resourceId } = configuration;
146
152
  logger.info(`${msiName}: Using the Azure IMDS endpoint coming from the environment variable MSI_ENDPOINT=${process.env.MSI_ENDPOINT}, and using the cloud shell to proceed with the authentication.`);
147
153
  let nextDelayInMs = imdsMsiRetryConfig.startDelayInMs;
148
154
  for (let retries = 0; retries < imdsMsiRetryConfig.maxRetries; retries++) {
149
155
  try {
150
- const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId)), { allowInsecureConnection: true }));
156
+ const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, prepareRequestOptions(scopes, clientId, resourceId)), { allowInsecureConnection: true }));
151
157
  const tokenResponse = await identityClient.sendTokenRequest(request, expiresOnParser);
152
158
  return (tokenResponse && tokenResponse.accessToken) || null;
153
159
  }