@azure/identity 2.0.0 → 2.0.1-alpha.20211025.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.
- package/CHANGELOG.md +23 -9
- package/dist/index.js +103 -23
- package/dist/index.js.map +1 -1
- package/dist-esm/src/client/identityClient.js +1 -1
- package/dist-esm/src/client/identityClient.js.map +1 -1
- package/dist-esm/src/credentials/azureCliCredential.js +1 -1
- package/dist-esm/src/credentials/azureCliCredential.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js +7 -2
- package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/index.js +2 -3
- package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential/utils.js +4 -1
- package/dist-esm/src/credentials/managedIdentityCredential/utils.js.map +1 -1
- package/package.json +4 -4
|
@@ -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.
|
|
37
|
+
const packageDetails = `azsdk-js-identity/2.0.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;AAGlC,OAAO,EAAuB,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExE,OAAO,EAAE,cAAc,EAA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P,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 { CommonClientOptions, ServiceClient } from \"@azure/core-client\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\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\";\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\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.0`;\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 ...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: any) => 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: any) => {\n return Date.now() + responseBody.expires_in * 1000;\n });\n\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: {\n token?: string;\n access_token?: string;\n refresh_token?: string;\n } = 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: any) => 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\n/**\n * Provides options to configure how the Identity library makes authentication\n * requests to Azure Active Directory.\n */\nexport interface TokenCredentialOptions extends CommonClientOptions {\n /**\n * The authority host to use for authentication requests.\n * Possible values are available through {@link AzureAuthorityHosts}.\n * The default is \"https://login.microsoftonline.com\".\n */\n authorityHost?: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"identityClient.js","sourceRoot":"","sources":["../../../src/client/identityClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAuB,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EAEtB,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;AAEzC,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAkB1C;;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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,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 { CommonClientOptions, ServiceClient } from \"@azure/core-client\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\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\";\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\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.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 ...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: any) => 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: any) => {\n return Date.now() + responseBody.expires_in * 1000;\n });\n\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: {\n token?: string;\n access_token?: string;\n refresh_token?: string;\n } = 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: any) => 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\n/**\n * Provides options to configure how the Identity library makes authentication\n * requests to Azure Active Directory.\n */\nexport interface TokenCredentialOptions extends CommonClientOptions {\n /**\n * The authority host to use for authentication requests.\n * Possible values are available through {@link AzureAuthorityHosts}.\n * The default is \"https://login.microsoftonline.com\".\n */\n authorityHost?: string;\n}\n"]}
|
|
@@ -47,7 +47,7 @@ export const cliCredentialInternals = {
|
|
|
47
47
|
"--resource",
|
|
48
48
|
resource,
|
|
49
49
|
...tenantSection
|
|
50
|
-
], { cwd: cliCredentialInternals.getSafeWorkingDir() }, (error, stdout, stderr) => {
|
|
50
|
+
], { cwd: cliCredentialInternals.getSafeWorkingDir(), shell: true }, (error, stdout, stderr) => {
|
|
51
51
|
resolve({ stdout: stdout, stderr: stderr, error });
|
|
52
52
|
});
|
|
53
53
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"azureCliCredential.js","sourceRoot":"","sources":["../../../src/credentials/azureCliCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,aAAa,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAExE,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD;;;GAGG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC;;OAEG;IACH,iBAAiB;QACf,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;YAChC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE;gBAC3B,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;aACrF;YACD,OAAO,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;SAC/B;aAAM;YACL,OAAO,MAAM,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,sBAAsB,CAC1B,QAAgB,EAChB,QAAiB;QAEjB,IAAI,aAAa,GAAa,EAAE,CAAC;QACjC,IAAI,QAAQ,EAAE;YACZ,aAAa,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;SACxC;QACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,IAAI;gBACF,aAAa,CAAC,QAAQ,CACpB,IAAI,EACJ;oBACE,SAAS;oBACT,kBAAkB;oBAClB,UAAU;oBACV,MAAM;oBACN,YAAY;oBACZ,QAAQ;oBACR,GAAG,aAAa;iBACjB,EACD,EAAE,GAAG,EAAE,sBAAsB,CAAC,iBAAiB,EAAE,EAAE,
|
|
1
|
+
{"version":3,"file":"azureCliCredential.js","sourceRoot":"","sources":["../../../src/credentials/azureCliCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,aAAa,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAExE,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD;;;GAGG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC;;OAEG;IACH,iBAAiB;QACf,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;YAChC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE;gBAC3B,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;aACrF;YACD,OAAO,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;SAC/B;aAAM;YACL,OAAO,MAAM,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,sBAAsB,CAC1B,QAAgB,EAChB,QAAiB;QAEjB,IAAI,aAAa,GAAa,EAAE,CAAC;QACjC,IAAI,QAAQ,EAAE;YACZ,a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AW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;gBACjD,MAAM,KAAK,CAAC;aACb;iBAAM;gBACL,YAAY,GAAG,GAAG,CAAC,MAAM,CAAC;gBAC1B,MAAM,QAAQ,GAA+C,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;gBACtF,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;gBAC5C,MAAM,WAAW,GAAG;oBAClB,KAAK,EAAE,QAAQ,CAAC,WAAW;oBAC3B,kBAAkB,EAAE,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE;iBAC3D,CAAC;gBACF,OAAO,WAAW,CAAC;aACpB;SACF;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,KAAK,GAAG,IAAI,KAAK,CACpB,GAAa,CAAC,OAAO,IAAI,yDAAyD,CACpF,CAAC;YACF,IAAI,CAAC,SAAS,CAAC;gBACb,IAAI,EAAE,cAAc,CAAC,KAAK;gBAC1B,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB,CAAC,CAAC;YACH,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;YACjD,MAAM,KAAK,CAAC;SACb;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-auth\";\n\nimport { createSpan } from \"../util/tracing\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { credentialLogger, formatSuccess, formatError } from \"../util/logging\";\nimport child_process from \"child_process\";\nimport { ensureValidScope, getScopeResource } from \"../util/scopeUtils\";\nimport { AzureCliCredentialOptions } from \"./azureCliCredentialOptions\";\nimport { processMultiTenantRequest } from \"../util/validateMultiTenant\";\nimport { checkTenantId } from \"../util/checkTenantId\";\n\n/**\n * Mockable reference to the CLI credential cliCredentialFunctions\n * @internal\n */\nexport const cliCredentialInternals = {\n /**\n * @internal\n */\n getSafeWorkingDir(): string {\n if (process.platform === \"win32\") {\n if (!process.env.SystemRoot) {\n throw new Error(\"Azure CLI credential expects a 'SystemRoot' environment variable\");\n }\n return process.env.SystemRoot;\n } else {\n return \"/bin\";\n }\n },\n\n /**\n * Gets the access token from Azure CLI\n * @param resource - The resource to use when getting the token\n * @internal\n */\n async getAzureCliAccessToken(\n resource: string,\n tenantId?: string\n ): Promise<{ stdout: string; stderr: string; error: Error | null }> {\n let tenantSection: string[] = [];\n if (tenantId) {\n tenantSection = [\"--tenant\", tenantId];\n }\n return new Promise((resolve, reject) => {\n try {\n child_process.execFile(\n \"az\",\n [\n \"account\",\n \"get-access-token\",\n \"--output\",\n \"json\",\n \"--resource\",\n resource,\n ...tenantSection\n ],\n { cwd: cliCredentialInternals.getSafeWorkingDir(), shell: true },\n (error, stdout, stderr) => {\n resolve({ stdout: stdout, stderr: stderr, error });\n }\n );\n } catch (err) {\n reject(err);\n }\n });\n }\n};\n\nconst logger = credentialLogger(\"AzureCliCredential\");\n\n/**\n * This credential will use the currently logged-in user login information\n * via the Azure CLI ('az') commandline tool.\n * To do so, it will read the user access token and expire time\n * with Azure CLI command \"az account get-access-token\".\n */\nexport class AzureCliCredential implements TokenCredential {\n private tenantId?: string;\n\n /**\n * Creates an instance of the {@link AzureCliCredential}.\n *\n * To use this credential, ensure that you have already logged\n * in via the 'az' tool using the command \"az login\" from the commandline.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzureCliCredentialOptions) {\n this.tenantId = options?.tenantId;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken> {\n const tenantId = processMultiTenantRequest(this.tenantId, options);\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n logger.getToken.info(`Using the scope ${scope}`);\n ensureValidScope(scope, logger);\n const resource = getScopeResource(scope);\n\n let responseData = \"\";\n\n const { span } = createSpan(\"AzureCliCredential.getToken\", options);\n\n try {\n const obj = await cliCredentialInternals.getAzureCliAccessToken(resource, tenantId);\n if (obj.stderr) {\n const isLoginError = obj.stderr.match(\"(.*)az login(.*)\");\n const isNotInstallError =\n obj.stderr.match(\"az:(.*)not found\") || obj.stderr.startsWith(\"'az' is not recognized\");\n if (isNotInstallError) {\n const error = new CredentialUnavailableError(\n \"Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n } else if (isLoginError) {\n const error = new CredentialUnavailableError(\n \"Please run 'az login' from a command prompt to authenticate before using this credential.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n const error = new CredentialUnavailableError(obj.stderr);\n logger.getToken.info(formatError(scopes, error));\n throw error;\n } else {\n responseData = obj.stdout;\n const response: { accessToken: string; expiresOn: string } = JSON.parse(responseData);\n logger.getToken.info(formatSuccess(scopes));\n const returnValue = {\n token: response.accessToken,\n expiresOnTimestamp: new Date(response.expiresOn).getTime()\n };\n return returnValue;\n }\n } catch (err) {\n const error = new Error(\n (err as Error).message || \"Unknown error while trying to retrieve the access token\"\n );\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message\n });\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n }\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
|
2
2
|
// Licensed under the MIT license.
|
|
3
|
+
import https from "https";
|
|
3
4
|
import { createHttpHeaders } from "@azure/core-rest-pipeline";
|
|
4
5
|
import { credentialLogger } from "../../util/logging";
|
|
5
6
|
import { mapScopesToResource, msiGenericGetToken } from "./utils";
|
|
@@ -64,7 +65,7 @@ export const fabricMsi = {
|
|
|
64
65
|
return result;
|
|
65
66
|
},
|
|
66
67
|
async getToken(configuration, getTokenOptions = {}) {
|
|
67
|
-
const {
|
|
68
|
+
const { scopes, identityClient, clientId } = configuration;
|
|
68
69
|
logger.info([
|
|
69
70
|
`${msiName}:`,
|
|
70
71
|
"Using the endpoint and the secret coming from the environment variables:",
|
|
@@ -72,7 +73,11 @@ export const fabricMsi = {
|
|
|
72
73
|
"IDENTITY_HEADER=[REDACTED] and",
|
|
73
74
|
"IDENTITY_SERVER_THUMBPRINT=[REDACTED]."
|
|
74
75
|
].join(" "));
|
|
75
|
-
return msiGenericGetToken(identityClient, prepareRequestOptions(scopes, clientId), expiresInParser, getTokenOptions
|
|
76
|
+
return msiGenericGetToken(identityClient, prepareRequestOptions(scopes, clientId), expiresInParser, getTokenOptions, new https.Agent({
|
|
77
|
+
// This is necessary because Service Fabric provides a self-signed certificate.
|
|
78
|
+
// The alternative path is to verify the certificate using the IDENTITY_SERVER_THUMBPRINT env variable.
|
|
79
|
+
rejectUnauthorized: false
|
|
80
|
+
}));
|
|
76
81
|
}
|
|
77
82
|
};
|
|
78
83
|
//# sourceMappingURL=fabricMsi.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fabricMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/fabricMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,iBAAiB,EAA0B,MAAM,2BAA2B,CAAC;AAGtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM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AAQ,EAAE;YACb,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,mDAAmD,CAAC,CAAC;YAC3E,OAAO,KAAK,CAAC;SACd;QACD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACxB,MAAM,MAAM,GAAG,OAAO,CACpB,GAAG,CAAC,iBAAiB,IAAI,GAAG,CAAC,eAAe,IAAI,GAAG,CAAC,0BAA0B,CAC/E,CAAC;QACF,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,wHAAwH,CACnI,CAAC;SACH;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,KAAK,CAAC,QAAQ,CACZ,aAA+B,EAC/B,kBAAmC,EAAE;QAErC,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,aAAa,CAAC;QAE3D,MAAM,CAAC,IAAI,CACT;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,OAAO,kBAAkB,CACvB,cAAc,EACd,qBAAqB,CAAC,MAAM,EAAE,QAAQ,CAAC,EACvC,eAAe,EACf,eAAe,EACf,IAAI,KAAK,CAAC,KAAK,CAAC;YACd,+EAA+E;YAC/E,uGAAuG;YACvG,kBAAkB,EAAE,KAAK;SAC1B,CAAC,CACH,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport https from \"https\";\nimport { createHttpHeaders, PipelineRequestOptions } from \"@azure/core-rest-pipeline\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { mapScopesToResource, msiGenericGetToken } from \"./utils\";\nimport { azureFabricVersion } from \"./constants\";\n\nconst msiName = \"ManagedIdentityCredential - Fabric MSI\";\nconst logger = credentialLogger(msiName);\n\nfunction expiresInParser(requestBody: any): number {\n // Parses a string representation of the seconds since epoch into a number value\n return Number(requestBody.expires_on);\n}\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: any = {\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// This credential 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\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 return msiGenericGetToken(\n identityClient,\n prepareRequestOptions(scopes, clientId),\n expiresInParser,\n getTokenOptions,\n 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 }\n};\n"]}
|
|
@@ -10,6 +10,7 @@ import { cloudShellMsi } from "./cloudShellMsi";
|
|
|
10
10
|
import { imdsMsi } from "./imdsMsi";
|
|
11
11
|
import { arcMsi } from "./arcMsi";
|
|
12
12
|
import { tokenExchangeMsi } from "./tokenExchangeMsi";
|
|
13
|
+
import { fabricMsi } from "./fabricMsi";
|
|
13
14
|
const logger = credentialLogger("ManagedIdentityCredential");
|
|
14
15
|
/**
|
|
15
16
|
* Attempts authentication using a managed identity that has been assigned
|
|
@@ -41,9 +42,7 @@ export class ManagedIdentityCredential {
|
|
|
41
42
|
if (this.cachedMSI) {
|
|
42
43
|
return this.cachedMSI;
|
|
43
44
|
}
|
|
44
|
-
|
|
45
|
-
// which is necessary since Service Fabric only provides self-signed certificates on their Identity Endpoint.
|
|
46
|
-
const MSIs = [appServiceMsi2017, cloudShellMsi, arcMsi, tokenExchangeMsi(), imdsMsi];
|
|
45
|
+
const MSIs = [fabricMsi, appServiceMsi2017, cloudShellMsi, arcMsi, tokenExchangeMsi(), imdsMsi];
|
|
47
46
|
for (const msi of MSIs) {
|
|
48
47
|
if (await msi.isAvailable(scopes, this.identityClient, clientId, getTokenOptions)) {
|
|
49
48
|
this.cachedMSI = msi;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,OAAO,EAAE,cAAc,EAA0B,MAAM,6BAA6B,CAAC;AACrF,OAAO,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D;;;;;;;;GAQG;AACH,MAAM,OAAO,yBAAyB;IAmBpC;;;OAGG;IACH,YACE,iBAA8D,EAC9D,OAAgC;QAtB1B,0BAAqB,GAAmB,IAAI,CAAC;QAwBnD,IAAI,OAAO,iBAAiB,KAAK,QAAQ,EAAE;YACzC,gCAAgC;YAChC,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;YAClC,IAAI,CAAC,cAAc,GAAG,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;SACnD;aAAM;YACL,2BAA2B;YAC3B,IAAI,CAAC,cAAc,GAAG,IAAI,cAAc,CAAC,iBAAiB,CAAC,CAAC;SAC7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A0C;YAC1C,MAAM,IAAI,mBAAmB,CAAC,GAAG,CAAC,UAAU,EAAE;gBAC5C,KAAK,EAAE,kDAAkD;gBACzD,iBAAiB,EAAE,GAAG,CAAC,OAAO;aAC/B,CAAC,CAAC;SACJ;gBAAS;YACR,sFAAsF;YACtF,IAAI,CAAC,GAAG,EAAE,CAAC;SACZ;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport { IdentityClient, TokenCredentialOptions } from \"../../client/identityClient\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../../errors\";\nimport { credentialLogger, formatSuccess, formatError } from \"../../util/logging\";\nimport { appServiceMsi2017 } from \"./appServiceMsi2017\";\nimport { createSpan } from \"../../util/tracing\";\nimport { cloudShellMsi } from \"./cloudShellMsi\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { MSI } from \"./models\";\nimport { arcMsi } from \"./arcMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n/**\n * Attempts authentication using a managed identity that has been assigned\n * to the deployment environment. This authentication type works in Azure VMs,\n * App Service and Azure Functions applications, and inside of Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private clientId: string | undefined;\n private isEndpointUnavailable: boolean | null = null;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: TokenCredentialOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions: string | TokenCredentialOptions | undefined,\n options?: TokenCredentialOptions\n ) {\n if (typeof clientIdOrOptions === \"string\") {\n // clientId, options constructor\n this.clientId = clientIdOrOptions;\n this.identityClient = new IdentityClient(options);\n } else {\n // options only constructor\n this.identityClient = new IdentityClient(clientIdOrOptions);\n }\n }\n\n private cachedMSI: MSI | undefined;\n\n private async cachedAvailableMSI(\n scopes: string | string[],\n clientId?: string,\n getTokenOptions?: GetTokenOptions\n ): Promise<MSI> {\n if (this.cachedMSI) {\n return this.cachedMSI;\n }\n\n // \"fabricMsi\" can't be added yet because our HTTPs pipeline doesn't allow skipping the SSL verification step,\n // which is necessary since Service Fabric only provides self-signed certificates on their Identity Endpoint.\n const MSIs = [appServiceMsi2017, cloudShellMsi, arcMsi, tokenExchangeMsi(), imdsMsi];\n\n for (const msi of MSIs) {\n if (await msi.isAvailable(scopes, this.identityClient, clientId, getTokenOptions)) {\n this.cachedMSI = msi;\n return msi;\n }\n }\n\n throw new CredentialUnavailableError(\"ManagedIdentityCredential - No MSI credential available\");\n }\n\n private async authenticateManagedIdentity(\n scopes: string | string[],\n clientId?: string,\n getTokenOptions?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span, updatedOptions } = createSpan(\n \"ManagedIdentityCredential-authenticateManagedIdentity\",\n getTokenOptions\n );\n\n try {\n // Determining the available MSI, and avoiding checking for other MSIs while the program is running.\n const availableMSI = await this.cachedAvailableMSI(scopes, clientId, updatedOptions);\n\n return availableMSI.getToken(\n {\n identityClient: this.identityClient,\n scopes,\n clientId\n },\n updatedOptions\n );\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n throw err;\n } finally {\n span.end();\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken> {\n let result: AccessToken | null = null;\n\n const { span, updatedOptions } = createSpan(\"ManagedIdentityCredential.getToken\", options);\n\n try {\n // isEndpointAvailable can be true, false, or null,\n // If it's null, it means we don't yet know whether\n // the endpoint is available and need to check for it.\n if (this.isEndpointUnavailable !== true) {\n result = await this.authenticateManagedIdentity(scopes, this.clientId, updatedOptions);\n\n if (result === null) {\n // If authenticateManagedIdentity returns null,\n // it means no MSI endpoints are available.\n // If so, we avoid trying to reach to them in future requests.\n this.isEndpointUnavailable = true;\n\n // It also means that the endpoint answered with either 200 or 201 (see the sendTokenRequest method),\n // yet we had no access token. For this reason, we'll throw once with a specific message:\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint was reached, yet no tokens were received.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // Since `authenticateManagedIdentity` didn't throw, and the result was not null,\n // We will assume that this endpoint is reachable from this point forward,\n // and avoid pinging again to it.\n this.isEndpointUnavailable = false;\n } else {\n // We've previously determined that the endpoint was unavailable,\n // either because it was unreachable or permanently unable to authenticate.\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint is not currently available\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err) {\n // CredentialUnavailable errors are expected to reach here.\n // We intend them to bubble up, so that DefaultAzureCredential can catch them.\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n // Expected errors to reach this point:\n // - Errors coming from a method unexpectedly breaking.\n // - When identityClient.sendTokenRequest throws, in which case\n // if the status code was 400, it means that the endpoint is working,\n // but no identity is available.\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n\n // If either the network is unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"ENETUNREACH\") {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential is unavailable. Network unreachable. Message: ${err.message}`\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // If either the host was unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"EHOSTUNREACH\") {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential is unavailable. No managed identity endpoint found. Message: ${err.message}`\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // If err.statusCode has a value of 400, it comes from sendTokenRequest,\n // and it means that the endpoint is working, but that no identity is available.\n if (err.statusCode === 400) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: The managed identity endpoint is indicating there's no available identity. Message: ${err.message}`\n );\n }\n\n // If the error has no status code, we can assume there was no available identity.\n // This will throw silently during any ChainedTokenCredential.\n if (err.statusCode === undefined) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential authentication failed. Message ${err.message}`\n );\n }\n\n // Any other error should break the chain.\n throw new AuthenticationError(err.statusCode, {\n error: \"ManagedIdentityCredential authentication failed.\",\n error_description: err.message\n });\n } finally {\n // Finally is always called, both if we return and if we throw in the above try/catch.\n span.end();\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,OAAO,EAAE,cAAc,EAA0B,MAAM,6BAA6B,CAAC;AACrF,OAAO,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EA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M,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;gBACjD,MAAM,KAAK,CAAC;aACb;YAED,sCAAsC;YACtC,sDAAsD;YACtD,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE;gBAC/B,MAAM,KAAK,GAAG,IAAI,0BAA0B,CAC1C,0FAA0F,GAAG,CAAC,OAAO,EAAE,CACxG,CAAC;gBAEF,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;gBACjD,MAAM,KAAK,CAAC;aACb;YAED,wEAAwE;YACxE,gFAAgF;YAChF,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,EAAE;gBAC1B,MAAM,IAAI,0BAA0B,CAClC,kHAAkH,GAAG,CAAC,OAAO,EAAE,CAChI,CAAC;aACH;YAED,kFAAkF;YAClF,8DAA8D;YAC9D,IAAI,GAAG,CAAC,UAAU,KAAK,SAAS,EAAE;gBAChC,MAAM,IAAI,0BAA0B,CAClC,4DAA4D,GAAG,CAAC,OAAO,EAAE,CAC1E,CAAC;aACH;YAED,0CAA0C;YAC1C,MAAM,IAAI,mBAAmB,CAAC,GAAG,CAAC,UAAU,EAAE;gBAC5C,KAAK,EAAE,kDAAkD;gBACzD,iBAAiB,EAAE,GAAG,CAAC,OAAO;aAC/B,CAAC,CAAC;SACJ;gBAAS;YACR,sFAAsF;YACtF,IAAI,CAAC,GAAG,EAAE,CAAC;SACZ;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { SpanStatusCode } from \"@azure/core-tracing\";\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport { IdentityClient, TokenCredentialOptions } from \"../../client/identityClient\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../../errors\";\nimport { credentialLogger, formatSuccess, formatError } from \"../../util/logging\";\nimport { appServiceMsi2017 } from \"./appServiceMsi2017\";\nimport { createSpan } from \"../../util/tracing\";\nimport { cloudShellMsi } from \"./cloudShellMsi\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { MSI } from \"./models\";\nimport { arcMsi } from \"./arcMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { fabricMsi } from \"./fabricMsi\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n/**\n * Attempts authentication using a managed identity that has been assigned\n * to the deployment environment. This authentication type works in Azure VMs,\n * App Service and Azure Functions applications, and inside of Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private clientId: string | undefined;\n private isEndpointUnavailable: boolean | null = null;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: TokenCredentialOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions: string | TokenCredentialOptions | undefined,\n options?: TokenCredentialOptions\n ) {\n if (typeof clientIdOrOptions === \"string\") {\n // clientId, options constructor\n this.clientId = clientIdOrOptions;\n this.identityClient = new IdentityClient(options);\n } else {\n // options only constructor\n this.identityClient = new IdentityClient(clientIdOrOptions);\n }\n }\n\n private cachedMSI: MSI | undefined;\n\n private async cachedAvailableMSI(\n scopes: string | string[],\n clientId?: string,\n getTokenOptions?: GetTokenOptions\n ): Promise<MSI> {\n if (this.cachedMSI) {\n return this.cachedMSI;\n }\n\n const MSIs = [fabricMsi, appServiceMsi2017, cloudShellMsi, arcMsi, tokenExchangeMsi(), imdsMsi];\n\n for (const msi of MSIs) {\n if (await msi.isAvailable(scopes, this.identityClient, clientId, getTokenOptions)) {\n this.cachedMSI = msi;\n return msi;\n }\n }\n\n throw new CredentialUnavailableError(\"ManagedIdentityCredential - No MSI credential available\");\n }\n\n private async authenticateManagedIdentity(\n scopes: string | string[],\n clientId?: string,\n getTokenOptions?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const { span, updatedOptions } = createSpan(\n \"ManagedIdentityCredential-authenticateManagedIdentity\",\n getTokenOptions\n );\n\n try {\n // Determining the available MSI, and avoiding checking for other MSIs while the program is running.\n const availableMSI = await this.cachedAvailableMSI(scopes, clientId, updatedOptions);\n\n return availableMSI.getToken(\n {\n identityClient: this.identityClient,\n scopes,\n clientId\n },\n updatedOptions\n );\n } catch (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n throw err;\n } finally {\n span.end();\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken> {\n let result: AccessToken | null = null;\n\n const { span, updatedOptions } = createSpan(\"ManagedIdentityCredential.getToken\", options);\n\n try {\n // isEndpointAvailable can be true, false, or null,\n // If it's null, it means we don't yet know whether\n // the endpoint is available and need to check for it.\n if (this.isEndpointUnavailable !== true) {\n result = await this.authenticateManagedIdentity(scopes, this.clientId, updatedOptions);\n\n if (result === null) {\n // If authenticateManagedIdentity returns null,\n // it means no MSI endpoints are available.\n // If so, we avoid trying to reach to them in future requests.\n this.isEndpointUnavailable = true;\n\n // It also means that the endpoint answered with either 200 or 201 (see the sendTokenRequest method),\n // yet we had no access token. For this reason, we'll throw once with a specific message:\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint was reached, yet no tokens were received.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // Since `authenticateManagedIdentity` didn't throw, and the result was not null,\n // We will assume that this endpoint is reachable from this point forward,\n // and avoid pinging again to it.\n this.isEndpointUnavailable = false;\n } else {\n // We've previously determined that the endpoint was unavailable,\n // either because it was unreachable or permanently unable to authenticate.\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint is not currently available\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err) {\n // CredentialUnavailable errors are expected to reach here.\n // We intend them to bubble up, so that DefaultAzureCredential can catch them.\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n // Expected errors to reach this point:\n // - Errors coming from a method unexpectedly breaking.\n // - When identityClient.sendTokenRequest throws, in which case\n // if the status code was 400, it means that the endpoint is working,\n // but no identity is available.\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message\n });\n\n // If either the network is unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"ENETUNREACH\") {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential is unavailable. Network unreachable. Message: ${err.message}`\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // If either the host was unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"EHOSTUNREACH\") {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential is unavailable. No managed identity endpoint found. Message: ${err.message}`\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // If err.statusCode has a value of 400, it comes from sendTokenRequest,\n // and it means that the endpoint is working, but that no identity is available.\n if (err.statusCode === 400) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: The managed identity endpoint is indicating there's no available identity. Message: ${err.message}`\n );\n }\n\n // If the error has no status code, we can assume there was no available identity.\n // This will throw silently during any ChainedTokenCredential.\n if (err.statusCode === undefined) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential authentication failed. Message ${err.message}`\n );\n }\n\n // Any other error should break the chain.\n throw new AuthenticationError(err.statusCode, {\n error: \"ManagedIdentityCredential authentication failed.\",\n error_description: err.message\n });\n } finally {\n // Finally is always called, both if we return and if we throw in the above try/catch.\n span.end();\n }\n }\n}\n"]}
|
|
@@ -26,8 +26,11 @@ export function mapScopesToResource(scopes) {
|
|
|
26
26
|
}
|
|
27
27
|
return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));
|
|
28
28
|
}
|
|
29
|
-
export async function msiGenericGetToken(identityClient, requestOptions, expiresInParser, getTokenOptions = {}) {
|
|
29
|
+
export async function msiGenericGetToken(identityClient, requestOptions, expiresInParser, getTokenOptions = {}, agent) {
|
|
30
30
|
const request = createPipelineRequest(Object.assign(Object.assign({ abortSignal: getTokenOptions.abortSignal }, requestOptions), { allowInsecureConnection: true }));
|
|
31
|
+
if (agent) {
|
|
32
|
+
request.agent = agent;
|
|
33
|
+
}
|
|
31
34
|
const tokenResponse = await identityClient.sendTokenRequest(request, expiresInParser);
|
|
32
35
|
return (tokenResponse && tokenResponse.accessToken) || null;
|
|
33
36
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAA0B,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAA0B,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAG1F,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGjD;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAyB;IAC3D,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACzB,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;YACvB,OAAO;SACR;QAED,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;KACnB;SAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QACrC,KAAK,GAAG,MAAM,CAAC;KAChB;IAED,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE;QACvC,OAAO,KAAK,CAAC;KACd;IAED,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,cAA8B,EAC9B,cAAsC,EACtC,eAA+C,EAC/C,kBAAmC,EAAE,EACrC,KAAa;IAEb,MAAM,OAAO,GAAG,qBAAqB,+BACnC,WAAW,EAAE,eAAe,CAAC,WAAW,IACrC,cAAc,KACjB,uBAAuB,EAAE,IAAI,IAC7B,CAAC;IAEH,IAAI,KAAK,EAAE;QACT,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC;KACvB;IAED,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;IACtF,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;AAC9D,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { PipelineRequestOptions, createPipelineRequest } from \"@azure/core-rest-pipeline\";\nimport { Agent } from \"http\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { DefaultScopeSuffix } from \"./constants\";\nimport { MSIExpiresInParser } from \"./models\";\n\n/**\n * Most MSIs send requests to the IMDS endpoint, or a similar endpoint. These are GET requests that require sending a `resource` parameter on the query.\n * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received.\n * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case.\n *\n * For that reason, when we encounter multiple scopes, we return undefined.\n * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors).\n */\nexport function mapScopesToResource(scopes: string | string[]): string | undefined {\n let scope = \"\";\n if (Array.isArray(scopes)) {\n if (scopes.length !== 1) {\n return;\n }\n\n scope = scopes[0];\n } else if (typeof scopes === \"string\") {\n scope = scopes;\n }\n\n if (!scope.endsWith(DefaultScopeSuffix)) {\n return scope;\n }\n\n return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));\n}\n\nexport async function msiGenericGetToken(\n identityClient: IdentityClient,\n requestOptions: PipelineRequestOptions,\n expiresInParser: MSIExpiresInParser | undefined,\n getTokenOptions: GetTokenOptions = {},\n agent?: Agent\n): Promise<AccessToken | null> {\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...requestOptions,\n allowInsecureConnection: true\n });\n\n if (agent) {\n request.agent = agent;\n }\n\n const tokenResponse = await identityClient.sendTokenRequest(request, expiresInParser);\n return (tokenResponse && tokenResponse.accessToken) || null;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@azure/identity",
|
|
3
3
|
"sdk-type": "client",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.1-alpha.20211025.3",
|
|
5
5
|
"description": "Provides credential implementations for Azure SDK libraries that can authenticate with Azure Active Directory",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"module": "dist-esm/src/index.js",
|
|
@@ -111,9 +111,9 @@
|
|
|
111
111
|
"uuid": "^8.3.0"
|
|
112
112
|
},
|
|
113
113
|
"devDependencies": {
|
|
114
|
-
"@azure/eslint-plugin-azure-sdk": "
|
|
115
|
-
"@azure/dev-tool": "
|
|
116
|
-
"@azure/test-utils": "
|
|
114
|
+
"@azure/eslint-plugin-azure-sdk": ">=3.0.0-alpha <3.0.0-alphb",
|
|
115
|
+
"@azure/dev-tool": ">=1.0.0-alpha <1.0.0-alphb",
|
|
116
|
+
"@azure/test-utils": ">=1.0.0-alpha <1.0.0-alphb",
|
|
117
117
|
"@azure-tools/test-recorder": "^1.0.0",
|
|
118
118
|
"@microsoft/api-extractor": "^7.18.11",
|
|
119
119
|
"@types/jws": "^3.2.2",
|