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C/B,MAAM,KAAK,GAAG,IAAI,0BAA0B,CAC1C,GAAG,yBAAyB,CAAC,IAAI,+DAA+D,GAAG,CAAC,OAAO,EAAE,CAC9G,CAAC;gBAEF,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;gBACjD,MAAM,KAAK,CAAC;aACb;YAED,wEAAwE;YACxE,gFAAgF;YAChF,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,EAAE;gBAC1B,MAAM,IAAI,0BAA0B,CAClC,GAAG,yBAAyB,CAAC,IAAI,yFAAyF,GAAG,CAAC,OAAO,EAAE,CACxI,CAAC;aACH;YAED,kFAAkF;YAClF,8DAA8D;YAC9D,IAAI,GAAG,CAAC,UAAU,KAAK,SAAS,EAAE;gBAChC,MAAM,IAAI,0BAA0B,CAClC,GAAG,yBAAyB,CAAC,IAAI,oCAAoC,GAAG,CAAC,OAAO,EAAE,CACnF,CAAC;aACH;YAED,0CAA0C;YAC1C,MAAM,IAAI,mBAAmB,CAAC,GAAG,CAAC,UAAU,EAAE;gBAC5C,KAAK,EAAE,GAAG,yBAAyB,CAAC,IAAI,yBAAyB;gBACjE,iBAAiB,EAAE,GAAG,CAAC,OAAO;aAC/B,CAAC,CAAC;SACJ;gBAAS;YACR,sFAAsF;YACtF,IAAI,CAAC,GAAG,EAAE,CAAC;SACZ;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../../errors\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { appServiceMsi2017 } from \"./appServiceMsi2017\";\nimport { tracingClient } from \"../../util/tracing\";\nimport { cloudShellMsi } from \"./cloudShellMsi\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { MSI } from \"./models\";\nimport { arcMsi } from \"./arcMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { fabricMsi } from \"./fabricMsi\";\nimport { appServiceMsi2019 } from \"./appServiceMsi2019\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `clientId` and not `resourceId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `resourceId` and not `clientId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialResourceIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId: string;\n}\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private clientId: string | undefined;\n private resourceId: string | undefined;\n private isEndpointUnavailable: boolean | null = null;\n private isAvailableIdentityClient: IdentityClient;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with clientId\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with Resource Id\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions,\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 ManagedIdentityCredentialClientIdOptions)?.clientId;\n _options = clientIdOrOptions;\n }\n this.resourceId = (_options as ManagedIdentityCredentialResourceIdOptions)?.resourceId;\n // For JavaScript users.\n if (this.clientId && this.resourceId) {\n throw new Error(\n `${ManagedIdentityCredential.name} - Client Id and Resource Id can't be provided at the same time.`\n );\n }\n this.identityClient = new IdentityClient(_options);\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n }\n\n private cachedMSI: MSI | undefined;\n\n private async cachedAvailableMSI(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions\n ): Promise {\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(\n `${ManagedIdentityCredential.name} - No MSI credential available`\n );\n }\n\n private async authenticateManagedIdentity(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions\n ): Promise {\n const { span, updatedOptions } = tracingClient.startSpan(\n `${ManagedIdentityCredential.name}.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\n return availableMSI.getToken(\n {\n identityClient: this.identityClient,\n scopes,\n clientId: this.clientId,\n resourceId: this.resourceId,\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 Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise {\n let result: AccessToken | null = null;\n\n const { span, updatedOptions } = tracingClient.startSpan(\n `${ManagedIdentityCredential.name}.getToken`,\n options\n );\n\n try {\n // isEndpointAvailable can be true, false, or null,\n // If it's null, it means we don't yet know whether\n // the endpoint is available and need to check for it.\n if (this.isEndpointUnavailable !== true) {\n result = await this.authenticateManagedIdentity(scopes, updatedOptions);\n\n if (result === null) {\n // If authenticateManagedIdentity returns null,\n // it means no MSI endpoints are available.\n // If so, we avoid trying to reach to them in future requests.\n this.isEndpointUnavailable = true;\n\n // It also means that the endpoint answered with either 200 or 201 (see the sendTokenRequest method),\n // yet we had no access token. For this reason, we'll throw once with a specific message:\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint was reached, yet no tokens were received.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // Since `authenticateManagedIdentity` didn't throw, and the result was not null,\n // We will assume that this endpoint is reachable from this point forward,\n // and avoid pinging again to it.\n this.isEndpointUnavailable = false;\n } else {\n // We've previously determined that the endpoint was unavailable,\n // either because it was unreachable or permanently unable to authenticate.\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint is not currently available\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err: 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.name}: 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.name}: Unavailable. No managed identity endpoint found. Message: ${err.message}`\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // If err.statusCode has a value of 400, it comes from sendTokenRequest,\n // and it means that the endpoint is working, but that no identity is available.\n if (err.statusCode === 400) {\n throw new CredentialUnavailableError(\n `${ManagedIdentityCredential.name}: The managed identity endpoint is indicating there's no available identity. Message: ${err.message}`\n );\n }\n\n // If the error has no status code, we can assume there was no available identity.\n // This will throw silently during any ChainedTokenCredential.\n if (err.statusCode === undefined) {\n throw new CredentialUnavailableError(\n `${ManagedIdentityCredential.name}: 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.name} 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"]}