All files / secrets index.ts

86.61% Statements 233/269
83.87% Branches 26/31
87.5% Functions 7/8
86.61% Lines 233/269

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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 2701x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 1x 1x 8x 9x 1x 1x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 7x 1x 1x 7x 1x 1x 1x 1x 1x 1x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x                             9x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 10x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x     9x 9x 9x 9x         9x 9x 9x 9x 10x                     10x 7x 7x 7x 21x 21x 21x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x  
import {
  SecretsManagerClient,
  GetSecretValueCommand,
  type SecretsManagerClientConfig,
} from '@aws-sdk/client-secrets-manager'
import { SecretConfig, RetryConfig } from './types'
 
const DEFAULT_RETRY_CONFIG: RetryConfig = {
  maxAttempts: 3,
  delayMs: 1000,
}
 
/**
 * Validate the configuration object.
 *
 * @param {SecretConfig} config - The configuration object containing the secret name and region.
 * @returns {void}
 */
 
/**
 * Validate the configuration object.
 *
 * @param {SecretConfig} config - The configuration object containing the secret name and region.
 * @returns {void}
 */
/**
 * Validate the configuration object.
 *
 * @param {SecretConfig} config - The configuration object containing the secret name and region.
 * @returns {void}
 */
function validateConfig(config: SecretConfig): void {
  if (!config.region) {
    throw new Error('AWS region is required')
  }
 
  if (!config.secretName) {
    throw new Error('Secret name is required')
  }
}
 
/**
 * Create a Secrets Manager client configuration.
 *
 * @param {SecretConfig} config - The configuration object containing the secret name and region.
 * @returns {SecretsManagerClientConfig} A Secrets Manager client configuration.
 *
 * @example
 * ```typescript
 * const clientConfig = createClientConfig({
 *   secretName: 'dev/video-microservice/env',
 *   region: 'us-east-2',
 * })
 * // Output: { region: 'us-east-2', maxAttempts: 3 }
 * ```
 */
function createClientConfig(config: SecretConfig): SecretsManagerClientConfig {
  const clientConfig: SecretsManagerClientConfig = {
    region: config.region,
    maxAttempts: DEFAULT_RETRY_CONFIG.maxAttempts,
  }
 
  // Use IAM roles if available, otherwise use provided credentials
  if (
    process.env['AWS_ACCESS_KEY_ID'] &&
    process.env['AWS_SECRET_ACCESS_KEY']
  ) {
    // Use environment variables (IAM roles or default credentials)
    console.log('Using AWS credentials from environment variables')
  } else if (config.accessKeyId && config.secretAccessKey) {
    // Use provided credentials
    clientConfig.credentials = {
      accessKeyId: config.accessKeyId,
      secretAccessKey: config.secretAccessKey,
    }
  }
 
  return clientConfig
}
 
/**
 * Delay for a given number of milliseconds.
 *
 * @param {number} ms - The number of milliseconds to delay.
 * @returns {Promise<void>} A promise that resolves after the delay.
 *
 * @example
 * ```typescript
 * await delay(1000)
 * // Output: A promise that resolves after 1 second
 * ```
 */
async function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms))
}
 
/**
 * Retry an operation with exponential backoff.
 *
 * @param {() => Promise<T>} operation - The operation to retry.
 * @param {RetryConfig} [retryConfig] - The retry configuration for the operation.
 * @returns {Promise<T>} A promise that resolves to the result of the operation.
 *
 * @example
 * ```typescript
 * const result = await retryWithBackoff(async () => {
 *   return await someOperation()
 * })
 * // Output: The result of the operation
 * ```
 */
async function retryWithBackoff<T>(
  operation: () => Promise<T>,
  retryConfig: RetryConfig = DEFAULT_RETRY_CONFIG
): Promise<T> {
  let lastError: Error
 
  for (let attempt = 1; attempt <= retryConfig.maxAttempts; attempt++) {
    try {
      return await operation()
    } catch (error) {
      lastError = error instanceof Error ? error : new Error(String(error))

      if (attempt === retryConfig.maxAttempts) {
        throw lastError
      }

      // Exponential backoff
      const delayTime = retryConfig.delayMs * Math.pow(2, attempt - 1)
      console.warn(
        `Attempt ${attempt} failed, retrying in ${delayTime}ms:`,
        lastError.message
      )
      await delay(delayTime)
    }
  }

  throw lastError!
}
 
