All files / mgmt-lambda/handlers updateHandler.ts

87.21% Statements 116/133
75.86% Branches 22/29
87.5% Functions 7/8
87.12% Lines 115/132

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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324    2x 2x                 2x               2x 2x 2x           2x 2x           2x         19x 19x   19x 15x 1x   14x 14x       14x   14x         11x 11x 1x 1x   10x 10x         10x 19x 10x 1x 1x     9x 9x   9x 1x 1x               8x       8x   2x                                   8x     8x 8x   8x 2x     6x   6x   6x 6x 6x 6x 6x   6x 3x 3x 3x           3x           6x 6x 1x     5x 5x 5x 4x 4x 4x 2x 2x 2x   2x 2x       2x     1x               6x 1x   5x 1x   4x 2x     2x           2x     2x 2x 2x     2x 2x 2x     2x 2x 2x         2x                                       2x                   2x 2x 2x             19x 19x     19x 19x   15x   15x                       14x 14x             14x   14x 14x           14x   14x 3x     11x   11x             10x 10x     10x 10x   10x   10x       10x    
import { APIGatewayProxyResult } from 'aws-lambda'
import type { DeploymentSettings } from '../model/DeploymentSettings'
import { defaults } from '../DefaultSettings'
import {
  CloudFrontClient,
  CreateInvalidationCommand,
  CreateInvalidationCommandInput,
  GetDistributionConfigCommand,
  GetDistributionConfigCommandOutput,
  UpdateDistributionCommand,
  UpdateDistributionCommandInput,
} from '@aws-sdk/client-cloudfront'
import {
  GetFunctionCommand,
  FunctionConfiguration,
  LambdaClient,
  ListVersionsByFunctionCommand,
  UpdateFunctionCodeCommand,
  UpdateFunctionCodeCommandOutput,
} from '@aws-sdk/client-lambda'
import { ApiException, ErrorCode } from '../exceptions'
import { delay } from '../utils/delay'
import {
  doesCacheBehaviorUseOrigins,
  getCacheBehaviorLambdaFunctionAssociations,
  getFPCDNOrigins,
} from '../utils/cloudfrontUtils'
 
const CLOUDFRONT_CONFIG_UPDATE_ATTEMPT_COUNT = 5
const CLOUDFRONT_CONFIG_UPDATE_ATTEMPT_DELAY = 3000 // Milliseconds
 
/**
 * @throws {ApiException}
 * @throws {import("@aws-sdk/client-lambda").LambdaServiceException}
 */
export async function handleUpdate(
  lambdaClient: LambdaClient,
  cloudFrontClient: CloudFrontClient,
  settings: DeploymentSettings
): Promise<APIGatewayProxyResult> {
  console.info(`Going to upgrade Fingerprint Pro function association at CloudFront distribution.`)
  console.info(`Settings: ${JSON.stringify(settings)}`)
 
  const functionInformationBeforeUpdate = await getLambdaFunctionInformation(lambdaClient, settings.LambdaFunctionName)
  if (!functionInformationBeforeUpdate?.FunctionArn) {
    throw new ApiException(ErrorCode.LambdaFunctionNotFound)
  }
  const currentRevisionId = functionInformationBeforeUpdate?.RevisionId
  Iif (!currentRevisionId) {
    console.error('Lambda@Edge function expected to have a revision ID of the current deployment')
    throw new ApiException(ErrorCode.LambdaFunctionCurrentRevisionNotDefined)
  }
  const currentCodeSha256 = functionInformationBeforeUpdate.CodeSha256
 
  const newVersionConfiguration = await updateLambdaFunctionCode(
    lambdaClient,
    settings.LambdaFunctionName,
    currentRevisionId
  )
  const newRevisionId = newVersionConfiguration.RevisionId
  if (!newRevisionId) {
    console.error('New revision for Lambda@Edge function was not created')
    throw new ApiException(ErrorCode.LambdaFunctionUpdateRevisionNotCreated)
  }
  const functionArn = newVersionConfiguration.FunctionArn
  Iif (!functionArn) {
    console.error('Function ARN for new version is not defined')
    throw new ApiException(ErrorCode.LambdaFunctionARNNotFound)
  }
 
  const listVersionsAfterUpdate = await listLambdaFunctionVersions(lambdaClient, settings.LambdaFunctionName)
  const newVersions = listVersionsAfterUpdate.filter((conf) => conf?.RevisionId === newRevisionId)
  if (newVersions.length !== 1) {
    console.error(`Excepted one new version, but found: ${newVersions.length} versions`)
    throw new ApiException(ErrorCode.LambdaFunctionWrongNewVersionsCount)
  }
 
  const newVersion = newVersions[0]
  const newVersionCodeSha256 = newVersion.CodeSha256
 
  if (currentCodeSha256 === newVersionCodeSha256) {
    console.info(`New version's code SHA256 is equal to the previous $LATEST code SHA256`)
    return {
      statusCode: 200,
      body: JSON.stringify({ status: 'Update is not required' }),
      headers: {
        'content-type': 'application/json',
      },
    }
  } else {
    console.info(
      `New version's SHA256 is not equals to the previous one. Continue with updating CloudFront resources...`
    )
  }
  await updateCloudFrontConfig(cloudFrontClient, settings.CFDistributionId, settings.LambdaFunctionName, functionArn)
 
  return {
    statusCode: 200,
    body: JSON.stringify({ status: 'Update completed' }),
    headers: {
      'content-type': 'application/json',
    },
  }
}
 
