Add extracted source directory and README navigation

This commit is contained in:
Shawn Bot
2026-03-31 14:56:06 +00:00
parent 6252bb6eb5
commit 91e01d755b
4757 changed files with 984951 additions and 0 deletions

View File

@@ -0,0 +1,109 @@
/*! @azure/msal-node v3.8.1 2025-10-29 */
'use strict';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// MSI Constants. Docs for MSI are available here https://docs.microsoft.com/azure/app-service/overview-managed-identity
const APP_SERVICE_MSI_API_VERSION = "2019-08-01";
/**
* Azure App Service Managed Identity Source implementation.
*
* This class provides managed identity authentication for applications running in Azure App Service.
* It uses the local metadata service endpoint available within App Service environments to obtain
* access tokens without requiring explicit credentials.
*
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AppServiceManagedIdentitySource.cs
*/
class AppService extends BaseManagedIdentitySource {
/**
* Creates a new instance of the AppService managed identity source.
*
* @param logger - Logger instance for diagnostic output
* @param nodeStorage - Node.js storage implementation for caching
* @param networkClient - Network client for making HTTP requests
* @param cryptoProvider - Cryptographic operations provider
* @param disableInternalRetries - Whether to disable internal retry logic
* @param identityEndpoint - The App Service identity endpoint URL
* @param identityHeader - The secret header value required for authentication
*/
constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) {
super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
this.identityEndpoint = identityEndpoint;
this.identityHeader = identityHeader;
}
/**
* Retrieves the required environment variables for App Service managed identity.
*
* App Service managed identity requires two environment variables:
* - IDENTITY_ENDPOINT: The URL of the local metadata service
* - IDENTITY_HEADER: A secret header value for authentication
*
* @returns An array containing [identityEndpoint, identityHeader] values from environment variables.
* Either value may be undefined if the environment variable is not set.
*/
static getEnvironmentVariables() {
const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER];
return [identityEndpoint, identityHeader];
}
/**
* Attempts to create an AppService managed identity source if the environment supports it.
*
* This method checks for the presence of required environment variables and validates
* the identity endpoint URL. If the environment is not suitable for App Service managed
* identity (missing environment variables or invalid endpoint), it returns null.
*
* @param logger - Logger instance for diagnostic output
* @param nodeStorage - Node.js storage implementation for caching
* @param networkClient - Network client for making HTTP requests
* @param cryptoProvider - Cryptographic operations provider
* @param disableInternalRetries - Whether to disable internal retry logic
*
* @returns A new AppService instance if the environment is suitable, null otherwise
*/
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
const [identityEndpoint, identityHeader] = AppService.getEnvironmentVariables();
// if either of the identity endpoint or identity header variables are undefined, this MSI provider is unavailable.
if (!identityEndpoint || !identityHeader) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.APP_SERVICE} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}' and '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variables are not defined.`);
return null;
}
const validatedIdentityEndpoint = AppService.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.APP_SERVICE, logger);
logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.APP_SERVICE} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.APP_SERVICE} managed identity.`);
return new AppService(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader);
}
/**
* Creates a managed identity token request for the App Service environment.
*
* This method constructs an HTTP GET request to the App Service identity endpoint
* with the required headers, query parameters, and managed identity configuration.
* The request includes the secret header for authentication and appropriate API version.
*
* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
* @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity
*
* @returns A configured ManagedIdentityRequestParameters object ready for network execution
*/
createRequest(resource, managedIdentityId) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
request.headers[ManagedIdentityHeaders.APP_SERVICE_SECRET_HEADER_NAME] =
this.identityHeader;
request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] =
APP_SERVICE_MSI_API_VERSION;
request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] =
resource;
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
}
// bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
return request;
}
}
export { AppService };
//# sourceMappingURL=AppService.mjs.map

View File

