Skip to content

Commit

Permalink
fix(elasticloadbalancingv2): logAccessLogs in Base Load Balancer (#6197)
Browse files Browse the repository at this point in the history
Moving the method logAccessLogs to the Base Load Balancer, so both types
of Load Balancer (Network and Application) can use the method.

closes #3794

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
rzamana and mergify[bot] authored Feb 11, 2020
1 parent 23f8b9f commit adbc3b9
Show file tree
Hide file tree
Showing 3 changed files with 163 additions and 60 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as s3 from '@aws-cdk/aws-s3';
import { Construct, Duration, Lazy, Resource, Stack, Token } from '@aws-cdk/core';
import { Construct, Duration, Lazy, Resource } from '@aws-cdk/core';
import { BaseLoadBalancer, BaseLoadBalancerProps, ILoadBalancerV2 } from '../shared/base-load-balancer';
import { IpAddressType } from '../shared/enums';
import { ApplicationListener, BaseApplicationListenerProps } from './application-listener';
Expand Down Expand Up @@ -78,34 +76,6 @@ export class ApplicationLoadBalancer extends BaseLoadBalancer implements IApplic
if (props.idleTimeout !== undefined) { this.setAttribute('idle_timeout.timeout_seconds', props.idleTimeout.toSeconds().toString()); }
}

/**
* Enable access logging for this load balancer.
*
* A region must be specified on the stack containing the load balancer; you cannot enable logging on
* environment-agnostic stacks. See https://docs.aws.amazon.com/cdk/latest/guide/environments.html
*/
public logAccessLogs(bucket: s3.IBucket, prefix?: string) {
this.setAttribute('access_logs.s3.enabled', 'true');
this.setAttribute('access_logs.s3.bucket', bucket.bucketName.toString());
this.setAttribute('access_logs.s3.prefix', prefix);

const region = Stack.of(this).region;
if (Token.isUnresolved(region)) {
throw new Error(`Region is required to enable ELBv2 access logging`);
}

const account = ELBV2_ACCOUNTS[region];
if (!account) {
throw new Error(`Cannot enable access logging; don't know ELBv2 account for region ${region}`);
}

prefix = prefix || '';
bucket.grantPut(new iam.AccountPrincipal(account), `${(prefix ? prefix + "/" : "")}AWSLogs/${Stack.of(this).account}/*`);

// make sure the bucket's policy is created before the ALB (see https://github.com/aws/aws-cdk/issues/1633)
this.node.addDependency(bucket);
}

/**
* Add a new listener to this load balancer
*/
Expand Down Expand Up @@ -530,33 +500,6 @@ export interface ApplicationLoadBalancerAttributes {
readonly securityGroupAllowsAllOutbound?: boolean;
}

// https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-logging-bucket-permissions
const ELBV2_ACCOUNTS: { [region: string]: string } = {
'us-east-1': '127311923021',
'us-east-2': '033677994240',
'us-west-1': '027434742980',
'us-west-2': '797873946194',
'ca-central-1': '985666609251',
'eu-central-1': '054676820928',
'eu-west-1': '156460612806',
'eu-west-2': '652711504416',
'eu-west-3': '009996457667',
'eu-north-1': '897822967062',
'ap-east-1': '754344448648',
'ap-northeast-1': '582318560864',
'ap-northeast-2': '600734575887',
'ap-northeast-3': '383597477331',
'ap-southeast-1': '114774131450',
'ap-southeast-2': '783225319266',
'ap-south-1': '718504428378',
'me-south-1': '076674570225',
'sa-east-1': '507241528517',
'us-gov-west-1': '048591011584',
'us-gov-east-1': '190560391635',
'cn-north-1': '638102146993',
'cn-northwest-1': '037604701340',
};

/**
* An ApplicationLoadBalancer that has been defined elsewhere
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import * as ec2 from '@aws-cdk/aws-ec2';
import { Construct, IResource, Lazy, Resource } from '@aws-cdk/core';
import * as iam from '@aws-cdk/aws-iam';
import * as s3 from '@aws-cdk/aws-s3';
import { Construct, IResource, Lazy, Resource, Stack, Token } from '@aws-cdk/core';
import { CfnLoadBalancer } from '../elasticloadbalancingv2.generated';
import { Attributes, ifUndefined, renderAttributes } from './util';

Expand Down Expand Up @@ -156,6 +158,34 @@ export abstract class BaseLoadBalancer extends Resource {
this.loadBalancerSecurityGroups = resource.attrSecurityGroups;
}

/**
* Enable access logging for this load balancer.
*
* A region must be specified on the stack containing the load balancer; you cannot enable logging on
* environment-agnostic stacks. See https://docs.aws.amazon.com/cdk/latest/guide/environments.html
*/
public logAccessLogs(bucket: s3.IBucket, prefix?: string) {
this.setAttribute('access_logs.s3.enabled', 'true');
this.setAttribute('access_logs.s3.bucket', bucket.bucketName.toString());
this.setAttribute('access_logs.s3.prefix', prefix);

const region = Stack.of(this).region;
if (Token.isUnresolved(region)) {
throw new Error(`Region is required to enable ELBv2 access logging`);
}

const account = ELBV2_ACCOUNTS[region];
if (!account) {
throw new Error(`Cannot enable access logging; don't know ELBv2 account for region ${region}`);
}

prefix = prefix || '';
bucket.grantPut(new iam.AccountPrincipal(account), `${(prefix ? prefix + "/" : "")}AWSLogs/${Stack.of(this).account}/*`);

// make sure the bucket's policy is created before the ALB (see https://github.com/aws/aws-cdk/issues/1633)
this.node.addDependency(bucket);
}