/**
 * @throws {ApiException}
 */
async function updateCloudFrontConfig(
  cloudFrontClient: CloudFrontClient,
  cloudFrontDistributionId: string,
  lambdaFunctionName: string,
  latestFunctionArn: string
) {
  const configParams = {
    Id: cloudFrontDistributionId,
  }
  const getConfigCommand = new GetDistributionConfigCommand(configParams)
  const cfConfig: GetDistributionConfigCommandOutput = await cloudFrontClient.send(getConfigCommand)
 
  if (!cfConfig.ETag || !cfConfig.DistributionConfig) {
    throw new ApiException(ErrorCode.CloudFrontDistributionNotFound)
  }
 
  const distributionConfig = cfConfig.DistributionConfig
 
  const { DefaultCacheBehavior, CacheBehaviors } = distributionConfig
 
  let fpCacheBehaviorsFound = 0
  let fpCacheBehaviorsUpdated = 0
  const invalidationPathPatterns: string[] = []
  const fpCDNOrigins = getFPCDNOrigins(distributionConfig)
  console.log('fpCDNOrigins.length', fpCDNOrigins?.length)
 
  if (doesCacheBehaviorUseOrigins(DefaultCacheBehavior, fpCDNOrigins)) {
    fpCacheBehaviorsFound++
    const lambdaAssocList = getCacheBehaviorLambdaFunctionAssociations(DefaultCacheBehavior, lambdaFunctionName)
    Iif (lambdaAssocList.length === 1) {
      lambdaAssocList[0].LambdaFunctionARN = latestFunctionArn
      fpCacheBehaviorsUpdated++
      invalidationPathPatterns.push('/*')
      console.info('Updated Fingerprint Pro Lambda@Edge function association in the default cache behavior')
    } else {
      console.info(
        'The default cache behavior has targeted to FP CDN, but has no Fingerprint Pro Lambda@Edge association'
      )
    }
  }
 
  for (const cacheBehavior of CacheBehaviors?.Items || []) {
    if (!doesCacheBehaviorUseOrigins(cacheBehavior, fpCDNOrigins)) {
      continue
    }
 
    fpCacheBehaviorsFound++
    const lambdaAssocList = getCacheBehaviorLambdaFunctionAssociations(cacheBehavior, lambdaFunctionName)
    if (lambdaAssocList?.length === 1) {
      lambdaAssocList[0].LambdaFunctionARN = latestFunctionArn
      fpCacheBehaviorsUpdated++
      if (cacheBehavior.PathPattern) {
        let pathPattern = cacheBehavior.PathPattern
        if (!cacheBehavior.PathPattern.startsWith('/')) {
          pathPattern = '/' + pathPattern
        }
        invalidationPathPatterns.push(pathPattern)
        console.info(
          `Updated Fingerprint Pro Lambda@Edge function association in the cache behavior with path ${cacheBehavior.PathPattern}`
        )
      } else {
        console.error(`Path pattern is not defined for cache behavior ${JSON.stringify(cacheBehavior)}`)
      }
    } else {
      console.info(
        `Cache behavior ${JSON.stringify(
          cacheBehavior
        )} has targeted to FP CDN, but has no Fingerprint Pro Lambda@Edge association`
      )
    }
  }
 
  if (fpCacheBehaviorsFound === 0) {
    throw new ApiException(ErrorCode.CacheBehaviorNotFound)
  }
  if (fpCacheBehaviorsUpdated === 0) {
    throw new ApiException(ErrorCode.LambdaFunctionAssociationNotFound)
  }
  if (invalidationPathPatterns.length === 0) {
    throw new ApiException(ErrorCode.CacheBehaviorPatternNotDefined)
  }
 
  const updateParams: UpdateDistributionCommandInput = {
    DistributionConfig: cfConfig.DistributionConfig,
    Id: cloudFrontDistributionId,
    IfMatch: cfConfig.ETag,
  }
 
  const updateConfigCommand = new UpdateDistributionCommand(updateParams)
  let updateCFResult: UpdateFunctionCodeCommandOutput
 
  let triedAttempts = 0
  while (triedAttempts < CLOUDFRONT_CONFIG_UPDATE_ATTEMPT_COUNT) {
    console.info(
      `Attempt ${triedAttempts + 1}/${CLOUDFRONT_CONFIG_UPDATE_ATTEMPT_COUNT} started to update CloudFront config`
    )
    try {
      updateCFResult = await cloudFrontClient.send(updateConfigCommand)
      console.info(
        `CloudFront config updated successfully on attempt ${triedAttempts + 1}/${CLOUDFRONT_CONFIG_UPDATE_ATTEMPT_COUNT}`
      )
      console.info(`CloudFront update has finished, ${JSON.stringify(updateCFResult)}`)
      console.info('Going to invalidate routes for upgraded cache behavior')
      invalidateFingerprintIntegrationCache(cloudFrontClient, cloudFrontDistributionId, invalidationPathPatterns).catch(
        (e) => {
          console.info(`Cache invalidation has failed: ${e.message}`)
        }
      )
      return
    } catch (e) {
      console.error(
        `Attempt ${triedAttempts + 1}/${CLOUDFRONT_CONFIG_UPDATE_ATTEMPT_COUNT} failed for updating CloudFront config`,
        e
      )
      Iif (triedAttempts + 1 === CLOUDFRONT_CONFIG_UPDATE_ATTEMPT_COUNT) {
        throw e
      }
      await delay(CLOUDFRONT_CONFIG_UPDATE_ATTEMPT_DELAY)
    }
    triedAttempts++
  }
}
 