/**
 * Load secrets from AWS Secrets Manager.
 *
 * @param {SecretConfig} config - The configuration object containing the secret name and region.
 * @param {RetryConfig} [retryConfig] - The retry configuration for the operation.
 * @returns {Promise<Record<string, string>>} A promise that resolves to a record of secret names and their values.
 *
 * @example
 * ```typescript
 * const secrets = await loadSecrets({
 *   secretName: 'dev/video-microservice/env',
 *   region: 'us-east-2',
 * })
 * // Output: { NODE_ENV: 'development', DATABASE_URL: '...', API_KEY: '...', ... }
 * ```
 */
export async function loadSecrets(
  config: SecretConfig,
  retryConfig?: RetryConfig
): Promise<Record<string, string>> {
  validateConfig(config)
 
  const clientConfig = createClientConfig(config)
  const client = new SecretsManagerClient(clientConfig)
 
  const secretNames = Array.isArray(config.secretName)
    ? config.secretName
    : [config.secretName]
 
  const allSecrets: Record<string, string> = {}
 
  for (const secretName of secretNames) {
    if (!secretName || typeof secretName !== 'string') {
      console.warn('Invalid secret name provided, skipping')
      continue
    }
 
    try {
      const secrets = await retryWithBackoff(async () => {
        const command = new GetSecretValueCommand({
          SecretId: secretName,
        })
 
        const response = await client.send(command)
 
        if (!response.SecretString) {
          throw new Error(`Secret ${secretName} not found or empty`)
        }
 
        try {
          return JSON.parse(response.SecretString)
        } catch (parseError) {
          throw new Error(
            `Failed to parse secret ${secretName} as JSON: ${parseError instanceof Error ? parseError.message : 'Unknown error'}`
          )
        }
      }, retryConfig)
 
      Object.assign(allSecrets, secrets)
      console.log(`Successfully loaded secret: ${secretName}`)
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : 'Unknown error'
      console.error(`Error loading secret ${secretName}: ${errorMessage}`)

      // In production, you might want to throw the error
      // For now, we'll continue with other secrets
      if (process.env['NODE_ENV'] === 'production') {
        throw error
      }
    }
  }
 
  // Set environment variables
  Object.entries(allSecrets).forEach(([key, value]) => {
    if (key && value !== undefined && value !== null) {
      process.env[key] = String(value)
    }
  })
 
  return allSecrets
}
 
/**
 * Test function to display all saved secrets in the environment variables.
 * This function logs all environment variables to the console for debugging purposes.
 * Useful for verifying that secrets were properly loaded and set as environment variables.
 *
 * @example
 * ```typescript
 * testSavedSecrets()
 * // Output: { NODE_ENV: 'development', DATABASE_URL: '...', API_KEY: '...', ... } 'SAVED SECRETS'
 * ```
 */
export function testSavedSecrets(): void {
  console.log(process.env, 'SAVED SECRETS')
}
 
/**
 * Check if the current process is running on AWS (EC2, Lambda, etc.).
 *
 * @returns {boolean} True if running on AWS, false otherwise.
 *
 * @example
 * ```typescript
 * isRunningOnAWS()
 * // Output: true
 * ```
 */
export function isRunningOnAWS(): boolean {
  return !!(
    process.env['AWS_EXECUTION_ENV'] || process.env['AWS_LAMBDA_FUNCTION_NAME']
  )
}
 
/**
 * Get the AWS region from the environment variables.
 *
 * @returns {string | undefined} The AWS region.
 *
 * @example
 * ```typescript
 * getAWSRegion()
 * // Output: 'us-east-1'
 * ```
 */
export function getAWSRegion(): string | undefined {
  return process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION']
}