Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
20
26
9 changes: 9 additions & 0 deletions dist/cloudflare-ips.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Cloudflare published edge ranges.
* https://www.cloudflare.com/ips-v4
* https://www.cloudflare.com/ips-v6
* Retrieved 2026-10-28.
*/
export declare const CLOUDFLARE_IPV4_CIDRS: string[];
export declare const CLOUDFLARE_IPV6_CIDRS: string[];
export declare const CLOUDFLARE_CIDRS: string[];
39 changes: 39 additions & 0 deletions dist/cloudflare-ips.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CLOUDFLARE_CIDRS = exports.CLOUDFLARE_IPV6_CIDRS = exports.CLOUDFLARE_IPV4_CIDRS = void 0;
/**
* Cloudflare published edge ranges.
* https://www.cloudflare.com/ips-v4
* https://www.cloudflare.com/ips-v6
* Retrieved 2026-10-28.
*/
exports.CLOUDFLARE_IPV4_CIDRS = [
'173.245.48.0/20',
'103.21.244.0/22',
'103.22.200.0/22',
'103.31.4.0/22',
'141.101.64.0/18',
'108.162.192.0/18',
'190.93.240.0/20',
'188.114.96.0/20',
'197.234.240.0/22',
'198.41.128.0/17',
'162.158.0.0/15',
'104.16.0.0/13',
'104.24.0.0/14',
'172.64.0.0/13',
'131.0.72.0/22',
];
exports.CLOUDFLARE_IPV6_CIDRS = [
'2400:cb00::/32',
'2606:4700::/32',
'2803:f800::/32',
'2405:b500::/32',
'2405:8100::/32',
'2a06:98c0::/29',
'2c0f:f248::/32',
];
exports.CLOUDFLARE_CIDRS = [
...exports.CLOUDFLARE_IPV4_CIDRS,
...exports.CLOUDFLARE_IPV6_CIDRS,
];
14 changes: 13 additions & 1 deletion dist/fargate.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
import * as route53 from 'aws-cdk-lib/aws-route53';
import { StackConfig } from './configuration';
import { LOAD_BALANCER_INGRESS, type LoadBalancerIngress } from './load-balancer-ingress';
export { LOAD_BALANCER_INGRESS, type LoadBalancerIngress };
/**
* Represents a definition for a task that can be used to generate a task definition
*/
Expand Down Expand Up @@ -39,6 +41,17 @@ interface FargateServiceProps extends cdk.NestedStackProps {
taskConfiguration: TaskConfiguration;
image?: ecs.ContainerImage;
securityGroup?: ec2.ISecurityGroup;
/**
* Who can connect to the load balancer on ports 80 and 443.
* @default LOAD_BALANCER_INGRESS.Open
*/
loadBalancerIngress?: LoadBalancerIngress;
/**
* CIDRs allowed to reach the load balancer. Required when
* `loadBalancerIngress` is `LOAD_BALANCER_INGRESS.Cidr`. Bare IPv4
* addresses are treated as /32 and bare IPv6 addresses as /128.
*/
loadBalancerCidrs?: string[];
}
/**
* Generate a fargate service that can be attached to a cluster. This service will include its own
Expand All @@ -53,4 +66,3 @@ export declare class FargateService extends cdk.NestedStack {
readonly service: ecs_patterns.ApplicationLoadBalancedFargateService;
constructor(scope: Construct, id: string, props: FargateServiceProps);
}
export {};
14 changes: 12 additions & 2 deletions dist/fargate.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FargateService = void 0;
exports.FargateService = exports.LOAD_BALANCER_INGRESS = void 0;
const cdk = __importStar(require("aws-cdk-lib"));
const ecs = __importStar(require("aws-cdk-lib/aws-ecs"));
const ecs_patterns = __importStar(require("aws-cdk-lib/aws-ecs-patterns"));
Expand All @@ -42,6 +42,8 @@ const ec2 = __importStar(require("aws-cdk-lib/aws-ec2"));
const iam = __importStar(require("aws-cdk-lib/aws-iam"));
const route53 = __importStar(require("aws-cdk-lib/aws-route53"));
const targets = __importStar(require("aws-cdk-lib/aws-route53-targets"));
const load_balancer_ingress_1 = require("./load-balancer-ingress");
Object.defineProperty(exports, "LOAD_BALANCER_INGRESS", { enumerable: true, get: function () { return load_balancer_ingress_1.LOAD_BALANCER_INGRESS; } });
const route53_1 = require("./route53");
const security_group_1 = require("./security-group");
// Default docker image to use
Expand All @@ -58,7 +60,8 @@ const DEFAULT_IMAGE = 'nginxdemos/hello:latest';
class FargateService extends cdk.NestedStack {
constructor(scope, id, props) {
super(scope, id, props);
const { healthCheckPath = '/health-check', containerPort = 80, imageVersion = 'latest', subDomainIncludingDot = '', stack, cluster, certificate, zone, repository, taskConfiguration, securityGroup: defaultSecurityGroup, } = props;
const { healthCheckPath = '/health-check', containerPort = 80, imageVersion = 'latest', subDomainIncludingDot = '', stack, cluster, certificate, zone, repository, taskConfiguration, securityGroup: defaultSecurityGroup, loadBalancerIngress = load_balancer_ingress_1.LOAD_BALANCER_INGRESS.Open, loadBalancerCidrs, } = props;
const allowedCidrs = (0, load_balancer_ingress_1.resolveLoadBalancerCidrs)(loadBalancerIngress, loadBalancerCidrs);
// Compile secrets into list of mapped ecs.Secrets
const secrets = {};
const secretValues = taskConfiguration.secrets;
Expand Down Expand Up @@ -104,7 +107,14 @@ class FargateService extends cdk.NestedStack {
onePerAz: true,
},
securityGroups: [securityGroup],
// Closed listeners get explicit CIDR rules below. Leave this unset for
// the default so the pattern keeps opening 80 and 443 to the internet.
openListener: allowedCidrs ? false : undefined,
});
if (allowedCidrs) {
// This service always terminates HTTPS and redirects HTTP.
(0, load_balancer_ingress_1.restrictLoadBalancerIngress)(this, this.service.loadBalancer, cluster.vpc, allowedCidrs, [80, 443]);
}
// Setup AutoScaling policy
if (taskConfiguration.autoScalingCpuTarget) {
// Default max capacity to double desired unless specified
Expand Down
1 change: 1 addition & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './acm';
export * from './build-pipeline';
export * from './cloudflare-ips';
export * from './configuration';
export * from './ecr-repository';
export * from './fargate';
Expand Down
1 change: 1 addition & 0 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./acm"), exports);
__exportStar(require("./build-pipeline"), exports);
__exportStar(require("./cloudflare-ips"), exports);
__exportStar(require("./configuration"), exports);
__exportStar(require("./ecr-repository"), exports);
__exportStar(require("./fargate"), exports);
Expand Down
25 changes: 25 additions & 0 deletions dist/load-balancer-ingress.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Construct } from 'constructs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as elb from 'aws-cdk-lib/aws-elasticloadbalancingv2';
/**
* Who may connect to the load balancer listeners (HTTP 80 and HTTPS 443).
*
* - `Open`: no IP restriction. This is the default and matches previous behaviour.
* - `Cloudflare`: only Cloudflare's published IPv4 and IPv6 ranges.
* - `Cidr`: only the ranges passed in `loadBalancerCidrs`.
*/
export declare const LOAD_BALANCER_INGRESS: {
readonly Open: "open";
readonly Cloudflare: "cloudflare";
readonly Cidr: "cidr";
};
export type LoadBalancerIngress = (typeof LOAD_BALANCER_INGRESS)[keyof typeof LOAD_BALANCER_INGRESS];
export declare function resolveLoadBalancerCidrs(ingress: LoadBalancerIngress, cidrs: string[] | undefined): string[] | undefined;
/**
* Allow `cidrs` to reach the load balancer on `ports`, and nothing else.
* The listeners must be created with `openListener: false` so the default
* 0.0.0.0/0 rule is not added.
*
* Rules are split across extra security groups when one group cannot hold them.
*/
export declare function restrictLoadBalancerIngress(scope: Construct, loadBalancer: elb.ApplicationLoadBalancer, vpc: ec2.IVpc, cidrs: string[], ports: number[]): void;
140 changes: 140 additions & 0 deletions dist/load-balancer-ingress.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.LOAD_BALANCER_INGRESS = void 0;
exports.resolveLoadBalancerCidrs = resolveLoadBalancerCidrs;
exports.restrictLoadBalancerIngress = restrictLoadBalancerIngress;
const net_1 = require("net");
const ec2 = __importStar(require("aws-cdk-lib/aws-ec2"));
const cloudflare_ips_1 = require("./cloudflare-ips");
/**
* Who may connect to the load balancer listeners (HTTP 80 and HTTPS 443).
*
* - `Open`: no IP restriction. This is the default and matches previous behaviour.
* - `Cloudflare`: only Cloudflare's published IPv4 and IPv6 ranges.
* - `Cidr`: only the ranges passed in `loadBalancerCidrs`.
*/
exports.LOAD_BALANCER_INGRESS = {
Open: 'open',
Cloudflare: 'cloudflare',
Cidr: 'cidr',
};
/** Default inbound rules per security group. */
const RULES_PER_SECURITY_GROUP = 60;
/** Application load balancers accept at most five security groups. */
const MAX_LOAD_BALANCER_SECURITY_GROUPS = 5;
function resolveLoadBalancerCidrs(ingress, cidrs) {
if (ingress === exports.LOAD_BALANCER_INGRESS.Open) {
if (cidrs !== undefined) {
throw new Error(`loadBalancerCidrs is only used when loadBalancerIngress is "${exports.LOAD_BALANCER_INGRESS.Cidr}"`);
}
return undefined;
}
if (ingress === exports.LOAD_BALANCER_INGRESS.Cloudflare) {
if (cidrs !== undefined) {
throw new Error(`loadBalancerCidrs cannot be combined with loadBalancerIngress "${exports.LOAD_BALANCER_INGRESS.Cloudflare}"`);
}
return cloudflare_ips_1.CLOUDFLARE_CIDRS;
}
if (!cidrs || cidrs.length === 0) {
throw new Error(`loadBalancerCidrs must contain at least one CIDR when loadBalancerIngress is "${exports.LOAD_BALANCER_INGRESS.Cidr}"`);
}
const normalized = cidrs.map(normalizeCidr);
return [...new Set(normalized)];
}
/**
* Allow `cidrs` to reach the load balancer on `ports`, and nothing else.
* The listeners must be created with `openListener: false` so the default
* 0.0.0.0/0 rule is not added.
*
* Rules are split across extra security groups when one group cannot hold them.
*/
function restrictLoadBalancerIngress(scope, loadBalancer, vpc, cidrs, ports) {
const rules = cidrs.flatMap((cidr) => ports.map((port) => ({
cidr,
peer: cidr.includes(':') ? ec2.Peer.ipv6(cidr) : ec2.Peer.ipv4(cidr),
port: ec2.Port.tcp(port),
})));
const groupsNeeded = Math.ceil(rules.length / RULES_PER_SECURITY_GROUP);
if (groupsNeeded > MAX_LOAD_BALANCER_SECURITY_GROUPS) {
throw new Error(`Load balancer ingress needs ${groupsNeeded} security groups for ${rules.length} rules, but an application load balancer accepts at most ${MAX_LOAD_BALANCER_SECURITY_GROUPS}`);
}
const [primary] = loadBalancer.connections.securityGroups;
if (!primary) {
throw new Error('Load balancer has no security group to restrict');
}
const groups = [primary];
for (let index = 1; index < groupsNeeded; index++) {
const extra = new ec2.SecurityGroup(scope, `LoadBalancerIngress${index}`, {
vpc,
description: 'Additional load balancer listener ingress',
allowAllOutbound: true,
});
loadBalancer.addSecurityGroup(extra);
groups.push(extra);
}
rules.forEach((rule, index) => {
const group = groups[Math.floor(index / RULES_PER_SECURITY_GROUP)];
group.addIngressRule(rule.peer, rule.port, `Allow TCP ${rule.port} from ${rule.cidr}`);
});
}
function normalizeCidr(input) {
const cidr = input.trim();
if (cidr.includes(':')) {
const withPrefix = cidr.includes('/') ? cidr : `${cidr}/128`;
if (!isCidr(withPrefix, 6, 128)) {
throw new Error(`Invalid IPv6 CIDR: ${input}`);
}
return withPrefix.toLowerCase();
}
const withPrefix = cidr.includes('/') ? cidr : `${cidr}/32`;
if (!isCidr(withPrefix, 4, 32)) {
throw new Error(`Invalid IPv4 CIDR: ${input}`);
}
return withPrefix;
}
function isCidr(cidr, version, maxPrefix) {
const slash = cidr.lastIndexOf('/');
if (slash <= 0) {
return false;
}
const address = cidr.slice(0, slash);
const prefixText = cidr.slice(slash + 1);
if (!/^\d{1,3}$/.test(prefixText)) {
return false;
}
const prefix = Number(prefixText);
return (0, net_1.isIP)(address) === version && prefix <= maxPrefix;
}
Loading
Loading