All files / src default-credential.ts

97.19% Statements 104/107
91.91% Branches 91/99
100% Functions 18/18
97.19% Lines 104/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455                                                                                                                          9x 9x         25x               36x 36x   36x     36x 22x     14x   36x     36x             56x 56x 7x     55x 55x 47x 24x     23x 23x     23x 56x 56x 56x         6x                     17x 17x             13x   13x                 12x 7x       9x 3x       6x   6x             6x 6x                     8x 8x               13x     13x   13x 11x     9x 6x     3x 3x     3x 2x     1x                           55x 55x 55x 16x     39x 32x         39x 39x 10x                           29x 29x 13x 13x       11x         11x                           16x 16x 16x   9x                 7x                       5x 4x 1x   3x                             23x     23x                     22x 22x                             18x             33x 33x     12x 12x 9x     1x                   11x 11x                           4x 4x     7x               3x 3x       3x 3x   3x             3x 3x   1x 1x                             5x 5x           3x 2x     1x      
import { createClientAssertion, loadClientCertificate } from './internal/client-certificate'
import { fetchJson, normalizeCommandToken, normalizeToken } from './internal/oauth'
import { resolveRequiredScopes } from './internal/request-core'
import type { RetryOptions } from './internal/request-core'
import {
  defaultFetch,
  executeCommand,
  getEnv,
  getRawEnv,
  hasCommandExecution,
  isCommandUnavailable,
  isWindows,
  readTextFile,
} from './internal/runtime'
import {
  claimsLoginInstructions,
  requireDeveloperInputs,
  environmentAllowedTenants,
  requireTenantId,
  resolveTenant,
  selectTenant,
  tokenRequestClaims,
} from './internal/token-options'
import { sanitizeAuthorityHost } from './internal/url'
import { getManagedIdentityToken } from './managed-identity'
import { getServicePrincipalToken } from './service-principal'
import { TokenUnavailableError } from './token-unavailable-error'
import type { AccessToken } from './types'
 
export interface DefaultAzureCredentialOptions {
  authorityHost?: string
  /** Tenant for workload identity, Azure CLI and Azure PowerShell. */
  tenantId?: string
  /**
   * Tenants besides the configured one that `getToken` may request; `*` allows any tenant.
   * The environment service principal falls back to AZURE_ADDITIONALLY_ALLOWED_TENANTS.
   */
  additionallyAllowedTenants?: string[]
  managedIdentityClientId?: string
  /** Retries of token requests; managed identity on IMDS has its own defaults. */
  retryOptions?: RetryOptions
  fetch?: typeof globalThis.fetch
}
 
export interface DefaultAzureCredentialTokenOptions extends DefaultAzureCredentialOptions {
  scope: string | string[]
}
 
export interface DeveloperAzureCredentialOptions {
  scope: string | string[]
  abortSignal?: AbortSignal
}
 
/** Per-call options of one chain run; the credential has validated the tenant. */
export interface ChainRequest {
  tenantId?: string
  claims?: string
  enableCae?: boolean
  signal?: AbortSignal
}
 
const jwtBearerAssertionType = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'
const enabledFlag = /^(?:true|1)$/iu
 
export async function getDefaultAzureCredentialToken(
  options: DefaultAzureCredentialTokenOptions,
): Promise<AccessToken> {
  return await acquireDefaultAzureCredentialToken(options, {})
}
 
/**
 * The tenant the chain uses when a call names none: the environment credential's, then workload
 * identity's, then the developer tools'. Calls whose tenant selects the same one share a token.
 */
