@azure/identity 4.5.0-alpha.20240822.3 → 4.5.0-alpha.20240826.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -8,7 +8,7 @@ import { getIdentityTokenEndpointSuffix } from "../util/identityTokenEndpoint";
8
8
  import { DefaultAuthorityHost, SDK_VERSION } from "../constants";
9
9
  import { tracingClient } from "../util/tracing";
10
10
  import { logger } from "../util/logging";
11
- import { parseExpirationTimestamp, } from "../credentials/managedIdentityCredential/utils";
11
+ import { parseExpirationTimestamp, parseRefreshTimestamp, } from "../credentials/managedIdentityCredential/utils";
12
12
  const noCorrelationId = "noCorrelationId";
13
13
  /**
14
14
  * @internal
@@ -70,6 +70,7 @@ export class IdentityClient extends ServiceClient {
70
70
  accessToken: {
71
71
  token: parsedBody.access_token,
72
72
  expiresOnTimestamp: parseExpirationTimestamp(parsedBody),
73
+ refreshAfterTimestamp: parseRefreshTimestamp(parsedBody),
73
74
  },
74
75
  refreshToken: parsedBody.refresh_token,
75
76
  };
@@ -1 +1 @@
1
- {"version":3,"file":"identityClient.js","sourceRoot":"","sources":["../../../src/client/identityClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAGL,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AACzE,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC,OAAO,EAEL,wBAAwB,GACzB,MAAM,gDAAgD,CAAC;AAExD,MA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ACT,uBAAuB,GAAG,EAAE,CAC7B,CAAC;QACJ,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,CAAC,OAAO,CACZ,6FAA6F,EAC7F,CAAC,CAAC,OAAO,CACV,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport type { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-node\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport {\n PipelineRequest,\n PipelineResponse,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost, SDK_VERSION } from \"../constants\";\nimport { tracingClient } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\nimport {\n TokenResponseParsedBody,\n parseExpirationTimestamp,\n} from \"../credentials/managedIdentityCredential/utils\";\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 * 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 allowLoggingAccountIdentifiers?: boolean;\n private abortControllers: Map<string, AbortController[] | undefined>;\n private allowInsecureConnection: boolean = false;\n // used for WorkloadIdentity\n private tokenCredentialOptions: TokenCredentialOptions;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;\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 this.allowLoggingAccountIdentifiers = options?.loggingOptions?.allowLoggingAccountIdentifiers;\n // used for WorkloadIdentity\n this.tokenCredentialOptions = { ...options };\n\n // used for ManagedIdentity\n if (options?.allowInsecureConnection) {\n this.allowInsecureConnection = options.allowInsecureConnection;\n }\n }\n\n async sendTokenRequest(request: PipelineRequest): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\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 this.logIdentifiers(response);\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: parseExpirationTimestamp(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 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 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 return tracingClient.withSpan(\n \"IdentityClient.refreshAccessToken\",\n options,\n async (updatedOptions) => {\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.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);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err: any) {\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 return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`,\n );\n throw err;\n }\n }\n },\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.apply(controller.signal, 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 allowInsecureConnection: this.allowInsecureConnection,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\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 allowInsecureConnection: this.allowInsecureConnection,\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\n this.logIdentifiers(response);\n\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 * @internal\n */\n getTokenCredentialOptions(): TokenCredentialOptions {\n return this.tokenCredentialOptions;\n }\n /**\n * If allowLoggingAccountIdentifiers was set on the constructor options\n * we try to log the account identifiers by parsing the received access token.\n *\n * The account identifiers we try to log are:\n * - `appid`: The application or Client Identifier.\n * - `upn`: User Principal Name.\n * - It might not be available in some authentication scenarios.\n * - If it's not available, we put a placeholder: \"No User Principal Name available\".\n * - `tid`: Tenant Identifier.\n * - `oid`: Object Identifier of the authenticated user.\n */\n private logIdentifiers(response: PipelineResponse): void {\n if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {\n return;\n }\n const unavailableUpn = \"No User Principal Name available\";\n try {\n const parsed = (response as any).parsedBody || JSON.parse(response.bodyAsText);\n const accessToken = parsed.access_token;\n if (!accessToken) {\n // Without an access token allowLoggingAccountIdentifiers isn't useful.\n return;\n }\n const base64Metadata = accessToken.split(\".\")[1];\n const { appid, upn, tid, oid } = JSON.parse(\n Buffer.from(base64Metadata, \"base64\").toString(\"utf8\"),\n );\n\n logger.info(\n `[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${\n upn || unavailableUpn\n }. Object ID (user): ${oid}`,\n );\n } catch (e: any) {\n logger.warning(\n \"allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:\",\n e.message,\n );\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,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAGL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W,GAAG,MAAM,CAAC,YAAY,CAAC;YACxC,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,uEAAuE;gBACvE,OAAO;YACT,CAAC;YACD,MAAM,cAAc,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACjD,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CACzC,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CACvD,CAAC;YAEF,MAAM,CAAC,IAAI,CACT,sCAAsC,KAAK,gBAAgB,GAAG,0BAC5D,GAAG,IAAI,cACT,uBAAuB,GAAG,EAAE,CAC7B,CAAC;QACJ,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,CAAC,OAAO,CACZ,6FAA6F,EAC7F,CAAC,CAAC,OAAO,CACV,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport type { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-node\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport {\n PipelineRequest,\n PipelineResponse,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost, SDK_VERSION } from \"../constants\";\nimport { tracingClient } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\nimport {\n TokenResponseParsedBody,\n parseExpirationTimestamp,\n parseRefreshTimestamp,\n} from \"../credentials/managedIdentityCredential/utils\";\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 * 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 allowLoggingAccountIdentifiers?: boolean;\n private abortControllers: Map<string, AbortController[] | undefined>;\n private allowInsecureConnection: boolean = false;\n // used for WorkloadIdentity\n private tokenCredentialOptions: TokenCredentialOptions;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;\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 this.allowLoggingAccountIdentifiers = options?.loggingOptions?.allowLoggingAccountIdentifiers;\n // used for WorkloadIdentity\n this.tokenCredentialOptions = { ...options };\n\n // used for ManagedIdentity\n if (options?.allowInsecureConnection) {\n this.allowInsecureConnection = options.allowInsecureConnection;\n }\n }\n\n async sendTokenRequest(request: PipelineRequest): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\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 this.logIdentifiers(response);\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: parseExpirationTimestamp(parsedBody),\n refreshAfterTimestamp: parseRefreshTimestamp(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 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 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 return tracingClient.withSpan(\n \"IdentityClient.refreshAccessToken\",\n options,\n async (updatedOptions) => {\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.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);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err: any) {\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 return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`,\n );\n throw err;\n }\n }\n },\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.apply(controller.signal, 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 allowInsecureConnection: this.allowInsecureConnection,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\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 allowInsecureConnection: this.allowInsecureConnection,\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\n this.logIdentifiers(response);\n\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 * @internal\n */\n getTokenCredentialOptions(): TokenCredentialOptions {\n return this.tokenCredentialOptions;\n }\n /**\n * If allowLoggingAccountIdentifiers was set on the constructor options\n * we try to log the account identifiers by parsing the received access token.\n *\n * The account identifiers we try to log are:\n * - `appid`: The application or Client Identifier.\n * - `upn`: User Principal Name.\n * - It might not be available in some authentication scenarios.\n * - If it's not available, we put a placeholder: \"No User Principal Name available\".\n * - `tid`: Tenant Identifier.\n * - `oid`: Object Identifier of the authenticated user.\n */\n private logIdentifiers(response: PipelineResponse): void {\n if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {\n return;\n }\n const unavailableUpn = \"No User Principal Name available\";\n try {\n const parsed = (response as any).parsedBody || JSON.parse(response.bodyAsText);\n const accessToken = parsed.access_token;\n if (!accessToken) {\n // Without an access token allowLoggingAccountIdentifiers isn't useful.\n return;\n }\n const base64Metadata = accessToken.split(\".\")[1];\n const { appid, upn, tid, oid } = JSON.parse(\n Buffer.from(base64Metadata, \"base64\").toString(\"utf8\"),\n );\n\n logger.info(\n `[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${\n upn || unavailableUpn\n }. Object ID (user): ${oid}`,\n );\n } catch (e: any) {\n logger.warning(\n \"allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:\",\n e.message,\n );\n }\n }\n}\n"]}
@@ -241,11 +241,13 @@ export class LegacyMsiProvider {
241
241
  * If the token received is invalid, an error will be thrown depending on what's missing.
242
242
  */
243
243
  handleResult(scopes, result, getTokenOptions) {
244
+ var _a;
244
245
  this.ensureValidMsalToken(scopes, result, getTokenOptions);
245
246
  logger.getToken.info(formatSuccess(scopes));
246
247
  return {
247
248
  token: result.accessToken,
248
249
  expiresOnTimestamp: result.expiresOn.getTime(),
250
+ refreshAfterTimestamp: (_a = result.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(),
249
251
  };
250
252
  }
251
253
  /**
@@ -282,9 +284,13 @@ export class LegacyMsiProvider {
282
284
  const expiresInSeconds = (resultToken === null || resultToken === void 0 ? void 0 : resultToken.expiresOnTimestamp)
283
285
  ? Math.floor((resultToken.expiresOnTimestamp - Date.now()) / 1000)
284
286
  : 0;
287
+ const refreshInSeconds = (resultToken === null || resultToken === void 0 ? void 0 : resultToken.refreshAfterTimestamp)
288
+ ? Math.floor((resultToken.refreshAfterTimestamp - Date.now()) / 1000)
289
+ : 0;
285
290
  return {
286
291
  accessToken: resultToken === null || resultToken === void 0 ? void 0 : resultToken.token,
287
292
  expiresInSeconds,
293
+ refreshInSeconds,
288
294
  };
289
295
  }
290
296
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"legacyMsiProvider.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/legacyMsiProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAA8B,6BAA6B,EAAE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,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,MAAM,CAAC,IAAI,CACT,6EAA6E,CAC9E,CAAC;oBACF,OAAO;wBACL,WAAW,EAAE,0BAA0B;wBACvC,gBAAgB,EAAE,CAAC;qBACpB,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,6BAA6B,GAAG,IAAI,CAAC;QAC5C,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AppTokenProviderParameters, ConfidentialClientApplication } from \"@azure/msal-node\";\nimport {\n AuthenticationError,\n AuthenticationRequiredError,\n CredentialUnavailableError,\n} from \"../../errors\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { MsalResult, MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { cloudShellMsi } from \"./cloudShellMsi\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\n\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { appServiceMsi2017 } from \"./appServiceMsi2017\";\nimport { appServiceMsi2019 } from \"./appServiceMsi2019\";\nimport { arcMsi } from \"./arcMsi\";\nimport { fabricMsi } from \"./fabricMsi\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { getMSALLogLevel } from \"../../msal/utils\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n// As part of the migration of Managed Identity to MSAL, this legacy provider captures the existing behavior\n// ported over from the ManagedIdentityCredential verbatim. This is to ensure that the existing behavior\n// is maintained while the new implementation is being tested and validated.\n// https://github.com/Azure/azure-sdk-for-js/issues/30189 tracks deleting this provider once it is no longer needed.\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n}\n\nexport class LegacyMsiProvider {\n private identityClient: IdentityClient;\n private clientId: string | undefined;\n private resourceId: string | undefined;\n private isEndpointUnavailable: boolean | null = null;\n private isAvailableIdentityClient: IdentityClient;\n private confidentialApp: ConfidentialClientApplication;\n private isAppTokenProviderInitialized: boolean = false;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options?: TokenCredentialOptions,\n ) {\n let _options: TokenCredentialOptions | undefined;\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = (clientIdOrOptions as ManagedIdentityCredentialOptions)?.clientId;\n _options = clientIdOrOptions;\n }\n this.resourceId = (_options as ManagedIdentityCredentialOptions)?.resourceId;\n // For JavaScript users.\n if (this.clientId && this.resourceId) {\n throw new Error(\n `ManagedIdentityCredential - Client Id and Resource Id can't be provided at the same time.`,\n );\n }\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n this.identityClient = new IdentityClient(_options);\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n /** authority host validation and metadata discovery to be skipped in managed identity\n * since this wasn't done previously before adding token cache support\n */\n this.confidentialApp = new ConfidentialClientApplication({\n auth: {\n authority: \"https://login.microsoftonline.com/managed_identity\",\n clientId: this.clientId ?? DeveloperSignOnClientId,\n clientSecret: \"dummy-secret\",\n cloudDiscoveryMetadata:\n '{\"tenant_discovery_endpoint\":\"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration\",\"api-version\":\"1.1\",\"metadata\":[{\"preferred_network\":\"login.microsoftonline.com\",\"preferred_cache\":\"login.windows.net\",\"aliases\":[\"login.microsoftonline.com\",\"login.windows.net\",\"login.microsoft.com\",\"sts.windows.net\"]},{\"preferred_network\":\"login.partner.microsoftonline.cn\",\"preferred_cache\":\"login.partner.microsoftonline.cn\",\"aliases\":[\"login.partner.microsoftonline.cn\",\"login.chinacloudapi.cn\"]},{\"preferred_network\":\"login.microsoftonline.de\",\"preferred_cache\":\"login.microsoftonline.de\",\"aliases\":[\"login.microsoftonline.de\"]},{\"preferred_network\":\"login.microsoftonline.us\",\"preferred_cache\":\"login.microsoftonline.us\",\"aliases\":[\"login.microsoftonline.us\",\"login.usgovcloudapi.net\"]},{\"preferred_network\":\"login-us.microsoftonline.com\",\"preferred_cache\":\"login-us.microsoftonline.com\",\"aliases\":[\"login-us.microsoftonline.com\"]}]}',\n authorityMetadata:\n '{\"token_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_post\",\"private_key_jwt\",\"client_secret_basic\"],\"jwks_uri\":\"https://login.microsoftonline.com/common/discovery/v2.0/keys\",\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],\"subject_types_supported\":[\"pairwise\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"response_types_supported\":[\"code\",\"id_token\",\"code id_token\",\"id_token token\"],\"scopes_supported\":[\"openid\",\"profile\",\"email\",\"offline_access\"],\"issuer\":\"https://login.microsoftonline.com/{tenantid}/v2.0\",\"request_uri_parameter_supported\":false,\"userinfo_endpoint\":\"https://graph.microsoft.com/oidc/userinfo\",\"authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/authorize\",\"device_authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/devicecode\",\"http_logout_supported\":true,\"frontchannel_logout_supported\":true,\"end_session_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/logout\",\"claims_supported\":[\"sub\",\"iss\",\"cloud_instance_name\",\"cloud_instance_host_name\",\"cloud_graph_host_name\",\"msgraph_host\",\"aud\",\"exp\",\"iat\",\"auth_time\",\"acr\",\"nonce\",\"preferred_username\",\"name\",\"tid\",\"ver\",\"at_hash\",\"c_hash\",\"email\"],\"kerberos_endpoint\":\"https://login.microsoftonline.com/common/kerberos\",\"tenant_region_scope\":null,\"cloud_instance_name\":\"microsoftonline.com\",\"cloud_graph_host_name\":\"graph.windows.net\",\"msgraph_host\":\"graph.microsoft.com\",\"rbac_url\":\"https://pas.windows.net\"}',\n clientCapabilities: [],\n },\n system: {\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n },\n },\n });\n }\n\n private cachedMSI: MSI | undefined;\n\n private async cachedAvailableMSI(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSI> {\n if (this.cachedMSI) {\n return this.cachedMSI;\n }\n\n const MSIs = [\n arcMsi,\n fabricMsi,\n appServiceMsi2019,\n appServiceMsi2017,\n cloudShellMsi,\n tokenExchangeMsi,\n imdsMsi,\n ];\n\n for (const msi of MSIs) {\n if (\n await msi.isAvailable({\n scopes,\n identityClient: this.isAvailableIdentityClient,\n clientId: this.clientId,\n resourceId: this.resourceId,\n getTokenOptions,\n })\n ) {\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 getTokenOptions?: GetTokenOptions,\n ): Promise<MSIToken | null> {\n const { span, updatedOptions } = tracingClient.startSpan(\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, updatedOptions);\n return availableMSI.getToken(\n {\n identityClient: this.identityClient,\n scopes,\n clientId: this.clientId,\n resourceId: this.resourceId,\n retryConfig: this.msiRetryConfig,\n },\n updatedOptions,\n );\n } catch (err: any) {\n span.setStatus({\n status: \"error\",\n error: err,\n });\n throw err;\n } finally {\n span.end();\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n let result: AccessToken | null = null;\n const { span, updatedOptions } = tracingClient.startSpan(\n `ManagedIdentityCredential.getToken`,\n 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 const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);\n if (availableMSI.name === \"tokenExchangeMsi\") {\n result = await this.authenticateManagedIdentity(scopes, updatedOptions);\n } else {\n const appTokenParameters: AppTokenProviderParameters = {\n correlationId: this.identityClient.getCorrelationId(),\n tenantId: options?.tenantId || \"managed_identity\",\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n claims: options?.claims,\n };\n\n // Added a check to see if SetAppTokenProvider was already defined.\n this.initializeSetAppTokenProvider();\n const authenticationResult = await this.confidentialApp.acquireTokenByClientCredential({\n ...appTokenParameters,\n });\n result = this.handleResult(scopes, authenticationResult || undefined);\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: any) {\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 status: \"error\",\n error: err,\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: 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: Unavailable. No managed identity endpoint found. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\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 // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential: Unavailable. Network unreachable. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\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 /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n private handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n this.ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n };\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n }\n\n private initializeSetAppTokenProvider(): void {\n if (!this.isAppTokenProviderInitialized) {\n this.confidentialApp.SetAppTokenProvider(async (appTokenProviderParameters) => {\n logger.info(\n `SetAppTokenProvider invoked with parameters- ${JSON.stringify(\n appTokenProviderParameters,\n )}`,\n );\n const getTokenOptions: GetTokenOptions = {\n ...appTokenProviderParameters,\n };\n logger.info(\n `authenticateManagedIdentity invoked with scopes- ${JSON.stringify(\n appTokenProviderParameters.scopes,\n )} and getTokenOptions - ${JSON.stringify(getTokenOptions)}`,\n );\n const resultToken = await this.authenticateManagedIdentity(\n appTokenProviderParameters.scopes,\n getTokenOptions,\n );\n\n if (resultToken) {\n logger.info(`SetAppTokenProvider will save the token in cache`);\n\n const expiresInSeconds = resultToken?.expiresOnTimestamp\n ? Math.floor((resultToken.expiresOnTimestamp - Date.now()) / 1000)\n : 0;\n return {\n accessToken: resultToken?.token,\n expiresInSeconds,\n };\n } else {\n logger.info(\n `SetAppTokenProvider token has \"no_access_token_returned\" as the saved token`,\n );\n return {\n accessToken: \"no_access_token_returned\",\n expiresInSeconds: 0,\n };\n }\n });\n this.isAppTokenProviderInitialized = true;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"legacyMsiProvider.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/legacyMsiProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAA8B,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AAC7F,OAAO,EACL,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAElF,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBA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A6E,CAC9E,CAAC;oBACF,OAAO;wBACL,WAAW,EAAE,0BAA0B;wBACvC,gBAAgB,EAAE,CAAC;qBACpB,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,6BAA6B,GAAG,IAAI,CAAC;QAC5C,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AppTokenProviderParameters, ConfidentialClientApplication } from \"@azure/msal-node\";\nimport {\n AuthenticationError,\n AuthenticationRequiredError,\n CredentialUnavailableError,\n} from \"../../errors\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { MsalResult, MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { cloudShellMsi } from \"./cloudShellMsi\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\n\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { appServiceMsi2017 } from \"./appServiceMsi2017\";\nimport { appServiceMsi2019 } from \"./appServiceMsi2019\";\nimport { arcMsi } from \"./arcMsi\";\nimport { fabricMsi } from \"./fabricMsi\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { getMSALLogLevel } from \"../../msal/utils\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n// As part of the migration of Managed Identity to MSAL, this legacy provider captures the existing behavior\n// ported over from the ManagedIdentityCredential verbatim. This is to ensure that the existing behavior\n// is maintained while the new implementation is being tested and validated.\n// https://github.com/Azure/azure-sdk-for-js/issues/30189 tracks deleting this provider once it is no longer needed.\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n}\n\nexport class LegacyMsiProvider {\n private identityClient: IdentityClient;\n private clientId: string | undefined;\n private resourceId: string | undefined;\n private isEndpointUnavailable: boolean | null = null;\n private isAvailableIdentityClient: IdentityClient;\n private confidentialApp: ConfidentialClientApplication;\n private isAppTokenProviderInitialized: boolean = false;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options?: TokenCredentialOptions,\n ) {\n let _options: TokenCredentialOptions | undefined;\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = (clientIdOrOptions as ManagedIdentityCredentialOptions)?.clientId;\n _options = clientIdOrOptions;\n }\n this.resourceId = (_options as ManagedIdentityCredentialOptions)?.resourceId;\n // For JavaScript users.\n if (this.clientId && this.resourceId) {\n throw new Error(\n `ManagedIdentityCredential - Client Id and Resource Id can't be provided at the same time.`,\n );\n }\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n this.identityClient = new IdentityClient(_options);\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n /** authority host validation and metadata discovery to be skipped in managed identity\n * since this wasn't done previously before adding token cache support\n */\n this.confidentialApp = new ConfidentialClientApplication({\n auth: {\n authority: \"https://login.microsoftonline.com/managed_identity\",\n clientId: this.clientId ?? DeveloperSignOnClientId,\n clientSecret: \"dummy-secret\",\n cloudDiscoveryMetadata:\n '{\"tenant_discovery_endpoint\":\"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration\",\"api-version\":\"1.1\",\"metadata\":[{\"preferred_network\":\"login.microsoftonline.com\",\"preferred_cache\":\"login.windows.net\",\"aliases\":[\"login.microsoftonline.com\",\"login.windows.net\",\"login.microsoft.com\",\"sts.windows.net\"]},{\"preferred_network\":\"login.partner.microsoftonline.cn\",\"preferred_cache\":\"login.partner.microsoftonline.cn\",\"aliases\":[\"login.partner.microsoftonline.cn\",\"login.chinacloudapi.cn\"]},{\"preferred_network\":\"login.microsoftonline.de\",\"preferred_cache\":\"login.microsoftonline.de\",\"aliases\":[\"login.microsoftonline.de\"]},{\"preferred_network\":\"login.microsoftonline.us\",\"preferred_cache\":\"login.microsoftonline.us\",\"aliases\":[\"login.microsoftonline.us\",\"login.usgovcloudapi.net\"]},{\"preferred_network\":\"login-us.microsoftonline.com\",\"preferred_cache\":\"login-us.microsoftonline.com\",\"aliases\":[\"login-us.microsoftonline.com\"]}]}',\n authorityMetadata:\n '{\"token_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_post\",\"private_key_jwt\",\"client_secret_basic\"],\"jwks_uri\":\"https://login.microsoftonline.com/common/discovery/v2.0/keys\",\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],\"subject_types_supported\":[\"pairwise\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"response_types_supported\":[\"code\",\"id_token\",\"code id_token\",\"id_token token\"],\"scopes_supported\":[\"openid\",\"profile\",\"email\",\"offline_access\"],\"issuer\":\"https://login.microsoftonline.com/{tenantid}/v2.0\",\"request_uri_parameter_supported\":false,\"userinfo_endpoint\":\"https://graph.microsoft.com/oidc/userinfo\",\"authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/authorize\",\"device_authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/devicecode\",\"http_logout_supported\":true,\"frontchannel_logout_supported\":true,\"end_session_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/logout\",\"claims_supported\":[\"sub\",\"iss\",\"cloud_instance_name\",\"cloud_instance_host_name\",\"cloud_graph_host_name\",\"msgraph_host\",\"aud\",\"exp\",\"iat\",\"auth_time\",\"acr\",\"nonce\",\"preferred_username\",\"name\",\"tid\",\"ver\",\"at_hash\",\"c_hash\",\"email\"],\"kerberos_endpoint\":\"https://login.microsoftonline.com/common/kerberos\",\"tenant_region_scope\":null,\"cloud_instance_name\":\"microsoftonline.com\",\"cloud_graph_host_name\":\"graph.windows.net\",\"msgraph_host\":\"graph.microsoft.com\",\"rbac_url\":\"https://pas.windows.net\"}',\n clientCapabilities: [],\n },\n system: {\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n },\n },\n });\n }\n\n private cachedMSI: MSI | undefined;\n\n private async cachedAvailableMSI(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSI> {\n if (this.cachedMSI) {\n return this.cachedMSI;\n }\n\n const MSIs = [\n arcMsi,\n fabricMsi,\n appServiceMsi2019,\n appServiceMsi2017,\n cloudShellMsi,\n tokenExchangeMsi,\n imdsMsi,\n ];\n\n for (const msi of MSIs) {\n if (\n await msi.isAvailable({\n scopes,\n identityClient: this.isAvailableIdentityClient,\n clientId: this.clientId,\n resourceId: this.resourceId,\n getTokenOptions,\n })\n ) {\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 getTokenOptions?: GetTokenOptions,\n ): Promise<MSIToken | null> {\n const { span, updatedOptions } = tracingClient.startSpan(\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, updatedOptions);\n return availableMSI.getToken(\n {\n identityClient: this.identityClient,\n scopes,\n clientId: this.clientId,\n resourceId: this.resourceId,\n retryConfig: this.msiRetryConfig,\n },\n updatedOptions,\n );\n } catch (err: any) {\n span.setStatus({\n status: \"error\",\n error: err,\n });\n throw err;\n } finally {\n span.end();\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n let result: AccessToken | null = null;\n const { span, updatedOptions } = tracingClient.startSpan(\n `ManagedIdentityCredential.getToken`,\n 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 const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);\n if (availableMSI.name === \"tokenExchangeMsi\") {\n result = await this.authenticateManagedIdentity(scopes, updatedOptions);\n } else {\n const appTokenParameters: AppTokenProviderParameters = {\n correlationId: this.identityClient.getCorrelationId(),\n tenantId: options?.tenantId || \"managed_identity\",\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n claims: options?.claims,\n };\n\n // Added a check to see if SetAppTokenProvider was already defined.\n this.initializeSetAppTokenProvider();\n const authenticationResult = await this.confidentialApp.acquireTokenByClientCredential({\n ...appTokenParameters,\n });\n result = this.handleResult(scopes, authenticationResult || undefined);\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: any) {\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 status: \"error\",\n error: err,\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: 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: Unavailable. No managed identity endpoint found. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\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 // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential: Unavailable. Network unreachable. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\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 /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n private handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n this.ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n refreshAfterTimestamp: result.refreshOn?.getTime(),\n };\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n }\n\n private initializeSetAppTokenProvider(): void {\n if (!this.isAppTokenProviderInitialized) {\n this.confidentialApp.SetAppTokenProvider(async (appTokenProviderParameters) => {\n logger.info(\n `SetAppTokenProvider invoked with parameters- ${JSON.stringify(\n appTokenProviderParameters,\n )}`,\n );\n const getTokenOptions: GetTokenOptions = {\n ...appTokenProviderParameters,\n };\n logger.info(\n `authenticateManagedIdentity invoked with scopes- ${JSON.stringify(\n appTokenProviderParameters.scopes,\n )} and getTokenOptions - ${JSON.stringify(getTokenOptions)}`,\n );\n const resultToken = await this.authenticateManagedIdentity(\n appTokenProviderParameters.scopes,\n getTokenOptions,\n );\n\n if (resultToken) {\n logger.info(`SetAppTokenProvider will save the token in cache`);\n\n const expiresInSeconds = resultToken?.expiresOnTimestamp\n ? Math.floor((resultToken.expiresOnTimestamp - Date.now()) / 1000)\n : 0;\n const refreshInSeconds = resultToken?.refreshAfterTimestamp\n ? Math.floor((resultToken.refreshAfterTimestamp - Date.now()) / 1000)\n : 0;\n return {\n accessToken: resultToken?.token,\n expiresInSeconds,\n refreshInSeconds,\n };\n } else {\n logger.info(\n `SetAppTokenProvider token has \"no_access_token_returned\" as the saved token`,\n );\n return {\n accessToken: \"no_access_token_returned\",\n expiresInSeconds: 0,\n };\n }\n });\n this.isAppTokenProviderInitialized = true;\n }\n }\n}\n"]}
@@ -79,6 +79,7 @@ export class MsalMsiProvider {
79
79
  throw new CredentialUnavailableError(`ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`);
80
80
  }
81
81
  return tracingClient.withSpan("ManagedIdentityCredential.getToken", options, async () => {
82
+ var _a;
82
83
  try {
83
84
  const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable({
84
85
  scopes,
@@ -138,6 +139,7 @@ export class MsalMsiProvider {
138
139
  return {
139
140
  expiresOnTimestamp: token.expiresOn.getTime(),
140
141
  token: token.accessToken,
142
+ refreshAfterTimestamp: (_a = token.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(),
141
143
  };
142
144
  }
143
145
  catch (err) {
@@ -1 +1 @@
1
- {"version":3,"file":"ms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\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { defaultLoggerCallback, getMSALLogLevel } from \"../../msal/utils\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { MSIConfiguration } from \"./models\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential(MSAL)\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID and is not required for system-assigned managed identities.\n */\n objectId?: string;\n}\n\nexport class MsalMsiProvider {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private objectId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options: ManagedIdentityCredentialOptions = {},\n ) {\n let _options: ManagedIdentityCredentialOptions = {};\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = clientIdOrOptions?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = _options?.resourceId;\n this.objectId = _options?.objectId;\n\n // For JavaScript users.\n const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);\n if (providedIds.length > 1) {\n throw new Error(\n `ManagedIdentityCredential - only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify(\n { clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId },\n )}`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n userAssignedObjectId: this.objectId,\n },\n system: {\n // todo: proxyUrl?\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.identityClient,\n resourceId: this.resourceId,\n });\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n logger.getToken.info(`MSAL Identity source: ${identitySource}`);\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"Attempted to use the token exchange managed identity, but received a null response.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Attempted to use the IMDS endpoint, but it is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n };\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n { cause: err },\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n { cause: err },\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw createError(\"No response.\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n"]}
1
+ {"version":3,"file":"msalMsiProvider.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/msalMsiProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAEvF,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAE1E,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAE9D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,MAAM,MAAM,GAAG,gBAAgB,CAAC,iCAAiC,CAAC,CAAC;AA4BnE,MAAM,OAAO,eAAe;IAa1B,YACE,iBAA6D,EAC7D,UAA4C,EAAE;;QATxC,mBAAc,GAAoC;YACxD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aAAa,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;QAC9D,OAAO,IAAI,CAAC;IACd,CAAC;IAED,6NAA6N;IAC7N,4CAA4C;IAC5C,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE,CAAC;QAC/C,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { defaultLoggerCallback, getMSALLogLevel } from \"../../msal/utils\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { MSIConfiguration } from \"./models\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential(MSAL)\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID and is not required for system-assigned managed identities.\n */\n objectId?: string;\n}\n\nexport class MsalMsiProvider {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private objectId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options: ManagedIdentityCredentialOptions = {},\n ) {\n let _options: ManagedIdentityCredentialOptions = {};\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = clientIdOrOptions?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = _options?.resourceId;\n this.objectId = _options?.objectId;\n\n // For JavaScript users.\n const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);\n if (providedIds.length > 1) {\n throw new Error(\n `ManagedIdentityCredential - only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify(\n { clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId },\n )}`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n userAssignedObjectId: this.objectId,\n },\n system: {\n // todo: proxyUrl?\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.identityClient,\n resourceId: this.resourceId,\n });\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n logger.getToken.info(`MSAL Identity source: ${identitySource}`);\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"Attempted to use the token exchange managed identity, but received a null response.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Attempted to use the IMDS endpoint, but it is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n refreshAfterTimestamp: token.refreshOn?.getTime(),\n };\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n { cause: err },\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n { cause: err },\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw createError(\"No response.\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n"]}
@@ -49,4 +49,29 @@ export function parseExpirationTimestamp(body) {
49
49
  }
50
50
  throw new Error(`Failed to parse token expiration from body. expires_in="${body.expires_in}", expires_on="${body.expires_on}"`);
51
51
  }
52
+ /**
53
+ * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.
54
+ * @param body - A parsed response body from the authentication endpoint.
55
+ */
56
+ export function parseRefreshTimestamp(body) {
57
+ if (body.refresh_on) {
58
+ if (typeof body.refresh_on === "number") {
59
+ return body.refresh_on * 1000;
60
+ }
61
+ if (typeof body.refresh_on === "string") {
62
+ const asNumber = +body.refresh_on;
63
+ if (!isNaN(asNumber)) {
64
+ return asNumber * 1000;
65
+ }
66
+ const asDate = Date.parse(body.refresh_on);
67
+ if (!isNaN(asDate)) {
68
+ return asDate;
69
+ }
70
+ }
71
+ throw new Error(`Failed to parse refresh_on from body. refresh_on="${body.refresh_on}"`);
72
+ }
73
+ else {
74
+ return undefined;
75
+ }
76
+ }
52
77
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAyB;IAC3D,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxB,OAAO;QACT,CAAC;QAED,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;SAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QACtC,KAAK,GAAG,MAAM,CAAC;IACjB,CAAC;IAED,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC,CAAC;AAChE,CAAC;AAeD;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAA6B;IACpE,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;IAChC,CAAC;IAED,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;QACxC,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC;QAClC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;YACrB,OAAO,QAAQ,GAAG,IAAI,CAAC;QACzB,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;YACnB,OAAO,MAAM,CAAC;QAChB,CAAC;IACH,CAAC;IAED,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;IAC7C,CAAC;IAED,MAAM,IAAI,KAAK,CACb,2DAA2D,IAAI,CAAC,UAAU,kBAAkB,IAAI,CAAC,UAAU,GAAG,CAC/G,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { DefaultScopeSuffix } from \"./constants\";\n\n/**\n * Most MSIs send requests to the IMDS endpoint, or a similar endpoint.\n * These are GET requests that require sending a `resource` parameter on the query.\n * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received.\n * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case.\n *\n * For that reason, when we encounter multiple scopes, we return undefined.\n * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors).\n */\nexport function mapScopesToResource(scopes: string | string[]): string | undefined {\n let scope = \"\";\n if (Array.isArray(scopes)) {\n if (scopes.length !== 1) {\n return;\n }\n\n scope = scopes[0];\n } else if (typeof scopes === \"string\") {\n scope = scopes;\n }\n\n if (!scope.endsWith(DefaultScopeSuffix)) {\n return scope;\n }\n\n return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n refresh_in?: number;\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseExpirationTimestamp(body: TokenResponseParsedBody): number {\n if (typeof body.expires_on === \"number\") {\n return body.expires_on * 1000;\n }\n\n if (typeof body.expires_on === \"string\") {\n const asNumber = +body.expires_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.expires_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n\n if (typeof body.expires_in === \"number\") {\n return Date.now() + body.expires_in * 1000;\n }\n\n throw new Error(\n `Failed to parse token expiration from body. expires_in=\"${body.expires_in}\", expires_on=\"${body.expires_on}\"`,\n );\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAyB;IAC3D,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxB,OAAO;QACT,CAAC;QAED,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;SAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QACtC,KAAK,GAAG,MAAM,CAAC;IACjB,CAAC;IAED,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC,CAAC;AAChE,CAA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,OAAO,QAAQ,GAAG,IAAI,CAAC;YACzB,CAAC;YAED,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC3C,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;gBACnB,OAAO,MAAM,CAAC;YAChB,CAAC;QACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,qDAAqD,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC;IAC3F,CAAC;SAAM,CAAC;QACN,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { DefaultScopeSuffix } from \"./constants\";\n\n/**\n * Most MSIs send requests to the IMDS endpoint, or a similar endpoint.\n * These are GET requests that require sending a `resource` parameter on the query.\n * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received.\n * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case.\n *\n * For that reason, when we encounter multiple scopes, we return undefined.\n * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors).\n */\nexport function mapScopesToResource(scopes: string | string[]): string | undefined {\n let scope = \"\";\n if (Array.isArray(scopes)) {\n if (scopes.length !== 1) {\n return;\n }\n\n scope = scopes[0];\n } else if (typeof scopes === \"string\") {\n scope = scopes;\n }\n\n if (!scope.endsWith(DefaultScopeSuffix)) {\n return scope;\n }\n\n return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n refresh_on?: number | string;\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseExpirationTimestamp(body: TokenResponseParsedBody): number {\n if (typeof body.expires_on === \"number\") {\n return body.expires_on * 1000;\n }\n\n if (typeof body.expires_on === \"string\") {\n const asNumber = +body.expires_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.expires_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n\n if (typeof body.expires_in === \"number\") {\n return Date.now() + body.expires_in * 1000;\n }\n\n throw new Error(\n `Failed to parse token expiration from body. expires_in=\"${body.expires_in}\", expires_on=\"${body.expires_on}\"`,\n );\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseRefreshTimestamp(body: TokenResponseParsedBody): number | undefined {\n if (body.refresh_on) {\n if (typeof body.refresh_on === \"number\") {\n return body.refresh_on * 1000;\n }\n\n if (typeof body.refresh_on === \"string\") {\n const asNumber = +body.refresh_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.refresh_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n throw new Error(`Failed to parse refresh_on from body. refresh_on=\"${body.refresh_on}\"`);\n } else {\n return undefined;\n }\n}\n"]}
@@ -31,7 +31,6 @@ export const AuthenticationErrorName = "AuthenticationError";
31
31
  * the specific failure.
32
32
  */
33
33
  export class AuthenticationError extends Error {
34
- // eslint-disable-next-line @typescript-eslint/ban-types
35
34
  constructor(statusCode, errorBody, options) {
36
35
  let errorResponse = {
37
36
  error: "unknown",
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAyDlC,SAAS,eAAe,CAAC,aAAkB;IACzC,OAAO,CACL,aAAa;QACb,OAAO,aAAa,CAAC,KAAK,KAAK,QAAQ;QACvC,OAAO,aAAa,CAAC,iBAAiB,KAAK,QAAQ,CACpD,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,4BAA4B,C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C,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CACrD,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAC/C,IAAI,CAAC,IAAI,GAAG,6BAA6B,CAAC;IAC5C,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n super(message, options);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(\n statusCode: number,\n errorBody: object | string | undefined | null,\n options?: { cause?: unknown },\n ) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"invalid_request\",\n errorDescription: `The service indicated that the request was invalid.\\n\\n${errorBody}`,\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription},`,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options,\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n /**\n * The underlying cause, if any, that caused the authentication to fail.\n */\n cause?: unknown;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions,\n ) {\n super(\n options.message,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options.cause ? { cause: options.cause } : undefined,\n );\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequ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AAE,SAAS,CAAC,WAAW;QACjC,SAAS,EAAE,SAAS,CAAC,SAAS;QAC9B,OAAO,EAAE,SAAS,CAAC,QAAQ;KAC5B,CAAC;AACJ,CAAC;AAwBD;;GAEG;AACH,MAAM,OAAO,2BAA4B,SAAQ,KAAK;IAUpD;IACE;;OAEG;IACH,OAA2C;QAE3C,KAAK,CACH,OAAO,CAAC,OAAO;QACf,2JAA2J;QAC3J,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CACrD,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAC/C,IAAI,CAAC,IAAI,GAAG,6BAA6B,CAAC;IAC5C,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n super(message, options);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n constructor(\n statusCode: number,\n errorBody: object | string | undefined | null,\n options?: { cause?: unknown },\n ) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"invalid_request\",\n errorDescription: `The service indicated that the request was invalid.\\n\\n${errorBody}`,\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription},`,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options,\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n /**\n * The underlying cause, if any, that caused the authentication to fail.\n */\n cause?: unknown;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions,\n ) {\n super(\n options.message,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options.cause ? { cause: options.cause } : undefined,\n );\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequiredError\";\n }\n}\n"]}
@@ -99,6 +99,7 @@ export class MsalBrowser {
99
99
  * If the token received is invalid, an error will be thrown depending on what's missing.
100
100
  */
101
101
  handleResult(scopes, result, getTokenOptions) {
102
+ var _a;
102
103
  if (result === null || result === void 0 ? void 0 : result.account) {
103
104
  this.account = msalToPublic(this.clientId, result.account);
104
105
  }
@@ -107,6 +108,7 @@ export class MsalBrowser {
107
108
  return {
108
109
  token: result.accessToken,
109
110
  expiresOnTimestamp: result.expiresOn.getTime(),
111
+ refreshAfterTimestamp: (_a = result.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(),
110
112
  };
111
113
  }
112
114
  }
@@ -1 +1 @@
1
- {"version":3,"file":"msalBrowserCommon.js","sourceRoot":"","sources":["../../../../src/msal/browserFlows/msalBrowserCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AACvF,OAAO,EAAoB,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAErE,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACjG,OAAO,EACL,yBAAyB,EACzB,mCAAmC,EACnC,eAAe,GAChB,MAAM,0BAA0B,CAAC;AAIlC,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAqClD;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CACtC,OAA+B;IAE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OAAO;oBACxB,OAAO,EACL,uFAAuF;iBAC1F,CAAC,CAAC;YACL,CAAC;YACD,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,oEAAoE,IAAI,CAAC,UAAU,EAAE,CACtF,CAAC;YACF,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;OAIG;IACO,YAAY,CACpB,MAAyB,EACzB,MAAmB,EACnB,eAAiC;QAEjC,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,OAAO,GAAG,YAAY,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;QAC7D,CAAC;QACD,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC;QACtD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;QACjD,OAAO;YACL,KAAK,EAAE,MAAM,CAAC,WAAW;YACzB,kBAAkB,EAAE,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE;SAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalBrowser from \"@azure/msal-browser\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRecord, MsalResult } from \"../types\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { CredentialLogger, formatSuccess } from \"../../util/logging\";\nimport { MsalFlow, MsalFlowOptions } from \"./flows\";\nimport { ensureValidMsalToken, getAuthority, getKnownAuthorities, msalToPublic } from \"../utils\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils\";\n\nimport { BrowserLoginStyle } from \"../../credentials/interactiveBrowserCredentialOptions\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { DefaultTenantId } from \"../../constants\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\nimport { MultiTenantTokenCredentialOptions } from \"../../credentials/multiTenantTokenCredentialOptions\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types take.\n * Some properties might not be used by some flow types.\n */\nexport interface MsalBrowserFlowOptions extends MsalFlowOptions {\n tokenCredentialOptions: MultiTenantTokenCredentialOptions;\n redirectUri?: string;\n loginStyle: BrowserLoginStyle;\n loginHint?: string;\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: LogPolicyOptions & {\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n allowLoggingAccountIdentifiers?: boolean;\n /**\n * Allows logging personally identifiable information for customer support.\n */\n enableUnsafeSupportLogging?: boolean;\n };\n}\n\n/**\n * The common methods we use to work with the MSAL browser flows.\n * @internal\n */\nexport interface MsalBrowserFlow extends MsalFlow {\n login(scopes?: string[]): Promise<AuthenticationRecord | undefined>;\n handleRedirect(): Promise<AuthenticationRecord | undefined>;\n}\n\n/**\n * Generates a MSAL configuration that generally works for browsers\n * @internal\n */\nexport function defaultBrowserMsalConfig(\n options: MsalBrowserFlowOptions,\n): msalBrowser.Configuration {\n const tenantId = options.tenantId || DefaultTenantId;\n const authority = getAuthority(tenantId, options.authorityHost);\n return {\n auth: {\n clientId: options.clientId!,\n authority,\n knownAuthorities: getKnownAuthorities(tenantId, authority, options.disableInstanceDiscovery),\n // If the users picked redirect as their login style,\n // but they didn't provide a redirectUri,\n // we can try to use the current page we're in as a default value.\n redirectUri: options.redirectUri || self.location.origin,\n },\n };\n}\n\n/**\n * MSAL partial base client for the browsers.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalBrowser implements MsalBrowserFlow {\n protected loginStyle: BrowserLoginStyle;\n protected clientId: string;\n protected tenantId: string;\n protected additionallyAllowedTenantIds: string[];\n protected authorityHost?: string;\n protected account: AuthenticationRecord | undefined;\n protected msalConfig: msalBrowser.Configuration;\n protected disableAutomaticAuthentication?: boolean;\n protected app?: msalBrowser.IPublicClientApplication;\n protected logger: CredentialLogger;\n\n constructor(options: MsalBrowserFlowOptions) {\n this.logger = options.logger;\n this.loginStyle = options.loginStyle;\n if (!options.clientId) {\n throw new CredentialUnavailableError(\"A client ID is required in browsers\");\n }\n this.clientId = options.clientId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants,\n );\n this.tenantId = resolveTenantId(this.logger, options.tenantId, options.clientId);\n this.authorityHost = options.authorityHost;\n this.msalConfig = defaultBrowserMsalConfig(options);\n this.disableAutomaticAuthentication = options.disableAutomaticAuthentication;\n\n if (options.authenticationRecord) {\n this.account = {\n ...options.authenticationRecord,\n tenantId: this.tenantId,\n };\n }\n }\n\n /**\n * In the browsers we don't need to init()\n */\n async init(): Promise<void> {\n // Nothing to do here.\n }\n\n /**\n * Attempts to handle a redirection request the least amount of times possible.\n */\n public abstract handleRedirect(): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Clears MSAL's cache.\n */\n async logout(): Promise<void> {\n this.app?.logout();\n }\n\n /**\n * Uses MSAL to retrieve the active account.\n */\n public abstract getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Uses MSAL to trigger a redirect or a popup login.\n */\n public abstract login(scopes?: string | string[]): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Attempts to retrieve a token from cache.\n */\n public abstract getTokenSilent(scopes: string[]): Promise<AccessToken>;\n\n /**\n * Attempts to retrieve the token in the browser.\n */\n protected abstract doGetToken(scopes: string[]): Promise<AccessToken>;\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {},\n ): Promise<AccessToken> {\n const tenantId =\n processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds) ||\n this.tenantId;\n\n if (!options.authority) {\n options.authority = getAuthority(tenantId, this.authorityHost);\n }\n\n // We ensure that redirection is handled at this point.\n await this.handleRedirect();\n\n if (!(await this.getActiveAccount()) && !this.disableAutomaticAuthentication) {\n await this.login(scopes);\n }\n return this.getTokenSilent(scopes).catch((err) => {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (options?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n this.logger.info(\n `Silent authentication failed, falling back to interactive method ${this.loginStyle}`,\n );\n return this.doGetToken(scopes);\n });\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n protected handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n if (result?.account) {\n this.account = msalToPublic(this.clientId, result.account);\n }\n ensureValidMsalToken(scopes, result, getTokenOptions);\n this.logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n };\n }\n}\n"]}
1
+ {"version":3,"file":"msalBrowserCommon.js","sourceRoot":"","sources":["../../../../src/msal/browserFlows/msalBrowserCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AACvF,OAAO,EAAoB,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAErE,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACjG,OAAO,EACL,yBAAyB,EACzB,mCAAmC,EACnC,eAAe,GAChB,MAAM,0BAA0B,CAAC;AAIlC,OAAO,EAA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CAAE,8BAA8B,EAAE,CAAC;gBAC5C,MAAM,IAAI,2BAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe,EAAE,OAAO;oBACxB,OAAO,EACL,uFAAuF;iBAC1F,CAAC,CAAC;YACL,CAAC;YACD,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,oEAAoE,IAAI,CAAC,UAAU,EAAE,CACtF,CAAC;YACF,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;OAIG;IACO,YAAY,CACpB,MAAyB,EACzB,MAAmB,EACnB,eAAiC;;QAEjC,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,OAAO,GAAG,YAAY,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;QAC7D,CAAC;QACD,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC;QACtD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;QACjD,OAAO;YACL,KAAK,EAAE,MAAM,CAAC,WAAW;YACzB,kBAAkB,EAAE,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE;YAC9C,qBAAqB,EAAE,MAAA,MAAM,CAAC,SAAS,0CAAE,OAAO,EAAE;SACnD,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalBrowser from \"@azure/msal-browser\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRecord, MsalResult } from \"../types\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { CredentialLogger, formatSuccess } from \"../../util/logging\";\nimport { MsalFlow, MsalFlowOptions } from \"./flows\";\nimport { ensureValidMsalToken, getAuthority, getKnownAuthorities, msalToPublic } from \"../utils\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils\";\n\nimport { BrowserLoginStyle } from \"../../credentials/interactiveBrowserCredentialOptions\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { DefaultTenantId } from \"../../constants\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\nimport { MultiTenantTokenCredentialOptions } from \"../../credentials/multiTenantTokenCredentialOptions\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types take.\n * Some properties might not be used by some flow types.\n */\nexport interface MsalBrowserFlowOptions extends MsalFlowOptions {\n tokenCredentialOptions: MultiTenantTokenCredentialOptions;\n redirectUri?: string;\n loginStyle: BrowserLoginStyle;\n loginHint?: string;\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: LogPolicyOptions & {\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n allowLoggingAccountIdentifiers?: boolean;\n /**\n * Allows logging personally identifiable information for customer support.\n */\n enableUnsafeSupportLogging?: boolean;\n };\n}\n\n/**\n * The common methods we use to work with the MSAL browser flows.\n * @internal\n */\nexport interface MsalBrowserFlow extends MsalFlow {\n login(scopes?: string[]): Promise<AuthenticationRecord | undefined>;\n handleRedirect(): Promise<AuthenticationRecord | undefined>;\n}\n\n/**\n * Generates a MSAL configuration that generally works for browsers\n * @internal\n */\nexport function defaultBrowserMsalConfig(\n options: MsalBrowserFlowOptions,\n): msalBrowser.Configuration {\n const tenantId = options.tenantId || DefaultTenantId;\n const authority = getAuthority(tenantId, options.authorityHost);\n return {\n auth: {\n clientId: options.clientId!,\n authority,\n knownAuthorities: getKnownAuthorities(tenantId, authority, options.disableInstanceDiscovery),\n // If the users picked redirect as their login style,\n // but they didn't provide a redirectUri,\n // we can try to use the current page we're in as a default value.\n redirectUri: options.redirectUri || self.location.origin,\n },\n };\n}\n\n/**\n * MSAL partial base client for the browsers.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalBrowser implements MsalBrowserFlow {\n protected loginStyle: BrowserLoginStyle;\n protected clientId: string;\n protected tenantId: string;\n protected additionallyAllowedTenantIds: string[];\n protected authorityHost?: string;\n protected account: AuthenticationRecord | undefined;\n protected msalConfig: msalBrowser.Configuration;\n protected disableAutomaticAuthentication?: boolean;\n protected app?: msalBrowser.IPublicClientApplication;\n protected logger: CredentialLogger;\n\n constructor(options: MsalBrowserFlowOptions) {\n this.logger = options.logger;\n this.loginStyle = options.loginStyle;\n if (!options.clientId) {\n throw new CredentialUnavailableError(\"A client ID is required in browsers\");\n }\n this.clientId = options.clientId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants,\n );\n this.tenantId = resolveTenantId(this.logger, options.tenantId, options.clientId);\n this.authorityHost = options.authorityHost;\n this.msalConfig = defaultBrowserMsalConfig(options);\n this.disableAutomaticAuthentication = options.disableAutomaticAuthentication;\n\n if (options.authenticationRecord) {\n this.account = {\n ...options.authenticationRecord,\n tenantId: this.tenantId,\n };\n }\n }\n\n /**\n * In the browsers we don't need to init()\n */\n async init(): Promise<void> {\n // Nothing to do here.\n }\n\n /**\n * Attempts to handle a redirection request the least amount of times possible.\n */\n public abstract handleRedirect(): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Clears MSAL's cache.\n */\n async logout(): Promise<void> {\n this.app?.logout();\n }\n\n /**\n * Uses MSAL to retrieve the active account.\n */\n public abstract getActiveAccount(): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Uses MSAL to trigger a redirect or a popup login.\n */\n public abstract login(scopes?: string | string[]): Promise<AuthenticationRecord | undefined>;\n\n /**\n * Attempts to retrieve a token from cache.\n */\n public abstract getTokenSilent(scopes: string[]): Promise<AccessToken>;\n\n /**\n * Attempts to retrieve the token in the browser.\n */\n protected abstract doGetToken(scopes: string[]): Promise<AccessToken>;\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {},\n ): Promise<AccessToken> {\n const tenantId =\n processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds) ||\n this.tenantId;\n\n if (!options.authority) {\n options.authority = getAuthority(tenantId, this.authorityHost);\n }\n\n // We ensure that redirection is handled at this point.\n await this.handleRedirect();\n\n if (!(await this.getActiveAccount()) && !this.disableAutomaticAuthentication) {\n await this.login(scopes);\n }\n return this.getTokenSilent(scopes).catch((err) => {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (options?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n this.logger.info(\n `Silent authentication failed, falling back to interactive method ${this.loginStyle}`,\n );\n return this.doGetToken(scopes);\n });\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n protected handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n if (result?.account) {\n this.account = msalToPublic(this.clientId, result.account);\n }\n ensureValidMsalToken(scopes, result, getTokenOptions);\n this.logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n refreshAfterTimestamp: result.refreshOn?.getTime(),\n };\n }\n}\n"]}