All files / mgmt-lambda auth.ts

100% Statements 21/21
100% Branches 18/18
100% Functions 2/2
100% Lines 21/21

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          2x 2x     27x 27x 2x     25x 25x       25x   25x     1x   24x   23x   1x   1x             27x 27x 1x     26x 26x       24x   2x    
import type { APIGatewayProxyEventV2WithRequestContext, APIGatewayEventRequestContextV2 } from 'aws-lambda'
import type { AuthSettings } from './model/AuthSettings.ts'
import type { SecretsManagerClient, GetSecretValueResponse } from '@aws-sdk/client-secrets-manager'
import { GetSecretValueCommand } from '@aws-sdk/client-secrets-manager'
 
const MGMT_TOKEN_SCHEME = 'mgmt-token'
const EMPTY_TOKEN = ''
 
export async function getAuthSettings(secretManagerClient: SecretsManagerClient): Promise<AuthSettings> {
  const secretName = process.env.SettingsSecretName
  if (secretName === undefined || secretName === '') {
    throw new Error('Unable to retrieve secret. Error: environment variable SettingsSecretName not found')
  }
 
  try {
    const command = new GetSecretValueCommand({
      SecretId: secretName,
    })
 
    const response: GetSecretValueResponse = await secretManagerClient.send(command)
 
    if (response.SecretBinary) {
      // Secrets Manager payload isn't schema-validated at runtime; trust its shape here.
      // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
      return JSON.parse(Buffer.from(response.SecretBinary).toString('utf8')) as AuthSettings
    }
    if (response.SecretString !== undefined && response.SecretString !== '') {
      // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
      return JSON.parse(response.SecretString) as AuthSettings
    }
    throw new Error('secret is empty')
  } catch (error) {
    throw new Error(`Unable to retrieve secret. ${String(error)}`)
  }
}
 
export function retrieveAuthToken(
  event: APIGatewayProxyEventV2WithRequestContext<APIGatewayEventRequestContextV2>
): string {
  const authorization = event.headers['authorization']
  if (authorization === undefined || authorization === '') {
    return EMPTY_TOKEN
  }
 
  const [type, token] = authorization.split(' ')
  if (type === MGMT_TOKEN_SCHEME) {
    // Without a space in the header, destructuring leaves token undefined at runtime even though
    // TS's array indexing (without noUncheckedIndexedAccess) assumes it's always string.
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    return token ?? EMPTY_TOKEN
  }
  return EMPTY_TOKEN
}