export function defaultChainTenant(options: DefaultAzureCredentialOptions): string | undefined {
  const tenantId = getEnv('AZURE_TENANT_ID')
  const clientId = getEnv('AZURE_CLIENT_ID')
  const hasEnvironmentCredential =
    getEnv('AZURE_CLIENT_SECRET') !== undefined ||
    getEnv('AZURE_CLIENT_CERTIFICATE_PATH') !== undefined ||
    (getEnv('AZURE_USERNAME') !== undefined && getRawEnv('AZURE_PASSWORD') !== undefined)
  if (tenantId !== undefined && clientId !== undefined && hasEnvironmentCredential) {
    return tenantId
  }
 
  const workloadTenantId = options.tenantId ?? tenantId
  const hasWorkloadIdentity =
    workloadTenantId !== undefined &&
    (options.managedIdentityClientId ?? clientId) !== undefined &&
    getEnv('AZURE_FEDERATED_TOKEN_FILE') !== undefined
  return hasWorkloadIdentity ? workloadTenantId : options.tenantId
}
 
export async function acquireDefaultAzureCredentialToken(
  options: DefaultAzureCredentialTokenOptions,
  request: ChainRequest,
): Promise<AccessToken> {
  const scopes = resolveRequiredScopes(options.scope)
  if (options.tenantId !== undefined) {
    requireTenantId(options.tenantId)
  }
 
  const { signal } = request
  const environmentToken = await getEnvironmentToken(scopes, options, request)
  if (environmentToken !== undefined) {
    return environmentToken
  }
 
  const tenantId = getEnv('AZURE_TENANT_ID')
  const clientId = getEnv('AZURE_CLIENT_ID')
 
  // The AKS workload identity webhook also sets AZURE_CLIENT_ID, so this must run before managed identity.
  const workloadTenantId = options.tenantId ?? tenantId
  const workloadClientId = options.managedIdentityClientId ?? clientId
  const federatedTokenFile = getEnv('AZURE_FEDERATED_TOKEN_FILE')
  if (
    workloadTenantId !== undefined &&
    workloadClientId !== undefined &&
    federatedTokenFile !== undefined
  ) {
    return await getWorkloadIdentityToken(
      resolveTenant(workloadTenantId, request.tenantId, options.additionallyAllowedTenants) ??
        workloadTenantId,
      workloadClientId,
      federatedTokenFile,
      scopes,
      options,
      request,
    )
  }
 
  const [scope] = scopes
  if (
    scopes.length === 1 &&
    scope?.endsWith('/.default') === true &&
    (options.tenantId === undefined ||
      selectTenant(options.tenantId, request.tenantId) === options.tenantId) &&
    request.claims === undefined
  ) {
    const managedIdentityToken = await unlessUnavailable(
      async () =>
        await getManagedIdentityToken({
          scope,
          clientId: options.managedIdentityClientId ?? clientId,
          abortSignal: signal,
          retryOptions: options.retryOptions,
          fetch: options.fetch,
        }),
      signal,
    )
    if (managedIdentityToken !== undefined) {
      return managedIdentityToken
    }
  }
 
  if (request.claims !== undefined) {
    throw new TokenUnavailableError(
      `Could not find available credentials. ${claimsLoginInstructions(request.claims, scopes, request.tenantId)}`,
    )
  }
  const developerToken = await unlessUnavailable(
    async () =>
      await getDeveloperToken(
        scopes,
        signal,
        resolveTenant(options.tenantId, request.tenantId, options.additionallyAllowedTenants),
      ),
    signal,
  )
  Eif (developerToken !== undefined) {
    return developerToken
  }
 
  throw new TokenUnavailableError(
    'Could not find available credentials: environment service principal, managed identity, Azure CLI and Azure PowerShell are unavailable',
  )
}
 
export async function getDeveloperAzureCredentialToken(
  options: DeveloperAzureCredentialOptions,
): Promise<AccessToken> {
  options.abortSignal?.throwIfAborted()
  return await getDeveloperToken(resolveRequiredScopes(options.scope), options.abortSignal)
}
 
