All files / src service-principal.ts

100% Statements 16/16
90% Branches 9/10
100% Functions 1/1
100% Lines 16/16

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                                                      49x 49x 144x 3x       46x 46x 46x 46x     49x     49x 49x                                 11x 11x 6x     1x               32x    
import { fetchJson, normalizeToken } from './internal/oauth'
import { resolveRequiredScopes } from './internal/request-core'
import type { RetryOptions } from './internal/request-core'
import { defaultFetch } from './internal/runtime'
import { requireTenantId, tokenRequestClaims } from './internal/token-options'
import { sanitizeAuthorityHost } from './internal/url'
import { TokenRequestError } from './token-request-error'
import type { AccessToken } from './types'
 
export interface ServicePrincipalOptions {
  tenantId: string
  clientId: string
  clientSecret: string
  scope: string | string[]
  authorityHost?: string
  abortSignal?: AbortSignal
  /** JSON claims challenge to send with the request. */
  claims?: string
  /** Requests a token for continuous access evaluation. */
  enableCae?: boolean
  retryOptions?: RetryOptions
  fetch?: typeof globalThis.fetch
}
 
export async function getServicePrincipalToken(
  options: ServicePrincipalOptions,
): Promise<AccessToken> {
  const { tenantId, clientId, clientSecret, abortSignal } = options
  for (const [name, value] of Object.entries({ tenantId, clientId, clientSecret })) {
    if (value.length === 0) {
      throw new TypeError(`${name} is required`)
    }
  }
 
  const validatedTenant = requireTenantId(tenantId)
  const scopes = resolveRequiredScopes(options.scope)
  const claims = tokenRequestClaims(options.claims, options.enableCae)
  const authorityHost = sanitizeAuthorityHost(
    options.authorityHost ?? 'https://login.microsoftonline.com',
  )
  abortSignal?.throwIfAborted()
 
  let payload: unknown
  try {
    payload = await fetchJson(
      `${authorityHost}/${validatedTenant}/oauth2/v2.0/token`,
      {
        method: 'POST',
        body: new URLSearchParams({
          client_id: clientId,
          client_secret: clientSecret,
          grant_type: 'client_credentials',
          scope: scopes.join(' '),
          ...(claims === undefined ? {} : { claims }),
        }),
        signal: abortSignal,
      },
      options.fetch ?? defaultFetch,
      options.retryOptions,
    )
  } catch (error) {
    abortSignal?.throwIfAborted()
    if (error instanceof TokenRequestError) {
      throw error
    }
 
    throw new TokenRequestError(
      'Failed to request service principal token',
      undefined,
      undefined,
      error,
    )
  }
 
  return normalizeToken(payload)
}