Scan standalone CDK constructs for misconfiguration

Vulnerability scanners like checkov have become a de facto standard for scanning IaC for possible misconfigurations. They can scan terraform configs, AWS CloudFormation templates, even – in a sense – CDK stacks, because they synthesize into CloudFormation templates that can be scanned.

In order to produce synthesized templates from stacks you have to have a full-blown CDK application. But what if you’re developing a standalone CDK construct as a library, to be used as a dependency in a CDK app? There is a way to scan it for vulnerabilities as well.

aws-cdk-lib/assertions module’s intended use is to write unit tests for CDK applications, and one of its features we can use is programmatically generate a CloudFormation template from a stack via Template.fromStack() method.

Take a look at the following code

import { MyCoolConstruct } from '../src/index';
import { Stack } from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import * as fs from 'fs';
let stack = new Stack();
new MyCoolConstruct(stack, 'MyCoolConstruct');
let template = JSON.stringify(Template.fromStack(stack));
fs.writeFileSync('my-cool-construct.json', template);

Lines 01-04 import your construct code
Lines 06-07 create an empty stack and instantiate yout construct in it
Lines 09-10 create a CloudFormation template and save it as a file.

Now you can run this code to generate the template, and scan the resulting template with checkov

npx ts-node -- get-templates.ts
checkov -f my-cool-construct.json

Leave a Reply

Your email address will not be published. Required fields are marked *