@@ -0,0 +1,248 @@
/*! @azure/msal-node v3.8.1 2025-10-29 */
'use strict';
import { HttpStatus, EncodingTypes, AuthError, createClientAuthError, ClientAuthErrorCodes } from '@azure/msal-common/node';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, HttpMethod, ManagedIdentityHeaders, ManagedIdentityQueryParameters, AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES } from '../../utils/Constants.mjs';
import { accessSync, constants, statSync, readFileSync } from 'fs';
import path from 'path';
import { unableToCreateAzureArc, wwwAuthenticateHeaderMissing, wwwAuthenticateHeaderUnsupportedFormat, platformNotSupported, invalidFileExtension, invalidFilePath, unableToReadSecretFile, invalidSecret } from '../../error/ManagedIdentityErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const ARC_API_VERSION = "2019-11-01";
const DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT = "http://127.0.0.1:40342/metadata/identity/oauth2/token";
const HIMDS_EXECUTABLE_HELPER_STRING = "N/A: himds executable exists";
const SUPPORTED_AZURE_ARC_PLATFORMS = {
win32: `${process.env["ProgramData"]}\\AzureConnectedMachineAgent\\Tokens\\`,
linux: "/var/opt/azcmagent/tokens/",
};
const AZURE_ARC_FILE_DETECTION = {
win32: `${process.env["ProgramFiles"]}\\AzureConnectedMachineAgent\\himds.exe`,
linux: "/opt/azcmagent/bin/himds",
};
/**
* Azure Arc managed identity source implementation for acquiring tokens from Azure Arc-enabled servers.
*
* This class provides managed identity authentication for applications running on Azure Arc-enabled servers
* by communicating with the local Hybrid Instance Metadata Service (HIMDS). It supports both environment
* variable-based configuration and automatic detection through the HIMDS executable.
*
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AzureArcManagedIdentitySource.cs
*/
class AzureArc extends BaseManagedIdentitySource {
/**
* Creates a new instance of the AzureArc managed identity source.
*
* @param logger - Logger instance for capturing telemetry and diagnostic information
* @param nodeStorage - Storage implementation for caching tokens and metadata
* @param networkClient - Network client for making HTTP requests to the identity endpoint
* @param cryptoProvider - Cryptographic operations provider for token validation and encryption
* @param disableInternalRetries - Flag to disable automatic retry logic for failed requests
* @param identityEndpoint - The Azure Arc identity endpoint URL for token requests
*/
constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) {
super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
this.identityEndpoint = identityEndpoint;
}
/**
* Retrieves and validates Azure Arc environment variables for managed identity configuration.
*
* This method checks for IDENTITY_ENDPOINT and IMDS_ENDPOINT environment variables.
* If either is missing, it attempts to detect the Azure Arc environment by checking for
* the HIMDS executable at platform-specific paths. On successful detection, it returns
* the default identity endpoint and a helper string indicating file-based detection.
*
* @returns An array containing [identityEndpoint, imdsEndpoint] where both values are
* strings if Azure Arc is available, or undefined if not available.
*/
static getEnvironmentVariables() {
let identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
let imdsEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT];
// if either of the identity or imds endpoints are undefined, check if the himds executable exists
if (!identityEndpoint || !imdsEndpoint) {
// get the expected Windows or Linux file path of the himds executable
const fileDetectionPath = AZURE_ARC_FILE_DETECTION[process.platform];
try {
/*
* check if the himds executable exists and its permissions allow it to be read
* returns undefined if true, throws an error otherwise
*/
accessSync(fileDetectionPath, constants.F_OK | constants.R_OK);
identityEndpoint = DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT;
imdsEndpoint = HIMDS_EXECUTABLE_HELPER_STRING;
}
catch (err) {
/*
* do nothing
* accessSync returns undefined on success, and throws an error on failure
*/
}
}
return [identityEndpoint, imdsEndpoint];
}
/**
* Attempts to create an AzureArc managed identity source instance.
*
* Validates the Azure Arc environment by checking environment variables
* and performing file-based detection. It ensures that only system-assigned managed identities
* are supported for Azure Arc scenarios. The method performs comprehensive validation of
* endpoint URLs and logs detailed information about the detection process.
*
* @param logger - Logger instance for capturing creation and validation steps
* @param nodeStorage - Storage implementation for the managed identity source
* @param networkClient - Network client for HTTP communication
* @param cryptoProvider - Cryptographic operations provider
* @param disableInternalRetries - Whether to disable automatic retry mechanisms
* @param managedIdentityId - The managed identity configuration, must be system-assigned
*
* @returns AzureArc instance if the environment supports Azure Arc managed identity, null otherwise
*
* @throws {ManagedIdentityError} When a user-assigned managed identity is specified (not supported for Azure Arc)
*/
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
const [identityEndpoint, imdsEndpoint] = AzureArc.getEnvironmentVariables();
// if either of the identity or imds endpoints are undefined (even after himds file detection)
if (!identityEndpoint || !imdsEndpoint) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is unavailable through environment variables because one or both of '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' are not defined. ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is also unavailable through file detection.`);
return null;
}
// check if the imds endpoint is set to the default for file detection
if (imdsEndpoint === HIMDS_EXECUTABLE_HELPER_STRING) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is available through file detection. Defaulting to known ${ManagedIdentitySourceNames.AZURE_ARC} endpoint: ${DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`);
}
else {
// otherwise, both the identity and imds endpoints are defined without file detection; validate them
const validatedIdentityEndpoint = AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger);
// remove trailing slash
validatedIdentityEndpoint.endsWith("/")
? validatedIdentityEndpoint.slice(0, -1)
: validatedIdentityEndpoint;
AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT, imdsEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger);
logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.AZURE_ARC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`);
}
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
throw createManagedIdentityError(unableToCreateAzureArc);
}
return new AzureArc(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint);
}
/**
* Creates a properly formatted HTTP request for acquiring tokens from the Azure Arc identity endpoint.
*
* This method constructs a GET request to the Azure Arc HIMDS endpoint with the required metadata header
* and query parameters. The endpoint URL is normalized to use 127.0.0.1 instead of localhost for
* consistency. Additional body parameters are calculated by the base class during token acquisition.
*
* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
*
* @returns A configured ManagedIdentityRequestParameters object ready for network execution
*/
createRequest(resource) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint.replace("localhost", "127.0.0.1"));
request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] =
ARC_API_VERSION;
request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] =
resource;
// bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
return request;
}
/**
* Processes the server response and handles Azure Arc-specific authentication challenges.
*
* This method implements the Azure Arc authentication flow which may require reading a secret file
* for authorization. When the initial request returns HTTP 401 Unauthorized, it extracts the file
* path from the WWW-Authenticate header, validates the file location and size, reads the secret,
* and retries the request with Basic authentication. The method includes comprehensive security
* validations to prevent path traversal and ensure file integrity.
*
* @param originalResponse - The initial HTTP response from the identity endpoint
* @param networkClient - Network client for making the retry request if needed
* @param networkRequest - The original request parameters (modified with auth header for retry)
* @param networkRequestOptions - Additional options for network requests
*
* @returns A promise that resolves to the server token response with access token and metadata
*
* @throws {ManagedIdentityError} When:
* - WWW-Authenticate header is missing or has unsupported format
* - Platform is not supported (not Windows or Linux)
* - Secret file has invalid extension (not .key)
* - Secret file path doesn't match expected platform path
* - Secret file cannot be read or is too large (>4096 bytes)
* @throws {ClientAuthError} When network errors occur during retry request
*/
async getServerTokenResponseAsync(originalResponse, networkClient, networkRequest, networkRequestOptions) {
let retryResponse;
if (originalResponse.status === HttpStatus.UNAUTHORIZED) {
const wwwAuthHeader = originalResponse.headers["www-authenticate"];
if (!wwwAuthHeader) {
throw createManagedIdentityError(wwwAuthenticateHeaderMissing);
}
if (!wwwAuthHeader.includes("Basic realm=")) {
throw createManagedIdentityError(wwwAuthenticateHeaderUnsupportedFormat);
}
const secretFilePath = wwwAuthHeader.split("Basic realm=")[1];
// throw an error if the managed identity application is not being run on Windows or Linux
if (!SUPPORTED_AZURE_ARC_PLATFORMS.hasOwnProperty(process.platform)) {
throw createManagedIdentityError(platformNotSupported);
}
// get the expected Windows or Linux file path
const expectedSecretFilePath = SUPPORTED_AZURE_ARC_PLATFORMS[process.platform];
// throw an error if the file in the file path is not a .key file
const fileName = path.basename(secretFilePath);
if (!fileName.endsWith(".key")) {
throw createManagedIdentityError(invalidFileExtension);
}
/*
* throw an error if the file path from the www-authenticate header does not match the
* expected file path for the platform (Windows or Linux) the managed identity application
* is running on
*/
if (expectedSecretFilePath + fileName !== secretFilePath) {
throw createManagedIdentityError(invalidFilePath);
}
let secretFileSize;
// attempt to get the secret file's size, in bytes
try {
secretFileSize = await statSync(secretFilePath).size;
}
catch (e) {
throw createManagedIdentityError(unableToReadSecretFile);
}
// throw an error if the secret file's size is greater than 4096 bytes
if (secretFileSize > AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES) {
throw createManagedIdentityError(invalidSecret);
}
// attempt to read the contents of the secret file
let secret;
try {
secret = readFileSync(secretFilePath, EncodingTypes.UTF8);
}
catch (e) {
throw createManagedIdentityError(unableToReadSecretFile);
}
const authHeaderValue = `Basic ${secret}`;
this.logger.info(`[Managed Identity] Adding authorization header to the request.`);
networkRequest.headers[ManagedIdentityHeaders.AUTHORIZATION_HEADER_NAME] = authHeaderValue;
try {
retryResponse =
await networkClient.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);
}
catch (error) {
if (error instanceof AuthError) {
throw error;
}
else {
throw createClientAuthError(ClientAuthErrorCodes.networkError);
}
}
}
return this.getServerTokenResponse(retryResponse || originalResponse);
}
}
export { ARC_API_VERSION, AZURE_ARC_FILE_DETECTION, AzureArc, DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT, SUPPORTED_AZURE_ARC_PLATFORMS };
//# sourceMappingURL=AzureArc.mjs.map

View File

@@ -0,0 +1,244 @@
/*! @azure/msal-node v3.8.1 2025-10-29 */
'use strict';
import { TimeUtils, Constants, HeaderNames, AuthError, createClientAuthError, ClientAuthErrorCodes, ResponseHandler, UrlString } from '@azure/msal-common/node';
import { ManagedIdentityQueryParameters, HttpMethod, ManagedIdentityIdType } from '../../utils/Constants.mjs';
import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs';
import { isIso8601 } from '../../utils/TimeUtils.mjs';
import { HttpClientWithRetries } from '../../network/HttpClientWithRetries.mjs';
import { invalidManagedIdentityIdType, MsiEnvironmentVariableUrlMalformedErrorCodes } from '../../error/ManagedIdentityErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Managed Identity User Assigned Id Query Parameter Names
*/
const ManagedIdentityUserAssignedIdQueryParameterNames = {
MANAGED_IDENTITY_CLIENT_ID_2017: "clientid",
MANAGED_IDENTITY_CLIENT_ID: "client_id",
MANAGED_IDENTITY_OBJECT_ID: "object_id",
MANAGED_IDENTITY_RESOURCE_ID_IMDS: "msi_res_id",
MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS: "mi_res_id",
};
/**
* Base class for all Managed Identity sources. Provides common functionality for
* authenticating with Azure Managed Identity endpoints across different Azure services
* including IMDS, App Service, Azure Arc, Service Fabric, Cloud Shell, and Machine Learning.
*
* This abstract class handles token acquisition, response processing, and network communication
* while allowing concrete implementations to define source-specific request creation logic.
*/
class BaseManagedIdentitySource {
/**
* Creates an instance of BaseManagedIdentitySource.
*
* @param logger - Logger instance for diagnostic information
* @param nodeStorage - Storage interface for caching tokens
* @param networkClient - Network client for making HTTP requests
* @param cryptoProvider - Cryptographic provider for token operations
* @param disableInternalRetries - Whether to disable automatic retry logic
*/
constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
this.logger = logger;
this.nodeStorage = nodeStorage;
this.networkClient = networkClient;
this.cryptoProvider = cryptoProvider;
this.disableInternalRetries = disableInternalRetries;
}
/**
* Processes the network response and converts it to a standardized server token response.
* This async version allows for source-specific response processing logic while maintaining
* backward compatibility with the synchronous version.
*
* @param response - The network response containing the managed identity token
* @param _networkClient - Network client used for the request (unused in base implementation)
* @param _networkRequest - The original network request parameters (unused in base implementation)
* @param _networkRequestOptions - The network request options (unused in base implementation)
*
* @returns Promise resolving to a standardized server authorization token response
*/
async getServerTokenResponseAsync(response,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_networkClient,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_networkRequest,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_networkRequestOptions) {
return this.getServerTokenResponse(response);
}
/**
* Converts a managed identity token response to a standardized server authorization token response.
* Handles time format conversion, expiration calculation, and error mapping to ensure
* compatibility with the MSAL response handling pipeline.
*
* @param response - The network response containing the managed identity token
*
* @returns Standardized server authorization token response with normalized fields
*/
getServerTokenResponse(response) {
let refreshIn, expiresIn;
if (response.body.expires_on) {
// if the expires_on field in the response body is a string and in ISO 8601 format, convert it to a Unix timestamp (seconds since epoch)
if (isIso8601(response.body.expires_on)) {
response.body.expires_on =
new Date(response.body.expires_on).getTime() / 1000;
}
expiresIn = response.body.expires_on - TimeUtils.nowSeconds();
// compute refresh_in as 1/2 of expires_in, but only if expires_in > 2h
if (expiresIn > 2 * 3600) {
refreshIn = expiresIn / 2;
}
}
const serverTokenResponse = {
status: response.status,
// success
access_token: response.body.access_token,
expires_in: expiresIn,
scope: response.body.resource,
token_type: response.body.token_type,
refresh_in: refreshIn,
// error
correlation_id: response.body.correlation_id || response.body.correlationId,
error: typeof response.body.error === "string"
? response.body.error
: response.body.error?.code,
error_description: response.body.message ||
(typeof response.body.error === "string"
? response.body.error_description
: response.body.error?.message),
error_codes: response.body.error_codes,
timestamp: response.body.timestamp,
trace_id: response.body.trace_id,
};
return serverTokenResponse;
}
/**
* Acquires an access token using the managed identity endpoint for the specified resource.
* This is the primary method for token acquisition, handling the complete flow from
* request creation through response processing and token caching.
*
* @param managedIdentityRequest - The managed identity request containing resource and optional parameters
* @param managedIdentityId - The managed identity configuration (system or user-assigned)
* @param fakeAuthority - Authority instance used for token caching (managed identity uses a placeholder authority)
* @param refreshAccessToken - Whether this is a token refresh operation
*
* @returns Promise resolving to an authentication result containing the access token and metadata
*
* @throws {AuthError} When network requests fail or token validation fails
* @throws {ClientAuthError} When network errors occur during the request
*/
async acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
const networkRequest = this.createRequest(managedIdentityRequest.resource, managedIdentityId);
if (managedIdentityRequest.revokedTokenSha256Hash) {
this.logger.info(`[Managed Identity] The following claims are present in the request: ${managedIdentityRequest.claims}`);
networkRequest.queryParameters[ManagedIdentityQueryParameters.SHA256_TOKEN_TO_REFRESH] = managedIdentityRequest.revokedTokenSha256Hash;
}
if (managedIdentityRequest.clientCapabilities?.length) {
const clientCapabilities = managedIdentityRequest.clientCapabilities.toString();
this.logger.info(`[Managed Identity] The following client capabilities are present in the request: ${clientCapabilities}`);
networkRequest.queryParameters[ManagedIdentityQueryParameters.XMS_CC] = clientCapabilities;
}
const headers = networkRequest.headers;
headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE;
const networkRequestOptions = { headers };
if (Object.keys(networkRequest.bodyParameters).length) {
networkRequestOptions.body =
networkRequest.computeParametersBodyString();
}
/**
* Initializes the network client helper based on the retry policy configuration.
* If internal retries are disabled, it uses the provided network client directly.
* Otherwise, it wraps the network client with an HTTP client that supports retries.
*/
const networkClientHelper = this.disableInternalRetries
? this.networkClient
: new HttpClientWithRetries(this.networkClient, networkRequest.retryPolicy, this.logger);
const reqTimestamp = TimeUtils.nowSeconds();
let response;
try {
// Sources that send POST requests: Cloud Shell
if (networkRequest.httpMethod === HttpMethod.POST) {
response =
await networkClientHelper.sendPostRequestAsync(networkRequest.computeUri(), networkRequestOptions);
// Sources that send GET requests: App Service, Azure Arc, IMDS, Service Fabric
}
else {
response =
await networkClientHelper.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);
}
}
catch (error) {
if (error instanceof AuthError) {
throw error;
}
else {
throw createClientAuthError(ClientAuthErrorCodes.networkError);
}
}
const responseHandler = new ResponseHandler(managedIdentityId.id, this.nodeStorage, this.cryptoProvider, this.logger, null, null);
const serverTokenResponse = await this.getServerTokenResponseAsync(response, networkClientHelper, networkRequest, networkRequestOptions);
responseHandler.validateTokenResponse(serverTokenResponse, refreshAccessToken);
// caches the token
return responseHandler.handleServerTokenResponse(serverTokenResponse, fakeAuthority, reqTimestamp, managedIdentityRequest);
}
/**
* Determines the appropriate query parameter name for user-assigned managed identity
* based on the identity type, API version, and endpoint characteristics.
* Different Azure services and API versions use different parameter names for the same identity types.
*
* @param managedIdentityIdType - The type of user-assigned managed identity (client ID, object ID, or resource ID)
* @param isImds - Whether the request is being made to the IMDS (Instance Metadata Service) endpoint
* @param usesApi2017 - Whether the endpoint uses the 2017-09-01 API version (affects client ID parameter name)
*
* @returns The correct query parameter name for the specified identity type and endpoint
*
* @throws {ManagedIdentityError} When an invalid managed identity ID type is provided
*/
getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityIdType, isImds, usesApi2017) {
switch (managedIdentityIdType) {
case ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID:
this.logger.info(`[Managed Identity] [API version ${usesApi2017 ? "2017+" : "2019+"}] Adding user assigned client id to the request.`);
// The Machine Learning source uses the 2017-09-01 API version, which uses "clientid" instead of "client_id"
return usesApi2017
? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017
: ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID;
case ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID:
this.logger.info("[Managed Identity] Adding user assigned resource id to the request.");
return isImds
? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_IMDS
: ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS;
case ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID:
this.logger.info("[Managed Identity] Adding user assigned object id to the request.");
return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_OBJECT_ID;
default:
throw createManagedIdentityError(invalidManagedIdentityIdType);
}
}
}
/**
* Validates and normalizes an environment variable containing a URL string.
* This static utility method ensures that environment variables used for managed identity
* endpoints contain properly formatted URLs and provides informative error messages when validation fails.
*
* @param envVariableStringName - The name of the environment variable being validated (for error reporting)
* @param envVariable - The environment variable value containing the URL string
* @param sourceName - The name of the managed identity source (for error reporting)
* @param logger - Logger instance for diagnostic information
*
* @returns The validated and normalized URL string
*
* @throws {ManagedIdentityError} When the environment variable contains a malformed URL
*/
BaseManagedIdentitySource.getValidatedEnvVariableUrlString = (envVariableStringName, envVariable, sourceName, logger) => {
try {
return new UrlString(envVariable).urlString;
}
catch (error) {
logger.info(`[Managed Identity] ${sourceName} managed identity is unavailable because the '${envVariableStringName}' environment variable is malformed.`);
throw createManagedIdentityError(MsiEnvironmentVariableUrlMalformedErrorCodes[envVariableStringName]);
}
};
export { BaseManagedIdentitySource, ManagedIdentityUserAssignedIdQueryParameterNames };
//# sourceMappingURL=BaseManagedIdentitySource.mjs.map

View File

@@ -0,0 +1,103 @@
/*! @azure/msal-node v3.8.1 2025-10-29 */
'use strict';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, ManagedIdentityHeaders, ManagedIdentityQueryParameters, HttpMethod } from '../../utils/Constants.mjs';
import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs';
import { unableToCreateCloudShell } from '../../error/ManagedIdentityErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Azure Cloud Shell managed identity source implementation.
*
* This class handles authentication for applications running in Azure Cloud Shell environment.
* Cloud Shell provides a browser-accessible shell for managing Azure resources and includes
* a pre-configured managed identity for authentication.
*
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/CloudShellManagedIdentitySource.cs
*/
class CloudShell extends BaseManagedIdentitySource {
/**
* Creates a new CloudShell managed identity source instance.
*
* @param logger - Logger instance for diagnostic logging
* @param nodeStorage - Node.js storage implementation for caching
* @param networkClient - HTTP client for making requests to the managed identity endpoint
* @param cryptoProvider - Cryptographic operations provider
* @param disableInternalRetries - Whether to disable automatic retry logic for failed requests
* @param msiEndpoint - The MSI endpoint URL obtained from environment variables
*/
constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint) {
super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
this.msiEndpoint = msiEndpoint;
}
/**
* Retrieves the required environment variables for Cloud Shell managed identity.
*
* Cloud Shell requires the MSI_ENDPOINT environment variable to be set, which
* contains the URL of the managed identity service endpoint.
*
* @returns An array containing the MSI_ENDPOINT environment variable value (or undefined if not set)
*/
static getEnvironmentVariables() {
const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT];
return [msiEndpoint];
}
/**
* Attempts to create a CloudShell managed identity source instance.
*
* This method validates that the required environment variables are present and
* creates a CloudShell instance if the environment is properly configured.
* Cloud Shell only supports system-assigned managed identities.
*
* @param logger - Logger instance for diagnostic logging
* @param nodeStorage - Node.js storage implementation for caching
* @param networkClient - HTTP client for making requests
* @param cryptoProvider - Cryptographic operations provider
* @param disableInternalRetries - Whether to disable automatic retry logic
* @param managedIdentityId - The managed identity configuration (must be system-assigned)
*
* @returns A CloudShell instance if the environment is valid, null otherwise
*
* @throws {ManagedIdentityError} When a user-assigned managed identity is requested,
* as Cloud Shell only supports system-assigned identities
*/
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
const [msiEndpoint] = CloudShell.getEnvironmentVariables();
// if the msi endpoint environment variable is undefined, this MSI provider is unavailable.
if (!msiEndpoint) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity is unavailable because the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT} environment variable is not defined.`);
return null;
}
const validatedMsiEndpoint = CloudShell.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.CLOUD_SHELL, logger);
logger.info(`[Managed Identity] Environment variable validation passed for ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity.`);
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
throw createManagedIdentityError(unableToCreateCloudShell);
}
return new CloudShell(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint);
}
/**
* Creates an HTTP request to acquire an access token from the Cloud Shell managed identity endpoint.
*
* This method constructs a POST request to the MSI endpoint with the required headers and
* body parameters for Cloud Shell authentication. The request includes the target resource
* for which the access token is being requested.
*
* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
*
* @returns A configured ManagedIdentityRequestParameters object ready for network execution
*/
createRequest(resource) {
const request = new ManagedIdentityRequestParameters(HttpMethod.POST, this.msiEndpoint);
request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
request.bodyParameters[ManagedIdentityQueryParameters.RESOURCE] =
resource;
return request;
}
}
export { CloudShell };
//# sourceMappingURL=CloudShell.mjs.map