async function invalidateFingerprintIntegrationCache(
  cloudFrontClient: CloudFrontClient,
  distributionId: string,
  pathPatterns: string[]
) {
  const invalidationParams: CreateInvalidationCommandInput = {
    DistributionId: distributionId,
    InvalidationBatch: {
      Paths: {
        Quantity: 1,
        Items: pathPatterns,
      },
      CallerReference: 'fingerprint-pro-management-lambda-function',
    },
  }
  const invalidationCommand = new CreateInvalidationCommand(invalidationParams)
  const invalidationResult = await cloudFrontClient.send(invalidationCommand)
  console.info(`Invalidation has finished, ${JSON.stringify(invalidationResult)}`)
}
 
async function getLambdaFunctionInformation(
  lambdaClient: LambdaClient,
  functionName: string
): Promise<FunctionConfiguration | undefined> {
  console.info(`Getting lambda function information for ${functionName}`)
  const command = new GetFunctionCommand({
    FunctionName: functionName,
  })
  console.info(`Sending get command to Lambda runtime with data ${JSON.stringify(command)}`)
  const result = await lambdaClient.send(command)
 
  console.info(`Got get command result: ${JSON.stringify(result)}`)
 
  return result.Configuration
}
 
/**
 * @throws {import("@aws-sdk/client-lambda").LambdaServiceException}
 * @throws {ApiException}
 */
async function updateLambdaFunctionCode(
  lambdaClient: LambdaClient,
  functionName: string,
  revisionId: string
): Promise<FunctionConfiguration> {
  console.info('Preparing command to update function code')
  const command = new UpdateFunctionCodeCommand({
    S3Bucket: defaults.LAMBDA_DISTRIBUTION_BUCKET,
    S3Key: defaults.LAMBDA_DISTRIBUTION_BUCKET_KEY,
    FunctionName: functionName,
    RevisionId: revisionId,
    Publish: true,
  })
  console.info(`Sending update command to Lambda runtime with data ${JSON.stringify(command)}`)
  let result: FunctionConfiguration
  try {
    result = await lambdaClient.send(command)
  } catch (e) {
    console.error(`Lambda function update has failed. Error: ${e}`)
    throw new ApiException(ErrorCode.LambdaFunctionUpdateFailed)
  }
 
  console.info(`Got update command result: ${JSON.stringify(result)}`)
 
  if (!result?.FunctionArn) {
    throw new ApiException(ErrorCode.LambdaFunctionARNNotFound)
  }
 
  console.info(`Got Lambda function update result, functionARN: ${result.FunctionArn}`)
 
  return result
}
 
async function listLambdaFunctionVersions(
  lambdaClient: LambdaClient,
  functionName: string
): Promise<FunctionConfiguration[]> {
  console.info('Getting Lambda function versions')
  const command = new ListVersionsByFunctionCommand({
    FunctionName: functionName,
  })
  console.info(`Sending ListVersionsByFunctionCommand to with data ${JSON.stringify(command)}`)
  const result = await lambdaClient.send(command)
 
  console.info(`Got ListVersionsByFunctionCommand result: ${JSON.stringify(result)}`)
 
  Iif (!result) {
    throw new ApiException(ErrorCode.LambdaFunctionARNNotFound)
  }
 
  return result.Versions || []
}