aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
https://aws.amazon.com/cdk
Apache License 2.0
11.51k stars 3.85k forks source link

aws-cdk-lib/aws-ecs-patterns: ALB services, option to only forward requests with the expected host #25434

Open plumdog opened 1 year ago

plumdog commented 1 year ago

Describe the feature

Option to only forward requests where the host header matches the domainName set for the ApplicationLoadBalanced(Ec2/Fargate)Service.

Use Case

We noticed we were getting lots of requests hitting the workload with the wrong host header. This is because, even though we are setting the domain name (https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationLoadBalancedEc2Service.html#domainname), the ALB still forwards everything to the workload.

Proposed Solution

My suggestion is for an option like enforceHostHeader?: boolean that, if set, changes the rules on the ALB listener to be:

This differs from the default listener behaviour which is just:

I suppose there's a case to be made that enforceHostHeader: true should be the default behaviour when domainName is set, but this would be a breaking change.

Other Information

I have escape-hatched this as follows:

const myDomainName = 'mydomain.example.com';
const myService = new ecsPatterns.ApplicationLoadBalancedEc2Service(this, `MyService`, {
    // ...
    domainName: myDomainName,
    openListener: true,
    protocol: elbv2.ApplicationProtocol.HTTPS,
    redirectHTTP: true,
});

myService.listener.addAction('ForwardIfMatchingDomain', {
    priority: 10,
    conditions: [
        elbv2.ListenerCondition.hostHeaders([myDomainName]),
    ],
    action: elbv2.ListenerAction.forward([myService.targetGroup]),
});
const cfnListener = myService.listener.node.defaultChild as elbv2.CfnListener;
cfnListener.addPropertyOverride('DefaultActions', [{
    Type: 'fixed-response',
    FixedResponseConfig: {
        ContentType: 'text/plain',
        MessageBody: 'Bad Request',
        StatusCode: '400',
    },
}]);

Acknowledgements

CDK version used

2.54.0

Environment details (OS name and version, etc.)

n/a

peterwoodworth commented 1 year ago

Our L3 constructs will make some opinionated choices like this, this is something we could add but typically if you need fine-grained control then building patterns with your own L2 constructs is a better choice if the modifications you need to make aren't easily achievable with escape hatches

We can always reconsider however, we use +1s to help prioritize our work, and are happy to revaluate this issue based on community feedback. You can reach out to the cdk.dev community on Slack to solicit support for reprioritization.