All files / proxy/utils/customer-variables/secrets-manager retrieve-secret.ts

100% Statements 22/22
100% Branches 8/8
100% Functions 4/4
100% Lines 22/22

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                        7x           30x 30x 19x     11x   11x   11x       9x 3x   6x         11x 11x     11x   9x   9x 4x     5x 5x 5x   2x   2x         11x    
import type { CustomerVariablesRecord } from '../types.ts'
import type { GetSecretValueCommandOutput, SecretsManagerClient } from '@aws-sdk/client-secrets-manager'
import { GetSecretValueCommand } from '@aws-sdk/client-secrets-manager'
import { arrayBufferToString } from '../../buffer.ts'
import { validateSecret } from './validate-secret.ts'
import { normalizeSecret } from './normalize-secret.ts'
import { TTLCache } from '../../cache.ts'
 
/**
 * Global cache for customer variables fetched from Secrets Manager.
 * By default, the cache is set to expire after 5 minutes.
 * */
const cache = new TTLCache<string, CustomerVariablesRecord | null>(300_000)
 
/**
 * Retrieves a secret from Secrets Manager and caches it or returns it from cache if it's still valid.
 * */
export async function retrieveSecret(secretsManager: SecretsManagerClient, key: string, cacheTtlMs?: number) {
  const cached = cache.get(key)
  if (cached !== undefined) {
    return cached
  }
 
  const result = await fetchSecret(secretsManager, key)
 
  cache.set(key, result, cacheTtlMs)
 
  return result
}
 
function convertSecretToString(result: GetSecretValueCommandOutput): string {
  if (result.SecretBinary) {
    return arrayBufferToString(result.SecretBinary)
  } else {
    return result.SecretString ?? ''
  }
}
 
async function fetchSecret(secretsManager: SecretsManagerClient, key: string): Promise<CustomerVariablesRecord | null> {
  try {
    const command = new GetSecretValueCommand({
      SecretId: key,
    })
    const result = await secretsManager.send(command)
 
    const secretString = convertSecretToString(result)
 
    if (!secretString) {
      return null
    }
 
    const parsedSecret = normalizeSecret(secretString)
    validateSecret(parsedSecret)
    return parsedSecret
  } catch (error) {
    console.error(`Failed to fetch and parse secret ${key}`, { error })
 
    return null
  }
}
 
export function clearSecretsCache() {
  cache.clear()
}