From 3123eb57885bafb37b56b8fa33bdc16a2da9d61c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 07:41:43 +0000 Subject: [PATCH 1/3] test: reproduce duplicate association when attaching a new function version attatchEdgeFunction only removes an association whose ARN matches exactly before appending, so attaching edge-fn:3 while edge-fn:2 is on viewer-request leaves two viewer-request associations (Quantity 2). CloudFront allows only one function per event type. The existing fixtures ('edge-lambda-arn') have no version, so they did not cover this case. These tests use versioned ARN fixtures and fail on the current code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Bmzxkp9hit6dRSrgRbVgx4 --- __tests__/configUpdator.test.ts | 143 ++++++++++++++++++++++++++++++++ __tests__/controller.test.ts | 49 +++++++++++ 2 files changed, 192 insertions(+) diff --git a/__tests__/configUpdator.test.ts b/__tests__/configUpdator.test.ts index 8cec9de..3011383 100644 --- a/__tests__/configUpdator.test.ts +++ b/__tests__/configUpdator.test.ts @@ -1,5 +1,31 @@ +import type { DistributionConfig, LambdaFunctionAssociation } from '@aws-sdk/client-cloudfront' import Updator from '../libs/configUpdator' +// Lambda@Edge only accepts versioned function ARNs, so these fixtures carry a version. +const functionArn = (name: string, version: number): string => + `arn:aws:lambda:us-east-1:123456789012:function:${name}:${version}` + +const createDistributionConfig = ( + items: LambdaFunctionAssociation[], + cacheBehaviors?: unknown +): DistributionConfig => ({ + DefaultCacheBehavior: { + LambdaFunctionAssociations: { + Quantity: items.length, + Items: items + } + }, + ...(cacheBehaviors ? { CacheBehaviors: cacheBehaviors } : {}) +}) as unknown as DistributionConfig + +const countByEventType = (items: LambdaFunctionAssociation[]): Record => { + return items.reduce((counts: Record, item) => { + const key = String(item.EventType) + counts[key] = (counts[key] || 0) + 1 + return counts + }, {}) +} + describe('libs/configUpdator.ts', () => { describe('constructor', () => { it('should set valid arn', () => { @@ -240,4 +266,121 @@ describe('libs/configUpdator.ts', () => { }) }) }) + describe('with versioned Lambda function ARNs', () => { + let updator: Updator + beforeEach(() => { + updator = new Updator(functionArn('edge-fn', 3), 'viewer-request') + }) + describe('#attatchEdgeFunction()', () => { + it('should replace another version of the same function on the same event type', () => { + const config = createDistributionConfig([ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) } + ]) + const result = updator.attatchEdgeFunction(config) + expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({ + Quantity: 1, + Items: [ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) } + ] + }) + }) + it('should replace a different function on the same event type', () => { + const config = createDistributionConfig([ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('other-fn', 1) } + ]) + const result = updator.attatchEdgeFunction(config) + expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({ + Quantity: 1, + Items: [ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) } + ] + }) + }) + it('should keep associations for other event types and keep Quantity equal to the number of Items', () => { + const originRequest = { + EventType: 'origin-request', + LambdaFunctionARN: functionArn('origin-fn', 5), + IncludeBody: true + } as LambdaFunctionAssociation + const viewerResponse = { + EventType: 'viewer-response', + LambdaFunctionARN: functionArn('response-fn', 1) + } as LambdaFunctionAssociation + const config = createDistributionConfig([ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) }, + originRequest, + viewerResponse + ]) + const result = updator.attatchEdgeFunction(config) + const associations = result.DefaultCacheBehavior?.LambdaFunctionAssociations + const items = associations?.Items || [] + expect(items).toHaveLength(3) + expect(associations?.Quantity).toEqual(items.length) + expect(items).toEqual(expect.arrayContaining([ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) }, + { EventType: 'origin-request', LambdaFunctionARN: functionArn('origin-fn', 5), IncludeBody: true }, + { EventType: 'viewer-response', LambdaFunctionARN: functionArn('response-fn', 1) } + ])) + expect(countByEventType(items)).toEqual({ + 'viewer-request': 1, + 'origin-request': 1, + 'viewer-response': 1 + }) + }) + it('should not change the other cache behaviors', () => { + const cacheBehaviors = { + Quantity: 1, + Items: [ + { + PathPattern: '/api/*', + LambdaFunctionAssociations: { + Quantity: 1, + Items: [ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) } + ] + } + } + ] + } + const expectedCacheBehaviors = JSON.parse(JSON.stringify(cacheBehaviors)) + const config = createDistributionConfig([ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) } + ], cacheBehaviors) + const result = updator.attatchEdgeFunction(config) + expect(result.CacheBehaviors).toEqual(expectedCacheBehaviors) + expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({ + Quantity: 1, + Items: [ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) } + ] + }) + }) + it('should keep a single association when the same version is attached again', () => { + const config = createDistributionConfig([ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) } + ]) + const result = updator.attatchEdgeFunction(config) + expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({ + Quantity: 1, + Items: [ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) } + ] + }) + }) + }) + describe('#detatchEdgeFunction()', () => { + it('should remove only the exact function version', () => { + const config = createDistributionConfig([ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) } + ]) + const result = updator.detatchEdgeFunction(config) + expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({ + Quantity: 1, + Items: [ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) } + ] + }) + }) + }) + }) }) diff --git a/__tests__/controller.test.ts b/__tests__/controller.test.ts index 42ac271..dc259a3 100644 --- a/__tests__/controller.test.ts +++ b/__tests__/controller.test.ts @@ -1,3 +1,4 @@ +import { CloudFrontClient, GetDistributionCommand, UpdateDistributionCommand, UpdateDistributionCommandInput } from '@aws-sdk/client-cloudfront' import Controller from '../libs/controller' describe('libs/contorller.ts', () => { @@ -8,4 +9,52 @@ describe('libs/contorller.ts', () => { }).not.toThrow() }) }) + describe('#attachEdgeFunction()', () => { + const functionArn = (name: string, version: number): string => + `arn:aws:lambda:us-east-1:123456789012:function:${name}:${version}` + + it('should send a single viewer-request association when another version is already attached', async () => { + const updateInputs: UpdateDistributionCommandInput[] = [] + const cloudfront = { + send: async (command: unknown) => { + if (command instanceof GetDistributionCommand) { + return { + ETag: 'etag', + Distribution: { + Id: 'EDISTRIBUTIONID', + DistributionConfig: { + DefaultCacheBehavior: { + LambdaFunctionAssociations: { + Quantity: 1, + Items: [ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) } + ] + } + } + } + } + } + } + if (command instanceof UpdateDistributionCommand) { + updateInputs.push(command.input) + return {} + } + throw new Error('unexpected command') + } + } as unknown as CloudFrontClient + const controller = new Controller(functionArn('edge-fn', 3), 'viewer-request', { cloudfront }) + + await controller.attachEdgeFunction('EDISTRIBUTIONID') + + expect(updateInputs).toHaveLength(1) + expect(updateInputs[0].Id).toEqual('EDISTRIBUTIONID') + expect(updateInputs[0].IfMatch).toEqual('etag') + expect(updateInputs[0].DistributionConfig?.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({ + Quantity: 1, + Items: [ + { EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) } + ] + }) + }) + }) }) From 060a3630d27c17c4362288ca0f976328407de778 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 07:42:27 +0000 Subject: [PATCH 2/3] fix: replace the association on the same event type when attaching CloudFront allows only one function per event type in a cache behavior. attatchEdgeFunction now drops every association whose EventType equals the target event type of the default cache behavior before appending the new one, instead of dropping only an exact ARN match. Attaching edge-fn:3 while edge-fn:2 (or another function) is on viewer-request now leaves a single viewer-request association. Associations for other event types and the other cache behaviors are left unchanged. detatchEdgeFunction still removes only the exact ARN. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Bmzxkp9hit6dRSrgRbVgx4 --- libs/configUpdator.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/libs/configUpdator.ts b/libs/configUpdator.ts index ca7d4c3..79eb716 100644 --- a/libs/configUpdator.ts +++ b/libs/configUpdator.ts @@ -130,6 +130,10 @@ export class ConfigUpdator { /** * update distribution config to attach edge function * + * CloudFront allows only one function per event type in a cache behavior, + * so any function (or function version) already associated with the target + * event type of the default cache behavior is replaced. + * * @param {CloudFront.Types.DistributionConfig} config - CloudFront distribution config * @return {CloudFront.Types.DistributionConfig} updated distribution config **/ @@ -142,11 +146,11 @@ export class ConfigUpdator { LambdaFunctionARN: this.getLambdaArn(), EventType: this.eventType } - if (!lambdas.Items) { - lambdas.Items = [newItem] - } else { - lambdas.Items.push(newItem) - } + const newLambdaItems: LambdaFunctionAssociation[] = (lambdas.Items || []).filter( + (item: LambdaFunctionAssociation) => item.EventType !== this.eventType + ) + newLambdaItems.push(newItem) + lambdas.Items = newLambdaItems lambdas.Quantity = lambdas.Items.length defaultCacheBehavior.LambdaFunctionAssociations = lambdas return param From 41bfc744027e617018a38fc5df60172acdc28503 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 07:42:44 +0000 Subject: [PATCH 3/3] docs: describe how attach and detach treat existing associations Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Bmzxkp9hit6dRSrgRbVgx4 --- README.md | 6 ++++-- README_ja.md | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 867a711..9c3d610 100644 --- a/README.md +++ b/README.md @@ -108,10 +108,12 @@ new LambdaEdgeController( ### Methods #### `attachEdgeFunction(distributionId: string): Promise` -Attaches the Lambda@Edge function to the specified CloudFront distribution. +Attaches the Lambda@Edge function to the default cache behavior of the specified CloudFront distribution. + +CloudFront allows only one function per event type in a cache behavior. If a function is already associated with the same event type (another version of the same function, or a different function), it is replaced by the function given to the constructor. Associations for other event types and the other cache behaviors are left unchanged. #### `detachEdgeFunction(distributionId: string): Promise` -Removes the Lambda@Edge function from the specified CloudFront distribution. +Removes the Lambda@Edge function from the default cache behavior of the specified CloudFront distribution. Only the association for the constructor's event type whose ARN (including the version) exactly matches the ARN given to the constructor is removed. #### `enableDebugger(): this` Enables detailed logging for debugging purposes. diff --git a/README_ja.md b/README_ja.md index 061c20d..aecba18 100644 --- a/README_ja.md +++ b/README_ja.md @@ -108,10 +108,12 @@ new LambdaEdgeController( ### メソッド #### `attachEdgeFunction(distributionId: string): Promise` -指定されたCloudFrontディストリビューションにLambda@Edge関数をアタッチします。 +指定されたCloudFrontディストリビューションのデフォルトキャッシュ動作にLambda@Edge関数をアタッチします。 + +CloudFrontでは、1つのキャッシュ動作につき、1つのイベントタイプに関連付けられる関数は1つだけです。同じイベントタイプに関数(同じ関数の別バージョン、または別の関数)がすでに関連付けられている場合は、コンストラクタに渡した関数に置き換えます。ほかのイベントタイプの関連付けと、ほかのキャッシュ動作は変更しません。 #### `detachEdgeFunction(distributionId: string): Promise` -指定されたCloudFrontディストリビューションからLambda@Edge関数を削除します。 +指定されたCloudFrontディストリビューションのデフォルトキャッシュ動作からLambda@Edge関数を削除します。削除するのは、コンストラクタに渡したイベントタイプの関連付けのうち、ARN(バージョンを含む)がコンストラクタに渡したARNと完全に一致するものだけです。 #### `enableDebugger(): this` デバッグ目的で詳細なログを有効化します。