async function getDeveloperToken(
  scopes: string[],
  signal?: AbortSignal,
  tenantId?: string,
): Promise<AccessToken> {
  Iif (!hasCommandExecution()) {
    throw new TokenUnavailableError('Command execution is unavailable')
  }
  requireDeveloperInputs(scopes, tenantId)
 
  const cliToken = await unlessUnavailable(
    async () => await getAzureCliToken(scopes, signal, tenantId),
    signal,
  )
  if (cliToken !== undefined) {
    return cliToken
  }
 
  const powerShellToken = await unlessUnavailable(
    async () => await getAzurePowerShellToken(scopes, signal, tenantId),
    signal,
  )
  if (powerShellToken !== undefined) {
    return powerShellToken
  }
 
  throw new TokenUnavailableError(
    'Could not find available developer credentials: Azure CLI and Azure PowerShell are unavailable',
  )
}
 
/**
 * The environment credential of `@azure/identity`: a client secret, then a certificate, then a
 * username and password. A configured source ends the chain, also when it refuses the tenant.
 */
async function getEnvironmentToken(
  scopes: string[],
  options: DefaultAzureCredentialOptions,
  request: ChainRequest,
): Promise<AccessToken | undefined> {
  const configuredTenantId = getEnv('AZURE_TENANT_ID')
  const clientId = getEnv('AZURE_CLIENT_ID')
  if (configuredTenantId === undefined || clientId === undefined) {
    return undefined
  }
 
  const tenantId = (): string =>
    resolveTenant(
      configuredTenantId,
      request.tenantId,
      options.additionallyAllowedTenants ?? environmentAllowedTenants(),
    ) ?? configuredTenantId
  const clientSecret = getEnv('AZURE_CLIENT_SECRET')
  if (clientSecret !== undefined) {
    return await getServicePrincipalToken({
      tenantId: tenantId(),
      clientId,
      clientSecret,
      scope: scopes,
      authorityHost: options.authorityHost,
      abortSignal: request.signal,
      claims: request.claims,
      enableCae: request.enableCae,
      retryOptions: options.retryOptions,
      fetch: options.fetch,
    })
  }
 
  const certificatePath = getEnv('AZURE_CLIENT_CERTIFICATE_PATH')
  if (certificatePath !== undefined) {
    const url = tokenEndpoint(options, tenantId())
    const certificate = await loadClientCertificate(
      await readTextFile(certificatePath),
      getRawEnv('AZURE_CLIENT_CERTIFICATE_PASSWORD'),
    )
    const assertion = await createClientAssertion(certificate, {
      clientId,
      audience: url,
      sendCertificateChain: enabledFlag.test(getEnv('AZURE_CLIENT_SEND_CERTIFICATE_CHAIN') ?? ''),
    })
    return await requestFormToken(
      url,
      {
        client_id: clientId,
        client_assertion: assertion,
        client_assertion_type: jwtBearerAssertionType,
        grant_type: 'client_credentials',
      },
      scopes,
      options,
      request,
    )
  }
 
  const username = getEnv('AZURE_USERNAME')
  const password = getRawEnv('AZURE_PASSWORD')
  if (username !== undefined && password !== undefined) {
    // Accounts that require MFA can't use this grant; Entra's error reaches the caller unchanged.
    return await requestFormToken(
      tokenEndpoint(options, tenantId()),
      { client_id: clientId, grant_type: 'password', username, password },
      scopes,
      options,
      request,
    )
  }
 
  return undefined
}
 
async function getWorkloadIdentityToken(
  tenantId: string,
  clientId: string,
  tokenFile: string,
  scopes: string[],
  options: DefaultAzureCredentialOptions,
  request: ChainRequest,
): Promise<AccessToken> {
  // Kubernetes rotates the projected token in place, so read it for every request.
  const assertion = (await readTextFile(tokenFile)).trim()
  if (assertion.length === 0) {
    throw new TypeError('Workload identity token file is empty')
  }
  return await requestFormToken(
    tokenEndpoint(options, tenantId),
    {
      client_id: clientId,
      client_assertion: assertion,
      client_assertion_type: jwtBearerAssertionType,
      grant_type: 'client_credentials',
    },
    scopes,
    options,
    request,
  )
}
 
function tokenEndpoint(options: DefaultAzureCredentialOptions, tenantId: string): string {
  const authorityHost = sanitizeAuthorityHost(
    options.authorityHost ?? 'https://login.microsoftonline.com',
  )
  return `${authorityHost}/${tenantId}/oauth2/v2.0/token`
}
 
