Skip to content

Conversation

DaltJM
Copy link

@DaltJM DaltJM commented Jun 29, 2025

Issue #34784

Closes #34784 .

Reason for this change

When using aws_ec2.IpAddresses.cidr() in the AWS CDK to define a VPC or subnet CIDR block, if the provided base IP address is not properly aligned for the specified prefix length, the CDK silently "rounds up" the address to the next valid CIDR block without issuing a warning or error. This can result in unexpected address space being allocated, which may go unnoticed during deployment and lead to future routing or peering issues.

Description of changes

Removed hidden rounding from the CidrBlock constructor. Now, both string and numeric branches strictly validate alignment and throw on misaligned input. An explicit pre‐alignment step was also added in NetworkBuilder.addSubnets (and the EC2 allocator) before calling new CidrBlock(base, mask). These changes address the issue by ensuring that any user-provided CIDR fails fast with a clear alignment error while preserving the original auto-allocation behaviour through explicit builder-side rounding. EnforceAlignment flag to the constructor (too leaky and confusing), mixed rounding logic in the constructor (inconsistent API), keeping global silent rounding (reintroduces the original bug), and exporting a separate helper function (only relocates logic without simplifying carve sites) were all considered and rejected. Key design decisions include centralising validation in the constructor, moving rounding into the builder for separation of concerns, avoiding public-API bloat by not introducing new flags or overloads, and preserving the existing test suite unchanged.

Describe any new or updated permissions being added

N/A

Description of how you validated changes

The CidrBlock constructor in network-utils.ts validates alignment only for CIDRs within the VPC-allowed range of /16 to /28, enabling broader blocks such as /12 to be used in contexts like EKS without triggering alignment errors. This ensures strict alignment enforcement for VPC and subnet definitions while supporting more flexible usage elsewhere. In network-utils.test.ts, the import for UnscopedValidationError was updated to reference the core module. A misaligned numeric offset test was added to verify error handling, and the maxIp() test was adjusted to reflect correct behaviour for aligned blocks. A new block of tests, CidrBlock alignment validation, was introduced to confirm that both string- and numeric-form CIDRs behave correctly with respect to alignment rules.

All tests were verified as completing successfully after implementing these changes. A local package was created and imported into a new TS CDK project. A VPC was created like so:

const vpc = new ec2.Vpc(this, "VPC", {
      ipAddresses: ec2.IpAddresses.cidr(props.cidr),
      maxAzs: 3,
      subnetConfiguration: [
        {
          name: "Public",
          subnetType: ec2.SubnetType.PUBLIC,
        },
        {
          name: 'Private',                   
          subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
          cidrMask: 24,
        },
      ],
    });

props.cidr was given the value of 10.0.32.0/19 and a cdk synth was performed. This resulted in a successfully synthed stack with a VPC with a CIDR value of 10.0.32.0/19. Additionally, several subnets were automatically created with CIDR of 10.0.40.0/21, 10.0.48.0/21, 10.0.32.0/24 and 10.0.33.0/24.

When props.cidr was given a value of 10.0.40.0/19 and cdk synth was performed, the following error was returned in the CLI.

/workspace/cdk-ipaddress-test/node_modules/aws-cdk-lib/aws-ec2/lib/network-util.js:189
                throw new (core_1().UnscopedValidationError)(`The base address ${NetworkUtils.numToIp(ipNum)}/${prefix} ` +
                      ^
UnscopedValidationError: The base address 10.0.40.0/19 is not aligned on a 8192-address boundary
    at path [undefined]

    at new CidrBlock (/workspace/cdk-ipaddress-test/node_modules/aws-cdk-lib/aws-ec2/lib/network-util.js:189:23)
    at new NetworkBuilder (/workspace/cdk-ipaddress-test/node_modules/aws-cdk-lib/aws-ec2/lib/network-util.js:103:28)
    at new Cidr (/workspace/cdk-ipaddress-test/node_modules/aws-cdk-lib/aws-ec2/lib/ip-addresses.js:166:31)
    at Function.cidr (/workspace/cdk-ipaddress-test/node_modules/aws-cdk-lib/aws-ec2/lib/ip-addresses.js:27:16)
    at new CdkIpaddressTestStack (/workspace/cdk-ipaddress-test/lib/cdk-ipaddress-test-stack.ts:14:36)
    at Object.<anonymous> (/workspace/cdk-ipaddress-test/bin/cdk-ipaddress-test.ts:6:1)
    at Module._compile (node:internal/modules/cjs/loader:1529:14)
    at Module.m._compile (/workspace/cdk-ipaddress-test/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1613:10)
    at Object.require.extensions.<computed> [as .ts] (/workspace/cdk-ipaddress-test/node_modules/ts-node/src/index.ts:1621:12)
npx ts-node --prefer-ts-exts bin/cdk-ipaddress-test.ts: Subprocess exited with error 1

Checklist


By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license

@github-actions github-actions bot added the beginning-contributor [Pilot] contributed between 0-2 PRs to the CDK label Jun 29, 2025
@aws-cdk-automation aws-cdk-automation requested a review from a team June 29, 2025 07:20
@github-actions github-actions bot added bug This issue is a bug. effort/medium Medium work item – several days of effort p2 labels Jun 29, 2025
Copy link
Collaborator

@aws-cdk-automation aws-cdk-automation left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pull request linter fails with the following errors:

❌ Fixes must contain a change to an integration test file and the resulting snapshot.

If you believe this pull request should receive an exemption, please comment and provide a justification. A comment requesting an exemption should contain the text Exemption Request. Additionally, if clarification is needed, add Clarification Request to a comment.

✅ A exemption request has been requested. Please wait for a maintainer's review.

@DaltJM DaltJM changed the title feat(ec2): strict alignment for CidrBlock (no silent rounding) fix(ec2): strict alignment for CidrBlock (no silent rounding) Jun 29, 2025
@DaltJM DaltJM marked this pull request as draft June 29, 2025 07:25
@DaltJM DaltJM marked this pull request as ready for review June 29, 2025 07:27
@aws-cdk-automation
Copy link
Collaborator

AWS CodeBuild CI Report

  • CodeBuild project: AutoBuildv2Project1C6BFA3F-wQm2hXv2jqQv
  • Commit ID: 7b462fa
  • Result: SUCCEEDED
  • Build Logs (available for 30 days)

Powered by github-codebuild-logs, available on the AWS Serverless Application Repository

@DaltJM
Copy link
Author

DaltJM commented Jul 5, 2025

@aws-cdk-automation Exemption Request - Requested changes have been committed.

@aws-cdk-automation aws-cdk-automation added pr-linter/exemption-requested The contributor has requested an exemption to the PR Linter feedback. pr/needs-community-review This PR needs a review from a Trusted Community Member or Core Team Member. labels Jul 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
beginning-contributor [Pilot] contributed between 0-2 PRs to the CDK bug This issue is a bug. effort/medium Medium work item – several days of effort p2 pr/needs-community-review This PR needs a review from a Trusted Community Member or Core Team Member. pr-linter/exemption-requested The contributor has requested an exemption to the PR Linter feedback.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Network-Utils: IpAddresses.cidr() silently adjusts misaligned base addresses to the next valid CIDR block
2 participants