View File

@@ -0,0 +1,108 @@
/*! @azure/msal-node v3.8.1 2025-10-29 */
'use strict';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs';
import { ImdsRetryPolicy } from '../../retry/ImdsRetryPolicy.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Documentation for IMDS is available at https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http
const IMDS_TOKEN_PATH = "/metadata/identity/oauth2/token";
const DEFAULT_IMDS_ENDPOINT = `http://169.254.169.254${IMDS_TOKEN_PATH}`;
const IMDS_API_VERSION = "2018-02-01";
/**
* Managed Identity source implementation for Azure Instance Metadata Service (IMDS).
*
* IMDS is available on Azure Virtual Machines and Virtual Machine Scale Sets and provides
* a REST endpoint to obtain OAuth tokens for managed identities. This implementation
* handles both system-assigned and user-assigned managed identities.
*
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ImdsManagedIdentitySource.cs
*/
class Imds extends BaseManagedIdentitySource {
/**
* Constructs an Imds instance with the specified configuration.
*
* @param logger - Logger instance for recording debug information and errors
* @param nodeStorage - NodeStorage instance used for token caching operations
* @param networkClient - Network client implementation for making HTTP requests to IMDS
* @param cryptoProvider - CryptoProvider for generating correlation IDs and other cryptographic operations
* @param disableInternalRetries - When true, disables the built-in retry logic for IMDS requests
* @param identityEndpoint - The complete IMDS endpoint URL including the token path
*/
constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) {
super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
this.identityEndpoint = identityEndpoint;
}
/**
* Creates an Imds instance with the appropriate endpoint configuration.
*
* This method checks for the presence of the AZURE_POD_IDENTITY_AUTHORITY_HOST environment
* variable, which is used in Azure Kubernetes Service (AKS) environments with Azure AD
* Pod Identity. If found, it uses that endpoint; otherwise, it falls back to the standard
* IMDS endpoint (169.254.169.254).
*
* @param logger - Logger instance for recording endpoint discovery and validation
* @param nodeStorage - NodeStorage instance for token caching
* @param networkClient - Network client for HTTP requests
* @param cryptoProvider - CryptoProvider for cryptographic operations
* @param disableInternalRetries - Whether to disable built-in retry logic
*
* @returns A configured Imds instance ready to make token requests
*/
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
let validatedIdentityEndpoint;
if (process.env[ManagedIdentityEnvironmentVariableNames
.AZURE_POD_IDENTITY_AUTHORITY_HOST]) {
logger.info(`[Managed Identity] Environment variable ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} for ${ManagedIdentitySourceNames.IMDS} returned endpoint: ${process.env[ManagedIdentityEnvironmentVariableNames
.AZURE_POD_IDENTITY_AUTHORITY_HOST]}`);
validatedIdentityEndpoint = Imds.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST, `${process.env[ManagedIdentityEnvironmentVariableNames
.AZURE_POD_IDENTITY_AUTHORITY_HOST]}${IMDS_TOKEN_PATH}`, ManagedIdentitySourceNames.IMDS, logger);
}
else {
logger.info(`[Managed Identity] Unable to find ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} environment variable for ${ManagedIdentitySourceNames.IMDS}, using the default endpoint.`);
validatedIdentityEndpoint = DEFAULT_IMDS_ENDPOINT;
}
return new Imds(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, validatedIdentityEndpoint);
}
/**
* Creates a properly configured HTTP request for acquiring an access token from IMDS.
*
* This method builds a complete request object with all necessary headers, query parameters,
* and retry policies required by the Azure Instance Metadata Service.
*
* Key request components:
* - HTTP GET method to the IMDS token endpoint
* - Metadata header set to "true" (required by IMDS)
* - API version parameter (currently "2018-02-01")
* - Resource parameter specifying the target audience
* - Identity-specific parameters for user-assigned managed identities
* - IMDS-specific retry policy
*
* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
* @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity
*
* @returns A configured ManagedIdentityRequestParameters object ready for network execution
*/
createRequest(resource, managedIdentityId) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] =
IMDS_API_VERSION;
request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] =
resource;
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, true // indicates source is IMDS
)] = managedIdentityId.id;
}
// The bodyParameters are calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity.
request.retryPolicy = new ImdsRetryPolicy();
return request;
}
}
export { Imds };
//# sourceMappingURL=Imds.mjs.map