/** Posts an OAuth token request with the per-call claims, cancellation and retries. */
async function requestFormToken(
  url: string,
  form: Record<string, string>,
  scopes: string[],
  options: DefaultAzureCredentialOptions,
  { claims, enableCae, signal }: ChainRequest,
): Promise<AccessToken> {
  const requestClaims = tokenRequestClaims(claims, enableCae)
  const payload = await fetchJson(
    url,
    {
      method: 'POST',
      body: new URLSearchParams({
        ...form,
        scope: scopes.join(' '),
        ...(requestClaims === undefined ? {} : { claims: requestClaims }),
      }),
      signal,
    },
    options.fetch ?? defaultFetch,
    options.retryOptions,
  )
 
  return normalizeToken(payload)
}
 
async function unlessUnavailable(
  acquire: () => Promise<AccessToken>,
  signal: AbortSignal | undefined,
): Promise<AccessToken | undefined> {
  try {
    return await acquire()
  } catch (error) {
    // A cancelled request must not move on to the next credential.
    signal?.throwIfAborted()
    if (error instanceof TokenUnavailableError) {
      return undefined
    }
 
    throw error
  }
}
 
async function getAzureCliToken(
  scopes: string[],
  signal?: AbortSignal,
  tenantId?: string,
): Promise<AccessToken> {
  let output: string
  try {
    output = await executeCommand(
      'az',
      [
        'account',
        'get-access-token',
        '--output',
        'json',
        '--scope',
        ...scopes,
        ...(tenantId === undefined ? [] : ['--tenant', tenantId]),
      ],
      { signal, shell: isWindows() },
    )
  } catch (error) {
    signal?.throwIfAborted()
    throw new TokenUnavailableError('Azure CLI is unavailable or not signed in', error)
  }
 
  return normalizeCommandToken(output)
}
 
async function getAzurePowerShellToken(
  scopes: string[],
  signal?: AbortSignal,
  tenantId?: string,
): Promise<AccessToken> {
  const [scope] = scopes
  Iif (scopes.length !== 1 || scope === undefined) {
    throw new TokenUnavailableError('Azure PowerShell requires exactly one scope')
  }
 
  const resource = scope.endsWith('/.default') ? scope.slice(0, -'/.default'.length) : scope
  const tenantArgument = tenantId === undefined ? '' : ` -TenantId '${tenantId}'`
  // Az.Accounts 5 returns a SecureString token; NetworkCredential unwraps it on PowerShell 5.1 and 7.
  const script = [
    "$ErrorActionPreference = 'Stop'",
    `$token = Get-AzAccessToken -ResourceUrl '${resource.replaceAll("'", "''")}'${tenantArgument}`,
    "$value = if ($token.Token -is [securestring]) { [System.Net.NetworkCredential]::new('', $token.Token).Password } else { $token.Token }",
    '@{ accessToken = $value; expiresOn = $token.ExpiresOn.ToUnixTimeSeconds() } | ConvertTo-Json -Compress',
  ].join('; ')
 
  try {
    return normalizeCommandToken(await runPowerShell(['pwsh', 'powershell'], script, signal))
  } catch (error) {
    signal?.throwIfAborted()
    throw new TokenUnavailableError(
      isCommandUnavailable(error)
        ? 'Azure PowerShell is unavailable'
        : 'Azure PowerShell token request failed',
      error,
    )
  }
}
 
/** Runs the script with the first PowerShell executable that exists. */
async function runPowerShell(
  [command = 'pwsh', ...fallbacks]: string[],
  script: string,
  signal?: AbortSignal,
): Promise<string> {
  try {
    return await executeCommand(
      command,
      ['-NoProfile', '-NoLogo', '-NonInteractive', '-Command', script],
      { signal },
    )
  } catch (error) {
    if (fallbacks.length > 0 && isCommandUnavailable(error)) {
      return await runPowerShell(fallbacks, script, signal)
    }
 
    throw error
  }
}