UNPKG

@azure/identity

Version:

Provides credential implementations for Azure SDK libraries that can authenticate with Microsoft Entra ID

201 lines (200 loc) • 8.4 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var azureDeveloperCliCredential_exports = {}; __export(azureDeveloperCliCredential_exports, { AzureDeveloperCliCredential: () => AzureDeveloperCliCredential, azureDeveloperCliPublicErrorMessages: () => azureDeveloperCliPublicErrorMessages, developerCliCredentialInternals: () => developerCliCredentialInternals }); module.exports = __toCommonJS(azureDeveloperCliCredential_exports); var import_logging = require("../util/logging.js"); var import_errors = require("../errors.js"); var import_tenantIdUtils = require("../util/tenantIdUtils.js"); var import_tracing = require("../util/tracing.js"); var import_scopeUtils = require("../util/scopeUtils.js"); var import_processUtils = require("../util/processUtils.js"); const logger = (0, import_logging.credentialLogger)("AzureDeveloperCliCredential"); const azureDeveloperCliPublicErrorMessages = { notInstalled: "Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.", login: "Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.", unknown: "Unknown error while trying to retrieve the access token", claim: "This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:" }; const developerCliCredentialInternals = { /** * @internal */ getSafeWorkingDir() { if (process.platform === "win32") { let systemRoot = process.env.SystemRoot || process.env["SYSTEMROOT"]; if (!systemRoot) { logger.getToken.warning( "The SystemRoot environment variable is not set. This may cause issues when using the Azure Developer CLI credential." ); systemRoot = "C:\\Windows"; } return systemRoot; } else { return "/bin"; } }, /** * Gets the access token from Azure Developer CLI * @param scopes - The scopes to use when getting the token * @internal */ async getAzdAccessToken(scopes, tenantId, timeout, claims) { let tenantSection = []; if (tenantId) { tenantSection = ["--tenant-id", tenantId]; } let claimsSections = []; if (claims) { const encodedClaims = btoa(claims); claimsSections = ["--claims", encodedClaims]; } const args = [ "auth", "token", "--output", "json", "--no-prompt", ...scopes.reduce((previous, current) => previous.concat("--scope", current), []), ...tenantSection, ...claimsSections ]; return import_processUtils.processUtils.execFileWithResult("azd", args, { allowWindowsBatchFiles: true, cwd: developerCliCredentialInternals.getSafeWorkingDir(), encoding: "utf8", timeout }); } }; class AzureDeveloperCliCredential { tenantId; additionallyAllowedTenantIds; timeout; /** * Creates an instance of the {@link AzureDeveloperCliCredential}. * * To use this credential, ensure that you have already logged * in via the 'azd' tool using the command "azd auth login" from the commandline. * * @param options - Options, to optionally allow multi-tenant requests. */ constructor(options) { if (options?.tenantId) { (0, import_tenantIdUtils.checkTenantId)(logger, options?.tenantId); this.tenantId = options?.tenantId; } this.additionallyAllowedTenantIds = (0, import_tenantIdUtils.resolveAdditionallyAllowedTenantIds)( options?.additionallyAllowedTenants ); this.timeout = options?.processTimeoutInMs; } /** * Authenticates with Microsoft Entra ID and returns an access token if successful. * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. * * @param scopes - The list of scopes for which the token will have access. * @param options - The options used to configure any requests this * TokenCredential implementation might make. */ async getToken(scopes, options = {}) { const tenantId = (0, import_tenantIdUtils.processMultiTenantRequest)( this.tenantId, options, this.additionallyAllowedTenantIds ); if (tenantId) { (0, import_tenantIdUtils.checkTenantId)(logger, tenantId); } let scopeList; if (typeof scopes === "string") { scopeList = [scopes]; } else { scopeList = scopes; } logger.getToken.info(`Using the scopes ${scopes}`); return import_tracing.tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => { try { scopeList.forEach((scope) => { (0, import_scopeUtils.ensureValidScopeForDevTimeCreds)(scope, logger); }); const obj = await developerCliCredentialInternals.getAzdAccessToken( scopeList, tenantId, this.timeout, options.claims ); const isMFARequiredError = obj.stderr?.match("must use multi-factor authentication") || obj.stderr?.match("reauthentication required"); const isNotLoggedInError = obj.stderr?.match("not logged in, run `azd login` to login") || obj.stderr?.match("not logged in, run `azd auth login` to login"); const isNotInstallError = obj.stderr?.match("azd:(.*)not found") || obj.stderr?.startsWith("'azd' is not recognized"); if (isNotInstallError || obj.error && obj.error.code === "ENOENT") { const error = new import_errors.CredentialUnavailableError( azureDeveloperCliPublicErrorMessages.notInstalled ); logger.getToken.info((0, import_logging.formatError)(scopes, error)); throw error; } if (isNotLoggedInError) { const error = new import_errors.CredentialUnavailableError(azureDeveloperCliPublicErrorMessages.login); logger.getToken.info((0, import_logging.formatError)(scopes, error)); throw error; } if (isMFARequiredError) { const scope = scopeList.reduce((previous, current) => previous.concat("--scope", current), []).join(" "); const loginCmd = `azd auth login ${scope}`; const error = new import_errors.CredentialUnavailableError( `${azureDeveloperCliPublicErrorMessages.claim} ${loginCmd}` ); logger.getToken.info((0, import_logging.formatError)(scopes, error)); throw error; } try { const resp = JSON.parse(obj.stdout); logger.getToken.info((0, import_logging.formatSuccess)(scopes)); return { token: resp.token, expiresOnTimestamp: new Date(resp.expiresOn).getTime(), tokenType: "Bearer" }; } catch (e) { if (obj.stderr) { throw new import_errors.CredentialUnavailableError(obj.stderr); } throw e; } } catch (err) { const error = err.name === "CredentialUnavailableError" ? err : new import_errors.CredentialUnavailableError( err.message || azureDeveloperCliPublicErrorMessages.unknown ); logger.getToken.info((0, import_logging.formatError)(scopes, error)); throw error; } }); } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { AzureDeveloperCliCredential, azureDeveloperCliPublicErrorMessages, developerCliCredentialInternals }); //# sourceMappingURL=azureDeveloperCliCredential.js.map