All jobs

Add AWS WAF to an API Gateway REST API in AWS CDK

Yes. An agent adds a WAFv2 Web ACL with AWS managed rule groups and a rate limit to your CDK stack, associates it with the API stage, tests the template, in a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the stack and how it is built. In a stack like api-cors-lambda-crud-dynamodb in aws-samples/aws-cdk-examples, index.ts defines ApiLambdaCrudDynamoDBStack: a DynamoDB Table keyed on itemId with RemovalPolicy.DESTROY, five NodejsFunctions on Runtime.NODEJS_24_X bundled with @aws-sdk/* left external, and a RestApi named Items Service with /items and /items/{id} resources, each with Lambda integrations and an OPTIONS MockIntegration from addCorsOptions that answers with Access-Control-Allow-Origin: *. cdk.json runs the app with npx tsc && npx tsx index.ts, package.json pins aws-cdk-lib 2.262.1 and aws-cdk 2.1133.0, and jest.config.js is set up with @swc/jest and aws-cdk-lib/testhelpers/jest-autoclean although no test file exists in this example yet. The sibling api-gateway-lambda-token-authorizer example shows the repository's test style: Template.fromStack with a snapshot.

Because the API is a RestApi, which deploys a stage, WAF can be attached to it; an HTTP API from aws-apigatewayv2 could not, and the agent says so rather than silently skipping. It adds a CfnWebACL from aws-cdk-lib/aws-wafv2 with scope: 'REGIONAL', a default action of allow, and four rules in priority order: the AWS managed AWSManagedRulesAmazonIpReputationList, AWSManagedRulesCommonRuleSet and AWSManagedRulesKnownBadInputsRuleSet groups with overrideAction: { none: {} }, and a rate-based rule aggregated by source IP whose five-minute limit is a stack property with a default the pull request states. Every rule and the ACL itself carry a visibilityConfig with CloudWatch metrics and sampled requests on, so blocked requests can be seen.

A CfnWebACLAssociation ties the ACL to the API with resourceArn: api.deploymentStage.stageArn and webAclArn: webAcl.attrArn. CDK already orders the stage before the association because the ARN references it. The agent exposes the ACL ARN as a CfnOutput and keeps the CORS mock methods as they are, noting that OPTIONS preflights now pass through the same rules.

The checks are the repository's own commands plus one new test. npm install runs the postinstall that installs lambdas/ dependencies, npm run build type-checks with tsc, and npx cdk synth produces the template, which needs no AWS account because the stack sets no environment. A new test/stack.test.ts uses Template.fromStack to assert one AWS::WAFv2::WebACL with Scope: REGIONAL and the four rule names, and one AWS::WAFv2::WebACLAssociation whose ResourceArn joins the API id and stage, then npx jest runs it with the existing config.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add AWS WAF to the API Gateway REST API in this CDK stack. Read index.ts, cdk.json, package.json, jest.config.js and the lambdas directory first, and confirm the API is a RestApi with a deployment stage. Add a CfnWebACL from aws-cdk-lib/aws-wafv2 with REGIONAL scope, a default allow action, the AWS managed AmazonIpReputationList, CommonRuleSet and KnownBadInputsRuleSet rule groups, and a rate-based rule per source IP whose limit is a stack property with a stated default, each with visibilityConfig metrics and sampled requests enabled. Associate it with the API stage through CfnWebACLAssociation using the stage ARN, output the ACL ARN, and leave the CORS mock methods unchanged. Add a test that uses Template.fromStack to assert the Web ACL, its rules and the association. Run npm install, npm run build, npx cdk synth and npx jest, and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

What comes back is a pull request on its own branch with the Web ACL, the association and the output added to index.ts, a new test/stack.test.ts, and nothing else changed. The Lambda functions, the table and the CORS handling keep their definitions.

The description quotes the AWS::WAFv2::WebACL and AWS::WAFv2::WebACLAssociation resources from the synthesized template and the jest result, and states the rate limit default it chose. The build, synth and test commands with their output are in the transcript at GET /o/{org}/sessions/{id}/messages.

Before merging, a reviewer decides the rate limit for their traffic, considers whether any managed rule should start in count mode to watch for false positives, and runs cdk diff against the account to see the two new resources. A follow-up message to the same session can add a logging configuration to a CloudWatch log group or an IP allow list.

Run it on every Linear issue labelled security

A team that files hardening work in Linear starts one run per issue from an automation with a linear trigger on the security label. The automation adds the issue after this prompt, so an issue that names the rate limit, an IP set to allow or a rule to run in count mode is what the agent reads, and the run starts in the repository the automation names.

Each run opens its own pull request from its own sandbox, and an automation run has its own max_runs_per_hour cap. The pull request links the issue and quotes the synthesized resources, so the review is a read of one template fragment and one test.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

WAF on API Gateway is a handful of constructs with precise requirements: the right scope, an association with a stage ARN rather than the API ARN, and a visibility config on every rule or the template is rejected at deploy time. The agent reads the stack to confirm the API type, writes the constructs, synthesizes the template in a sandbox with the pinned aws-cdk-lib, and asserts the result in a test the repository's Jest config already supports.

The pull request carries the synthesized resources and the test output, so a reviewer sees exactly what CloudFormation will create. Several stacks can be done at once, each in its own sandbox, with one pull request each.

Frequently asked questions

Does this work with an HTTP API?

No. WAFv2 regional Web ACLs associate with REST API stages, Application Load Balancers, AppSync APIs and a few other resource types, but not with API Gateway HTTP APIs. This stack uses RestApi, so it qualifies; on a stack that uses aws-apigatewayv2, the agent stops and says what the options are, such as putting CloudFront in front.

Will the managed rules block legitimate requests?

They can, which is why every rule has sampled requests and metrics enabled and why the pull request suggests switching a rule group's override to count mode for a period before enforcing it. The agent does not guess at exclusions; it makes them visible.

Where does the rate limit come from?

It is a constructor property on the stack with a default the agent states in the pull request, so the reviewer sets it from their own traffic rather than accepting a number pulled from a sample. WAF counts requests per source IP over a five-minute window.

Does the test need an AWS account?

No. Template.fromStack synthesizes the stack in memory, and the stack has no environment set, so cdk synth and the Jest test both run without credentials. Only cdk deploy, which the agent does not run, needs the account.

More AWS CDK jobs

More jobs like this: Turn a Linear label into a PR

Keep reading