All files / mgmt-lambda auth.ts

100% Statements 24/24
100% Branches 7/7
100% Functions 2/2
100% Lines 24/24

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    2x   2x 2x   2x 27x 27x 2x     25x 25x       25x   25x 1x   24x 23x   1x   1x       2x     27x 27x 1x     26x 26x 24x   2x    
import { APIGatewayProxyEventV2WithRequestContext, APIGatewayEventRequestContextV2 } from 'aws-lambda'
import type { AuthSettings } from './model/AuthSettings'
import { SecretsManagerClient, GetSecretValueCommand, GetSecretValueResponse } 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) {
    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) {
      return JSON.parse(Buffer.from(response.SecretBinary).toString('utf8'))
    }
    if (response.SecretString) {
      return JSON.parse(response.SecretString)
    }
    throw new Error('secret is empty')
  } catch (error: any) {
    throw new Error(`Unable to retrieve secret. ${error}`)
  }
}
 
export function retrieveAuthToken(
  event: APIGatewayProxyEventV2WithRequestContext<APIGatewayEventRequestContextV2>
): string {
  const authorization = event.headers['authorization']
  if (!authorization) {
    return EMPTY_TOKEN
  }
 
  const [type, token] = authorization.split(' ')
  if (type == MGMT_TOKEN_SCHEME) {
    return token || EMPTY_TOKEN
  }
  return EMPTY_TOKEN
}