All files / src managed-identity.ts

100% Statements 56/56
97.36% Branches 37/38
100% Functions 7/7
100% Lines 56/56

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                                              10x 10x   10x 10x         31x 31x 1x     30x 1x     29x 87x   29x 1x     28x 28x 31x 31x 31x 31x 31x   31x 11x 11x               17x 5x 1x         4x                         12x 31x 31x 5x 5x                   5x 5x 5x           15x                                   16x 16x 16x 16x         48x 8x       16x                 12x 12x 12x       5x   7x 7x                     20x 20x   6x 6x 2x     4x     14x    
import { fetchJson, normalizeToken } from './internal/oauth'
import {
  defaultMaxRetryDelayInMs,
  defaultRetryableStatuses,
  exponentialDelay,
} from './internal/request-core'
import type { RetryOptions } from './internal/request-core'
import { defaultFetch, getEnv } from './internal/runtime'
import { TokenRequestError } from './token-request-error'
import { TokenUnavailableError } from './token-unavailable-error'
import type { AccessToken } from './types'
 
export interface ManagedIdentityOptions {
  scope: string
  clientId?: string
  objectId?: string
  resourceId?: string
  abortSignal?: AbortSignal
  /** IMDS defaults to 5 retries from 800 ms and also retries 404 and 410. */
  retryOptions?: RetryOptions
  fetch?: typeof globalThis.fetch
}
 
const imdsProbeTimeoutMs = 1000
const imdsRetryableStatuses = [...defaultRetryableStatuses, 404, 410]
// IMDS answers 410 for up to 70 s while it updates; five waits from 3 s span at least 74.4 s.
const imdsGoneRetryDelayInMs = 3000
const whitespace = /\s/u
 
export async function getManagedIdentityToken(
  options: ManagedIdentityOptions,
): Promise<AccessToken> {
  const { scope, clientId, objectId, resourceId } = options
  if (!scope.endsWith('/.default')) {
    throw new TypeError('Scope must end with /.default')
  }
 
  if (whitespace.test(scope)) {
    throw new TypeError('Managed identity requires exactly one scope')
  }
 
  const selectorCount = [clientId, objectId, resourceId].filter(
    (value) => value !== undefined,
  ).length
  if (selectorCount > 1) {
    throw new TypeError('Specify at most one of clientId, objectId, or resourceId')
  }
 
  const { abortSignal: signal } = options
  signal?.throwIfAborted()
  const resource = scope.slice(0, -'/.default'.length)
  const fetcher = options.fetch ?? defaultFetch
  const identityEndpoint = getEnv('IDENTITY_ENDPOINT')
  const identityHeader = getEnv('IDENTITY_HEADER')
  const msiEndpoint = getEnv('MSI_ENDPOINT')
 
  if (identityEndpoint !== undefined && identityHeader !== undefined) {
    const url = tokenUrl(identityEndpoint, '2019-08-01', resource, options, 'mi_res_id')
    return await requestToken(
      url,
      { headers: { Metadata: 'true', 'X-IDENTITY-HEADER': identityHeader }, signal },
      fetcher,
      options.retryOptions,
    )
  }
 
  if (msiEndpoint !== undefined) {
    if (selectorCount > 0) {
      throw new TokenUnavailableError(
        'Cloud Shell managed identity does not support explicit identity selectors',
      )
    }
 
    return await requestToken(
      new URL(msiEndpoint),
      {
        method: 'POST',
        headers: { Metadata: 'true' },
        body: new URLSearchParams({ resource, 'api-version': '2017-09-01' }),
        signal,
      },
      fetcher,
      options.retryOptions,
    )
  }
 
  const imdsHost = getEnv('AZURE_POD_IDENTITY_AUTHORITY_HOST') ?? 'http://169.254.169.254'
  const imdsEndpoint = `${imdsHost}/metadata/identity/oauth2/token`
  await probeImds(imdsEndpoint, fetcher, signal)
  const url = tokenUrl(imdsEndpoint, '2018-02-01', resource, options, 'msi_res_id')
  return await requestToken(
    url,
    { headers: { Metadata: 'true' }, signal },
    fetcher,
    imdsRetryOptions(options.retryOptions),
  )
}
 
/** IMDS needs longer retries, including 404 and 410 while an identity or IMDS itself is set up. */
function imdsRetryOptions(options: RetryOptions = {}): RetryOptions {
  const retryDelayInMs = options.retryDelayInMs ?? 800
  const maxRetryDelayInMs = options.maxRetryDelayInMs ?? defaultMaxRetryDelayInMs
  return {
    maxRetries: 5,
    retryableStatuses: imdsRetryableStatuses,
    ...options,
    retryDelayInMs,
    retryDelay: (context) =>
      options.retryDelay?.(context) ??
      (context.response?.status === 410 && context.retryAfterInMs === undefined
        ? exponentialDelay(
            context.attempt,
            Math.max(imdsGoneRetryDelayInMs, retryDelayInMs),
            maxRetryDelayInMs,
          )
        : undefined),
  }
}
 
function tokenUrl(
  endpoint: string,
  apiVersion: string,
  resource: string,
  selector: ManagedIdentityOptions,
  resourceIdParameter: string,
): URL {
  const url = new URL(endpoint)
  url.searchParams.set('api-version', apiVersion)
  url.searchParams.set('resource', resource)
  for (const [name, value] of [
    ['client_id', selector.clientId],
    ['object_id', selector.objectId],
    [resourceIdParameter, selector.resourceId],
  ] as const) {
    if (value !== undefined) {
      url.searchParams.set(name, value)
    }
  }
 
  return url
}
 
/** IMDS answers a request without the metadata header immediately, so any response proves it is reachable. */
async function probeImds(
  endpoint: string,
  fetcher: typeof globalThis.fetch,
  signal: AbortSignal | undefined,
): Promise<void> {
  const timeout = AbortSignal.timeout(imdsProbeTimeoutMs)
  try {
    const response = await fetcher(endpoint, {
      redirect: 'manual',
      signal: signal === undefined ? timeout : AbortSignal.any([signal, timeout]),
    })
    await response.body?.cancel()
  } catch (error) {
    signal?.throwIfAborted()
    throw new TokenUnavailableError('IMDS endpoint unavailable', error)
  }
}
 
async function requestToken(
  url: URL,
  init: RequestInit,
  fetcher: typeof globalThis.fetch,
  retryOptions: RetryOptions | undefined,
): Promise<AccessToken> {
  let payload: unknown
  try {
    payload = await fetchJson(url, init, fetcher, retryOptions)
  } catch (error) {
    init.signal?.throwIfAborted()
    if (error instanceof TokenRequestError && error.status !== undefined && error.status < 500) {
      throw error
    }
 
    throw new TokenUnavailableError('Managed identity endpoint unavailable', error)
  }
 
  return normalizeToken(payload)
}