From 9ebb84a745176e9b67d481995945fed5d2477d4c Mon Sep 17 00:00:00 2001 From: Nico Tonnhofer Date: Mon, 25 Mar 2024 20:10:32 +0000 Subject: [PATCH] fix(elasticloadbalancingv2): least privilege invoke permission --- .../lib/lambda-target.ts | 6 ++---- .../test/lambda-target.test.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/aws-cdk-lib/aws-elasticloadbalancingv2-targets/lib/lambda-target.ts b/packages/aws-cdk-lib/aws-elasticloadbalancingv2-targets/lib/lambda-target.ts index b861e125d5a18..29b41c07e2fdf 100644 --- a/packages/aws-cdk-lib/aws-elasticloadbalancingv2-targets/lib/lambda-target.ts +++ b/packages/aws-cdk-lib/aws-elasticloadbalancingv2-targets/lib/lambda-target.ts @@ -18,8 +18,7 @@ export class LambdaTarget implements elbv2.IApplicationLoadBalancerTarget { * load balancer. */ public attachToApplicationTargetGroup(targetGroup: elbv2.IApplicationTargetGroup): elbv2.LoadBalancerTargetProps { - const grant = this.fn.grantInvoke(new iam.ServicePrincipal('elasticloadbalancing.amazonaws.com')); - grant.applyBefore(targetGroup); + this.fn.addPermission('Permission', { principal: new iam.ServicePrincipal('elasticloadbalancing.amazonaws.com'), sourceArn: targetGroup.targetGroupArn }); return this.attach(targetGroup); } @@ -30,8 +29,7 @@ export class LambdaTarget implements elbv2.IApplicationLoadBalancerTarget { * load balancer. */ public attachToNetworkTargetGroup(targetGroup: elbv2.INetworkTargetGroup): elbv2.LoadBalancerTargetProps { - const grant = this.fn.grantInvoke(new iam.ServicePrincipal('elasticloadbalancing.amazonaws.com')); - grant.applyBefore(targetGroup); + this.fn.addPermission('Permission', { principal: new iam.ServicePrincipal('elasticloadbalancing.amazonaws.com'), sourceArn: targetGroup.targetGroupArn }); return this.attach(targetGroup); } diff --git a/packages/aws-cdk-lib/aws-elasticloadbalancingv2-targets/test/lambda-target.test.ts b/packages/aws-cdk-lib/aws-elasticloadbalancingv2-targets/test/lambda-target.test.ts index 7f3be404e0563..d2f91d13443fb 100644 --- a/packages/aws-cdk-lib/aws-elasticloadbalancingv2-targets/test/lambda-target.test.ts +++ b/packages/aws-cdk-lib/aws-elasticloadbalancingv2-targets/test/lambda-target.test.ts @@ -48,3 +48,16 @@ test('Lambda targets create dependency on Invoke permission', () => { return (def.DependsOn ?? []).includes('FunInvokeServicePrincipalelasticloadbalancingamazonawscomD2CAC0C4'); }); }); + +test('Lambda targets create least privilege permission', () => { + // WHEN + listener.addTargets('Targets', { + targets: [new targets.LambdaTarget(fn)], + }); + + // THEN + Template.fromStack(stack).hasResourceProperties('AWS::Lambda::Permission', { + Principal: 'elasticloadbalancing.amazonaws.com', + SourceArn: { Ref: 'LBListenerTargetsGroup76EF81E8' }, + }); +});