iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🗣️

[CDK] Checking Host Headers with ALB Listener Rules

に公開

Introduction

This post is a bit of a tip.
We'll assume a configuration where requests are allowed only when the host header matches a specific value, and return a 403 response otherwise.

This is achieved by modifying listener rules in an AWS Elastic Load Balancer (specifically, an Application Load Balancer).
I have reproduced that configuration using CDK.
Let's take a look at the code right away.

CDK

I have declared variables like alb, certificate, and targetGroup, but I'll omit the details as they are secondary to the main topic.
The point is to create a setup where the "default rule returns 403," and then overlay a rule that allows requests to the intended target if specific conditions (in this case, if the host header is hoge.example.com) are met.
You can change the priority of the rules as you like, and the default rule is applied when none of the other rules are satisfied.

Rules are evaluated in priority order, from the lowest value to the highest value. The default rule is evaluated last. You can change the priority of a non-default rule at any time. You cannot change the priority of the default rule.

https://docs.aws.amazon.com/ja_jp/elasticloadbalancing/latest/application/listener-update-rules.html

import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';

// alb is previously declared
// certificate is obtained from ACM

// Add HTTPS listener rule
const httpsListener = alb.addListener('SampleHttpsListener', {
  port: 443,
  protocol: elbv2.ApplicationProtocol.HTTPS,
  // Return 403 by default
  defaultAction: elbv2.ListenerAction.fixedResponse(403, {
    contentType: "text/plain",
    messageBody: '403 Forbidden'
  }),
  certificates: [certificate],
});

// Set additional rules
httpsListener.addTargetGroups("SampleTargetGroup", {
  // Priority
  priority: 100,
  // Target group (same can be achieved with addTarget)
  targetGroups: [targetGroup],
  // Condition settings
  conditions: [
    // Apply if the host header is a specific value
    // Other filters like SourceIp are also possible
    elbv2.ListenerCondition.hostHeaders([
      "hoge.example.com"
    ])
  ]
});

References

https://docs.aws.amazon.com/ja_jp/elasticloadbalancing/latest/application/listener-update-rules.html

https://dev.classmethod.jp/articles/alb-condition-values-per-rule/

Discussion