/**
* Set a non-standard attribute on the load balancer
*
Expand All @@ -172,3 +202,30 @@ export abstract class BaseLoadBalancer extends Resource {
this.setAttribute(key, undefined);
}
}

// https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-logging-bucket-permissions
const ELBV2_ACCOUNTS: { [region: string]: string } = {
'us-east-1': '127311923021',
'us-east-2': '033677994240',
'us-west-1': '027434742980',
'us-west-2': '797873946194',
'ca-central-1': '985666609251',
'eu-central-1': '054676820928',
'eu-west-1': '156460612806',
'eu-west-2': '652711504416',
'eu-west-3': '009996457667',
'eu-north-1': '897822967062',
'ap-east-1': '754344448648',
'ap-northeast-1': '582318560864',
'ap-northeast-2': '600734575887',
'ap-northeast-3': '383597477331',
'ap-southeast-1': '114774131450',
'ap-southeast-2': '783225319266',
'ap-south-1': '718504428378',
'me-south-1': '076674570225',
'sa-east-1': '507241528517',
'us-gov-west-1': '048591011584',
'us-gov-east-1': '190560391635',
'cn-north-1': '638102146993',
'cn-northwest-1': '037604701340',
};
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect, haveResource } from '@aws-cdk/assert';
import { expect, haveResource, ResourcePart } from '@aws-cdk/assert';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as s3 from '@aws-cdk/aws-s3';
import * as cdk from '@aws-cdk/core';
import { Test } from 'nodeunit';
import * as elbv2 from '../../lib';
Expand Down Expand Up @@ -74,6 +75,108 @@ export = {
test.done();
},

'Access logging'(test: Test) {
// GIVEN
const stack = new cdk.Stack(undefined, undefined, { env: { region: 'us-east-1' } });
const vpc = new ec2.Vpc(stack, 'Stack');
const bucket = new s3.Bucket(stack, 'AccessLoggingBucket');
const lb = new elbv2.NetworkLoadBalancer(stack, 'LB', { vpc });

// WHEN
lb.logAccessLogs(bucket);

// THEN

// verify that the LB attributes reference the bucket
expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::LoadBalancer', {
LoadBalancerAttributes: [
{
Key: "access_logs.s3.enabled",
Value: "true"
},
{
Key: "access_logs.s3.bucket",
Value: { Ref: "AccessLoggingBucketA6D88F29" }
}
],
}));

// verify the bucket policy allows the ALB to put objects in the bucket
expect(stack).to(haveResource('AWS::S3::BucketPolicy', {
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: ["s3:PutObject*", "s3:Abort*"],
Effect: 'Allow',
Principal: { AWS: { "Fn::Join": ["", ["arn:", { Ref: "AWS::Partition" }, ":iam::127311923021:root"]] } },
Resource: {
"Fn::Join": ["", [{ "Fn::GetAtt": ["AccessLoggingBucketA6D88F29", "Arn"] }, "/AWSLogs/",
{ Ref: "AWS::AccountId" }, "/*"]]
}
}
]
}
}));

// verify the ALB depends on the bucket *and* the bucket policy
expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::LoadBalancer', {
DependsOn: ['AccessLoggingBucketPolicy700D7CC6', 'AccessLoggingBucketA6D88F29']
}, ResourcePart.CompleteDefinition));

test.done();
},

'access logging with prefix'(test: Test) {
// GIVEN
const stack = new cdk.Stack(undefined, undefined, { env: { region: 'us-east-1' } });
const vpc = new ec2.Vpc(stack, 'Stack');
const bucket = new s3.Bucket(stack, 'AccessLoggingBucket');
const lb = new elbv2.NetworkLoadBalancer(stack, 'LB', { vpc });

// WHEN
lb.logAccessLogs(bucket, 'prefix-of-access-logs');

// THEN
// verify that the LB attributes reference the bucket
expect(stack).to(haveResource('AWS::ElasticLoadBalancingV2::LoadBalancer', {
LoadBalancerAttributes: [
{
Key: "access_logs.s3.enabled",
Value: "true"
},
{
Key: "access_logs.s3.bucket",
Value: { Ref: "AccessLoggingBucketA6D88F29" }
},
{
Key: "access_logs.s3.prefix",
Value: "prefix-of-access-logs"
}
],
}));

// verify the bucket policy allows the ALB to put objects in the bucket
expect(stack).to(haveResource('AWS::S3::BucketPolicy', {
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: ["s3:PutObject*", "s3:Abort*"],
Effect: 'Allow',
Principal: { AWS: { "Fn::Join": ["", ["arn:", { Ref: "AWS::Partition" }, ":iam::127311923021:root"]] } },
Resource: {
"Fn::Join": ["", [{ "Fn::GetAtt": ["AccessLoggingBucketA6D88F29", "Arn"] }, "/prefix-of-access-logs/AWSLogs/",
{ Ref: "AWS::AccountId" }, "/*"]]
}
}
]
}
}));

test.done();
},

'loadBalancerName'(test: Test) {
// GIVEN
const stack = new cdk.Stack();
Expand Down

0 comments on commit adbc3b9

Please sign in to comment.