View File

@@ -0,0 +1,128 @@
/*! @azure/msal-node v3.8.1 2025-10-29 */
'use strict';
import { BaseManagedIdentitySource, ManagedIdentityUserAssignedIdQueryParameterNames } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const MACHINE_LEARNING_MSI_API_VERSION = "2017-09-01";
const MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR = `Only client id is supported for user-assigned managed identity in ${ManagedIdentitySourceNames.MACHINE_LEARNING}.`; // referenced in unit test
/**
* Machine Learning Managed Identity Source implementation for Azure Machine Learning environments.
*
* This class handles managed identity authentication specifically for Azure Machine Learning services.
* It supports both system-assigned and user-assigned managed identities, using the MSI_ENDPOINT
* and MSI_SECRET environment variables that are automatically provided in Azure ML environments.
*/
class MachineLearning extends BaseManagedIdentitySource {
/**
* Creates a new MachineLearning managed identity source instance.
*
* @param logger - Logger instance for diagnostic information
* @param nodeStorage - Node storage implementation for caching
* @param networkClient - Network client for making HTTP requests
* @param cryptoProvider - Cryptographic operations provider
* @param disableInternalRetries - Whether to disable automatic request retries
* @param msiEndpoint - The MSI endpoint URL from environment variables
* @param secret - The MSI secret from environment variables
*/
constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret) {
super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
this.msiEndpoint = msiEndpoint;
this.secret = secret;
}
/**
* Retrieves the required environment variables for Azure Machine Learning managed identity.
*
* This method checks for the presence of MSI_ENDPOINT and MSI_SECRET environment variables
* that are automatically set by the Azure Machine Learning platform when managed identity
* is enabled for the compute instance or cluster.
*
* @returns An array containing [msiEndpoint, secret] where either value may be undefined
* if the corresponding environment variable is not set
*/
static getEnvironmentVariables() {
const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT];
const secret = process.env[ManagedIdentityEnvironmentVariableNames.MSI_SECRET];
return [msiEndpoint, secret];
}
/**
* Attempts to create a MachineLearning managed identity source.
*
* This method validates the Azure Machine Learning environment by checking for the required
* MSI_ENDPOINT and MSI_SECRET environment variables. If both are present and valid,
* it creates and returns a MachineLearning instance. If either is missing or invalid,
* it returns null, indicating that this managed identity source is not available
* in the current environment.
*
* @param logger - Logger instance for diagnostic information
* @param nodeStorage - Node storage implementation for caching
* @param networkClient - Network client for making HTTP requests
* @param cryptoProvider - Cryptographic operations provider
* @param disableInternalRetries - Whether to disable automatic request retries
*
* @returns A new MachineLearning instance if the environment is valid, null otherwise
*/
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
const [msiEndpoint, secret] = MachineLearning.getEnvironmentVariables();
// if either of the MSI endpoint or MSI secret variables are undefined, this MSI provider is unavailable.
if (!msiEndpoint || !secret) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.MSI_SECRET}' environment variables are not defined.`);
return null;
}
const validatedMsiEndpoint = MachineLearning.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.MACHINE_LEARNING, logger);
logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity.`);
return new MachineLearning(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret);
}
/**
* Creates a managed identity token request for Azure Machine Learning environments.
*
* This method constructs the HTTP request parameters needed to acquire an access token
* from the Azure Machine Learning managed identity endpoint. It handles both system-assigned
* and user-assigned managed identities with specific logic for each type:
*
* - System-assigned: Uses the DEFAULT_IDENTITY_CLIENT_ID environment variable
* - User-assigned: Only supports client ID-based identification (not object ID or resource ID)
*
* The request uses the 2017-09-01 API version and includes the required secret header
* for authentication with the MSI endpoint.
*
* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
* @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity
*
* @returns A configured ManagedIdentityRequestParameters object ready for network execution
*
* @throws Error if an unsupported managed identity ID type is specified (only client ID is supported for user-assigned)
*/
createRequest(resource, managedIdentityId) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.msiEndpoint);
request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
request.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] =
this.secret;
request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] =
MACHINE_LEARNING_MSI_API_VERSION;
request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] =
resource;
if (managedIdentityId.idType === ManagedIdentityIdType.SYSTEM_ASSIGNED) {
request.queryParameters[ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017] = process.env[ManagedIdentityEnvironmentVariableNames
.DEFAULT_IDENTITY_CLIENT_ID]; // this environment variable is always set in an Azure Machine Learning source
}
else if (managedIdentityId.idType ===
ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID) {
request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, false, // isIMDS
true // uses2017API
)] = managedIdentityId.id;
}
else {
throw new Error(MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR);
}
// bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
return request;
}
}
export { MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR, MachineLearning };
//# sourceMappingURL=MachineLearning.mjs.map

View File

@@ -0,0 +1,122 @@
/*! @azure/msal-node v3.8.1 2025-10-29 */
'use strict';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, ManagedIdentityHeaders, ManagedIdentityQueryParameters, HttpMethod } from '../../utils/Constants.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const SERVICE_FABRIC_MSI_API_VERSION = "2019-07-01-preview";
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ServiceFabricManagedIdentitySource.cs
*/
class ServiceFabric extends BaseManagedIdentitySource {
/**
* Constructs a new ServiceFabric managed identity source for acquiring tokens from Azure Service Fabric clusters.
*
* Service Fabric managed identity allows applications running in Service Fabric clusters to authenticate
* without storing credentials in code. This source handles token acquisition using the Service Fabric
* Managed Identity Token Service (MITS).
*
* @param logger - Logger instance for logging authentication events and debugging information
* @param nodeStorage - NodeStorage instance for caching tokens and other authentication artifacts
* @param networkClient - Network client for making HTTP requests to the Service Fabric identity endpoint
* @param cryptoProvider - Crypto provider for cryptographic operations like token validation
* @param disableInternalRetries - Whether to disable internal retry logic for failed requests
* @param identityEndpoint - The Service Fabric managed identity endpoint URL
* @param identityHeader - The Service Fabric managed identity secret header value
*/
constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) {
super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
this.identityEndpoint = identityEndpoint;
this.identityHeader = identityHeader;
}
/**
* Retrieves the environment variables required for Service Fabric managed identity authentication.
*
* Service Fabric managed identity requires three specific environment variables to be set by the
* Service Fabric runtime:
* - IDENTITY_ENDPOINT: The endpoint URL for the Managed Identity Token Service (MITS)
* - IDENTITY_HEADER: A secret value used for authentication with the MITS
* - IDENTITY_SERVER_THUMBPRINT: The thumbprint of the MITS server certificate for secure communication
*
* @returns An array containing the identity endpoint, identity header, and identity server thumbprint values.
* Elements will be undefined if the corresponding environment variables are not set.
*/
static getEnvironmentVariables() {
const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER];
const identityServerThumbprint = process.env[ManagedIdentityEnvironmentVariableNames
.IDENTITY_SERVER_THUMBPRINT];
return [identityEndpoint, identityHeader, identityServerThumbprint];
}
/**
* Attempts to create a ServiceFabric managed identity source if the runtime environment supports it.
*
* Checks for the presence of all required Service Fabric environment variables
* and validates the endpoint URL format. It will only create a ServiceFabric instance if the application
* is running in a properly configured Service Fabric cluster with managed identity enabled.
*
* Note: User-assigned managed identities must be configured at the cluster level, not at runtime.
* This method will log a warning if a user-assigned identity is requested.
*
* @param logger - Logger instance for logging creation events and validation results
* @param nodeStorage - NodeStorage instance for caching tokens and authentication artifacts
* @param networkClient - Network client for making HTTP requests to the identity endpoint
* @param cryptoProvider - Crypto provider for cryptographic operations
* @param disableInternalRetries - Whether to disable internal retry logic for failed requests
* @param managedIdentityId - Managed identity identifier specifying system-assigned or user-assigned identity
*
* @returns A ServiceFabric instance if all environment variables are valid and present, otherwise null
*/
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
const [identityEndpoint, identityHeader, identityServerThumbprint] = ServiceFabric.getEnvironmentVariables();
if (!identityEndpoint || !identityHeader || !identityServerThumbprint) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity is unavailable because one or all of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}', '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' or '${ManagedIdentityEnvironmentVariableNames.IDENTITY_SERVER_THUMBPRINT}' environment variables are not defined.`);
return null;
}
const validatedIdentityEndpoint = ServiceFabric.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.SERVICE_FABRIC, logger);
logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity.`);
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
logger.warning(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} user assigned managed identity is configured in the cluster, not during runtime. See also: https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service.`);
}
return new ServiceFabric(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader);
}
/**
* Creates HTTP request parameters for acquiring an access token from the Service Fabric Managed Identity Token Service (MITS).
*
* This method constructs a properly formatted HTTP GET request that includes:
* - The secret header for authentication with MITS
* - API version parameter for the Service Fabric MSI endpoint
* - Resource parameter specifying the target Azure service
* - Optional identity parameters for user-assigned managed identities
*
* The request follows the Service Fabric managed identity protocol and uses the 2019-07-01-preview API version.
* For user-assigned identities, the appropriate query parameter (client_id, object_id, or resource_id) is added
* based on the identity type.
*
* @param resource - The Azure resource URI for which the access token is requested (e.g., "https://vault.azure.net/")
* @param managedIdentityId - The managed identity configuration specifying system-assigned or user-assigned identity details
*
* @returns A configured ManagedIdentityRequestParameters object ready for network execution
*/
createRequest(resource, managedIdentityId) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
request.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] =
this.identityHeader;
request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] =
SERVICE_FABRIC_MSI_API_VERSION;
request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] =
resource;
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
}
// bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
return request;
}
}
export { ServiceFabric };
//# sourceMappingURL=ServiceFabric.mjs.map