Testing CDK: assertions, snapshots and cdk-nag
Prove infrastructure controls with xUnit tests over the synthesized template, add a coarse snapshot that catches surprise changes, and run cdk-nag v3 as a test with every finding fixed or acknowledged with a written reason.
Assumes: .NET 10 LTS · xUnit v3 4.0.3 (Microsoft.Testing.Platform) · Amazon.CDK.Lib 2.277.0 · Cdklabs.CdkNag 3.0.2 · Node.js 22 LTS. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain the testing pyramid for infrastructure code: pure C# tests, fine-grained assertions, snapshots, policy scans.
- Write xUnit v3 tests that synthesize a stack in memory and assert on resources with
Template,MatchandAnnotations. - Share one expensive synthesis across many tests, and make the suite skip locally but fail in CI when Node.js is missing.
- Add a coarse snapshot that shows unexpected changes in a pull request without breaking on every CDK upgrade.
- Run cdk-nag v3 as a plugin inside a test, read its findings, and acknowledge a finding with a reason using the v3 API.
- Prove that the checks themselves work (a positive control), so a silently empty report cannot give false comfort.
- Compare with Terraform's
terraform testand policy scanners.
Prerequisites
- CDK constructs: L1, L2 and L3: the
EvidenceBucketconstruct and theRequireEncryptedBucketsaspect are tested here. - CDK stacks, environments and configuration
- Tools: .NET 10 SDK, Node.js 22 or 24 LTS (or Docker, shown below). No AWS account is needed; synthesis is local.
Why this matters in banking
An infrastructure change is a production change. At Harbourline a security group rule, a KMS key policy or a retention setting needs the same evidence as application code: a test that fails when the rule is broken. Infrastructure tests give the second line of defence something concrete to sample: "Show me the test that proves production databases are encrypted. Show me the run where it passed for this release."
They also give developers fast feedback. Synthesizing and asserting takes seconds on a laptop; a failed deployment takes twenty minutes and leaves a rolled-back stack. The cheapest place to find that a bucket lost its TLS rule is before an account is involved.
Finally, tests are how a construct library earns trust. Application teams adopt EvidenceBucket only if a test suite guards its controls.
The idea in plain language
A CDK test does three things: build a stack in memory, synthesize it to a CloudFormation template, and assert that the template contains what you expect. Nothing touches AWS.
Analogy: a building inspector reads the drawings against the code book before the foundation is poured. A drawing-level test is cheap to run and cheap to fix; the same mistake found after the concrete sets is expensive.
There are four kinds of check, from cheapest to most thorough:
| Layer | Needs Node.js? | What it proves | Example |
|---|---|---|---|
| Pure C# tests | No | Settings and helpers behave | An invalid CIDR is rejected |
| Fine-grained assertions | Yes | A resource has specific properties | The bucket blocks public access |
| Snapshot | Yes | The shape of the template did not change by surprise | The stack still has 2 buckets and 5 alarms |
| Policy scan (cdk-nag) | Yes | The template meets a rule pack | No unacknowledged AWS Solutions findings |
What problem this solves
| Problem | Check that catches it |
|---|---|
Someone removes EnforceSSL from a shared construct | Assertion on the bucket policy |
| A refactor accidentally adds a NAT gateway (about $0.045 per hour each, plus data) | ResourceCountIs("AWS::EC2::NatGateway", 0) |
| A library upgrade quietly changes generated IAM | Coarse snapshot plus cdk diff in the pull request |
| An unencrypted raw bucket sneaks in | Aspect and cdk-nag |
| A suppression with no reason | Helper that refuses short reasons, reviewed in the diff |
Honest limits
- Tests check the template, not the running account. A test cannot see console edits (that is drift detection) or IAM permissions boundaries in the account (that is SCPs).
- Over-specified assertions are brittle. Asserting every property makes every harmless change a failing test. Assert the controls, not the implementation.
- Full-template snapshots rot. Asset hashes and logical IDs change on CDK upgrades; reviewers learn to approve blindly. Use coarse snapshots.
- cdk-nag packs are checklists, not guarantees. A pack named after a standard does not make you compliant with it.
- Synthesis is slow on first use (several seconds to start Node.js through jsii). Share synthesis between tests.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Pester tests over ARM or Bicep output | xUnit tests over the synthesized template | Same idea; here the "template" is produced by running your C# |
| ARM-TTK (template test toolkit) | cdk-nag, cfn-lint | Rule packs applied during synthesis |
| Azure Policy audit mode | cdk-nag acknowledgments with reasons | Findings fail the build unless acknowledged |
bicep build plus snapshot in Git | Coarse snapshot test | Count resources by type, not the whole file |
| What-if in a PR | cdk diff in a PR | Complements tests; humans read it |
Architecture
Security-boundary view. Tests run on a build agent with no cloud credentials at all. That is a feature: a unit test that needs credentials is an integration test. The agent runs untrusted pull-request code, so give it no secrets and no deploy role.
Step-by-step implementation
Add a test project
Create tests/Harbourline.Evidence.Cdk.Tests next to the app from the earlier lessons. It uses xUnit v3 on Microsoft.Testing.Platform, which is selected by a global.json at the repository root.
Write the synthesis helper
One class builds stacks, applies the same feature flags as cdk.json, and skips or fails when Node.js is missing.
Write fine-grained assertions
One test per control, named after the control.
Add cdk-nag as a test, with a positive control
The first run lists findings. Fix what you can; acknowledge the rest with a reason.
Run the suite three ways
Without Node.js (skipped), in CI mode without Node.js (fails), and with Node.js (passes).
AWS Console instructions
There is no console work: these tests never contact AWS. The console matters later, when a deployed stack's drift or a CloudFormation event contradicts a test; that is a signal your tests are checking the wrong thing.
AWS CLI
All commands are local. With the .NET SDK and Node.js installed:
dotnet test --project tests/Harbourline.Evidence.Cdk.Tests/Harbourline.Evidence.Cdk.Tests.csprojOn a machine with only Docker (the way the course CI runs the lab tests), install Node.js inside the container and use your own NuGet cache volume:
MSYS_NO_PATHCONV=1 docker run --rm --memory 3g \
-v "$PWD:/src" -v cea-nuget-m10:/root/.nuget/packages -w /src \
mcr.microsoft.com/dotnet/sdk:10.0 sh -c "\
curl -fsSL https://nodejs.org/dist/v22.12.0/node-v22.12.0-linux-x64.tar.gz | tar -xz -C /usr/local --strip-components=1 \
&& CI=true dotnet test --solution EnvironmentTwoTools.slnx"Pin Node.js to a supported LTS (22 or 24). Node.js 18 is end of life; the CDK's jsii runtime prints a warning on it, and older versions are not supported ⚠ VERIFY the supported Node.js versions for your CDK release.
Infrastructure as Code
The assertion API lives in Amazon.CDK.Assertions (part of Amazon.CDK.Lib). The calls you need:
| Call | Meaning |
|---|---|
Template.FromStack(stack) | Synthesize the stack and wrap its template |
template.ResourceCountIs(type, n) | Exactly n resources of a type |
template.HasResourceProperties(type, props) | At least one resource of that type has those properties |
template.HasResource(type, definition) | Same, for top-level attributes such as DeletionPolicy |
template.FindResources(type) | Return the matching resources for your own checks |
Match.ObjectLike, Match.ArrayWith, Match.AnyValue, Match.Absent, Match.StringLikeRegexp | Partial and flexible matching |
Annotations.FromStack(stack) | Read errors, warnings and info recorded by aspects and constructs |
A single assertion in full. The nested dictionaries mirror the JSON of the template:
template.HasResourceProperties("AWS::S3::Bucket", new Dictionary<string, object>
{
["VersioningConfiguration"] = new Dictionary<string, object> { ["Status"] = "Enabled" },
["PublicAccessBlockConfiguration"] = new Dictionary<string, object>
{
["BlockPublicAcls"] = true,
["BlockPublicPolicy"] = true,
["IgnorePublicAcls"] = true,
["RestrictPublicBuckets"] = true,
},
});HasResourceProperties matches partially by default: extra properties on the real resource are fine. Use Match.Absent() when you need to say "this property must not exist", for example that a task role has no Policies.
Complete code
The code below was built and run on .NET 10 with Amazon.CDK.Lib 2.277.0, Cdklabs.CdkNag 3.0.2 and Node.js 22: 10 tests passed. It tests the EvidenceBucket construct and the RequireEncryptedBuckets aspect from the previous lesson.
{
"sdk": {
"version": "10.0.100",
"rollForward": "latestFeature"
},
"test": {
"runner": "Microsoft.Testing.Platform"
}
}<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
<WarningsNotAsErrors>CS0618</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
<!-- Runs on Microsoft.Testing.Platform (opted in through global.json). -->
<PackageReference Include="xunit.v3" Version="4.0.3" />
<PackageReference Include="Cdklabs.CdkNag" Version="3.0.2" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<!-- jsii (the bridge to the CDK's Node.js runtime) is not designed for parallel calls. -->
<Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Harbourline.Evidence.Cdk\Harbourline.Evidence.Cdk.csproj" />
</ItemGroup>
</Project>{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"parallelizeTestCollections": false,
"parallelizeAssembly": false
}using System.Diagnostics;
using System.Text.Json;
using Amazon.CDK;
using Amazon.CDK.Assertions;
using Cdklabs.CdkNag;
using Harbourline.Evidence.Cdk.Constructs;
namespace Harbourline.Evidence.Cdk.Tests;
/// <summary>
/// Builds small stacks in memory for the tests. Nothing here talks to AWS: synthesis is local.
/// CDK for .NET runs its construct library in Node.js, so Node.js must be on PATH. Without it the tests
/// are SKIPPED (not failed), which keeps a developer machine without Node from showing a false red build.
/// </summary>
public static class Synth
{
// The same feature flag as cdk.json. Tests do not read cdk.json, so they must set what the app sets.
private static readonly Dictionary<string, object> Flags = new()
{
["@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy"] = true,
};
public static Template EvidenceBucketTemplate(string environmentName)
{
RequireNode();
var app = NewApp();
var stack = NewStack(app);
_ = new EvidenceBucket(stack, "Exports", new EvidenceBucketProps { EnvironmentName = environmentName });
return Template.FromStack(stack);
}
public static Template WithReader(string environmentName)
{
RequireNode();
var app = NewApp();
var stack = NewStack(app);
var evidence = new EvidenceBucket(stack, "Exports", new EvidenceBucketProps { EnvironmentName = environmentName });
var role = new Amazon.CDK.AWS.IAM.Role(stack, "Reader", new Amazon.CDK.AWS.IAM.RoleProps
{
AssumedBy = new Amazon.CDK.AWS.IAM.ServicePrincipal("ecs-tasks.amazonaws.com"),
});
evidence.GrantReader(role);
return Template.FromStack(stack);
}
/// <summary>A stack with the aspect registered. A violation is recorded as an error annotation on the construct.</summary>
public static Stack AspectStack(bool addRawBucket)
{
RequireNode();
var app = NewApp();
var stack = NewStack(app);
_ = new EvidenceBucket(stack, "Exports", new EvidenceBucketProps { EnvironmentName = "dev" });
if (addRawBucket)
{
_ = new Amazon.CDK.AWS.S3.CfnBucket(stack, "Careless"); // no encryption: the aspect must object
}
Aspects.Of(app).Add(new RequireEncryptedBuckets());
return stack;
}
/// <summary>
/// Runs cdk-nag (AWS Solutions pack) the way cdk-nag v3 works: as a CDK policy-validation plugin.
/// With the context flag below, the CDK writes policy-validation-report.json into the cloud assembly,
/// and this method returns every finding that is not acknowledged as "rule @ construct path".
/// </summary>
public static IReadOnlyList<string> NagFindings(Action<Stack> addAcknowledgments)
{
RequireNode();
var outdir = Path.Combine(Path.GetTempPath(), "hl-nag-" + Guid.NewGuid().ToString("N"));
var context = new Dictionary<string, object>(Flags) { ["@aws-cdk/core:validationReportJson"] = true };
var app = new App(new AppProps { Outdir = outdir, Context = context });
var stack = NewStack(app);
_ = new EvidenceBucket(stack, "Exports", new EvidenceBucketProps { EnvironmentName = "dev" });
addAcknowledgments(stack);
Validations.Of(app).AddPlugins(new AwsSolutionsChecks(app, new NagPackProps { Verbose = true }));
var findings = new List<string>();
try { app.Synth(); }
catch (Exception ex) { findings.Add("synth threw: " + ex.Message); }
var reportPath = Path.Combine(outdir, "policy-validation-report.json");
if (!File.Exists(reportPath))
{
findings.Add("no policy-validation-report.json was written, so cdk-nag did not run");
return findings;
}
using var report = JsonDocument.Parse(File.ReadAllText(reportPath));
if (report.RootElement.TryGetProperty("pluginReports", out var reports))
{
foreach (var r in reports.EnumerateArray())
{
if (!r.TryGetProperty("violations", out var violations)) continue;
foreach (var v in violations.EnumerateArray())
{
var rule = v.TryGetProperty("ruleName", out var n) ? n.GetString() : "?";
var where = v.TryGetProperty("violatingConstructs", out var list) && list.ValueKind == JsonValueKind.Array
? string.Join(", ", list.EnumerateArray().Select(c => c.TryGetProperty("constructPath", out var p) ? p.GetString() : "?"))
: "?";
findings.Add($"{rule} @ {where}");
}
}
}
try { Directory.Delete(outdir, recursive: true); } catch (IOException) { }
return findings;
}
private static App NewApp() => new(new AppProps { Context = Flags });
private static Stack NewStack(App app) => new(app, "test", new StackProps
{
// A fictional account ID from the documentation range: tests never contact AWS.
Env = new Amazon.CDK.Environment { Account = "111122223333", Region = "us-east-1" },
});
/// <summary>
/// On a developer machine without Node.js the CDK tests are skipped. In CI (CI=true) a missing Node.js is a FAILURE,
/// because a build that skips every CDK test has proved nothing.
/// </summary>
private static void RequireNode()
{
var ci = string.Equals(System.Environment.GetEnvironmentVariable("CI"), "true", StringComparison.OrdinalIgnoreCase);
if (ci)
{
Assert.True(NodeIsAvailable.Value, "Node.js 22 or 24 must be installed on the CI agent: CDK for .NET needs it to synthesize.");
}
else
{
Assert.SkipUnless(NodeIsAvailable.Value, "Node.js is not on PATH. CDK for .NET needs Node.js 22 or 24 to synthesize.");
}
}
private static readonly Lazy<bool> NodeIsAvailable = new(() =>
{
try
{
using var p = Process.Start(new ProcessStartInfo("node", "--version") { RedirectStandardOutput = true, RedirectStandardError = true });
p?.WaitForExit(10_000);
return p is { ExitCode: 0 };
}
catch (System.ComponentModel.Win32Exception)
{
return false;
}
});
}using Amazon.CDK.Assertions;
namespace Harbourline.Evidence.Cdk.Tests;
/// <summary>Fine-grained assertions: each test states one control and proves it on the synthesized template.</summary>
public class EvidenceBucketTests
{
[Fact]
public void Two_buckets_are_created_and_each_has_a_tls_only_policy()
{
var template = Synth.EvidenceBucketTemplate("dev");
template.ResourceCountIs("AWS::S3::Bucket", 2); // the evidence bucket and its access-log bucket
template.ResourceCountIs("AWS::S3::BucketPolicy", 2);
template.HasResourceProperties("AWS::S3::BucketPolicy", new Dictionary<string, object>
{
["PolicyDocument"] = Match.ObjectLike(new Dictionary<string, object>
{
["Statement"] = Match.ArrayWith(new object[]
{
Match.ObjectLike(new Dictionary<string, object>
{
["Effect"] = "Deny",
["Condition"] = new Dictionary<string, object>
{
["Bool"] = new Dictionary<string, object> { ["aws:SecureTransport"] = "false" },
},
}),
}),
}),
});
}
[Fact]
public void Evidence_bucket_is_private_versioned_and_encrypted_with_a_customer_managed_key()
{
var template = Synth.EvidenceBucketTemplate("dev");
template.HasResourceProperties("AWS::S3::Bucket", new Dictionary<string, object>
{
["VersioningConfiguration"] = new Dictionary<string, object> { ["Status"] = "Enabled" },
["PublicAccessBlockConfiguration"] = new Dictionary<string, object>
{
["BlockPublicAcls"] = true,
["BlockPublicPolicy"] = true,
["IgnorePublicAcls"] = true,
["RestrictPublicBuckets"] = true,
},
["BucketEncryption"] = Match.ObjectLike(new Dictionary<string, object>
{
["ServerSideEncryptionConfiguration"] = Match.ArrayWith(new object[]
{
Match.ObjectLike(new Dictionary<string, object>
{
["BucketKeyEnabled"] = true,
["ServerSideEncryptionByDefault"] = Match.ObjectLike(new Dictionary<string, object>
{
["SSEAlgorithm"] = "aws:kms",
["KMSMasterKeyID"] = Match.AnyValue(),
}),
}),
}),
}),
});
}
[Fact]
public void Key_rotates_every_year()
{
Synth.EvidenceBucketTemplate("dev").HasResourceProperties("AWS::KMS::Key", new Dictionary<string, object>
{
["EnableKeyRotation"] = true,
["PendingWindowInDays"] = 7,
});
}
[Fact]
public void Prod_keeps_its_data_and_has_no_auto_delete_helper()
{
var template = Synth.EvidenceBucketTemplate("prod");
template.HasResource("AWS::S3::Bucket", new Dictionary<string, object>
{
["DeletionPolicy"] = "Retain",
["UpdateReplacePolicy"] = "Retain",
});
template.HasResource("AWS::KMS::Key", new Dictionary<string, object> { ["DeletionPolicy"] = "Retain" });
template.ResourceCountIs("Custom::S3AutoDeleteObjects", 0);
}
[Fact]
public void Dev_can_be_destroyed_in_one_command()
{
var template = Synth.EvidenceBucketTemplate("dev");
template.HasResource("AWS::S3::Bucket", new Dictionary<string, object> { ["DeletionPolicy"] = "Delete" });
template.ResourceCountIs("Custom::S3AutoDeleteObjects", 2);
}
[Fact]
public void Reader_grant_includes_kms_decrypt_and_no_write_actions()
{
var template = Synth.WithReader("dev");
template.HasResourceProperties("AWS::IAM::Policy", new Dictionary<string, object>
{
["PolicyDocument"] = Match.ObjectLike(new Dictionary<string, object>
{
["Statement"] = Match.ArrayWith(new object[]
{
Match.ObjectLike(new Dictionary<string, object>
{
["Action"] = Match.ArrayWith(new object[] { "kms:Decrypt" }),
["Effect"] = "Allow",
}),
}),
}),
});
// A reader must never be able to write or delete evidence.
var policies = template.FindResources("AWS::IAM::Policy");
var text = System.Text.Json.JsonSerializer.Serialize(policies);
Assert.DoesNotContain("s3:PutObject", text, StringComparison.Ordinal);
Assert.DoesNotContain("s3:DeleteObject", text, StringComparison.Ordinal);
}
[Fact]
public void Aspect_accepts_the_evidence_bucket_and_flags_a_raw_unencrypted_bucket()
{
var clean = Annotations.FromStack(Synth.AspectStack(addRawBucket: false));
Assert.Empty(clean.FindError("*", Match.StringLikeRegexp(".*no default encryption.*")));
// Aspect errors are annotations: the CDK CLI refuses to continue, and tests read them with Annotations.
var careless = Annotations.FromStack(Synth.AspectStack(addRawBucket: true));
careless.HasError("*", Match.StringLikeRegexp(".*no default encryption.*"));
}
}using Amazon.CDK;
using Amazon.CDK.AWS.S3;
using Cdklabs.CdkNag;
namespace Harbourline.Evidence.Cdk.Tests;
/// <summary>cdk-nag (AWS Solutions pack) as a unit test: every finding is either fixed or acknowledged with a reason.</summary>
public class NagTests
{
[Fact]
public void Evidence_bucket_has_no_unacknowledged_findings()
{
var findings = Synth.NagFindings(_ => { });
Assert.True(findings.Count == 0, "cdk-nag findings:\n" + string.Join("\n", findings));
}
[Fact]
public void Cdk_nag_really_detects_a_careless_bucket()
{
// Guards against a silently empty report: a bucket with no encryption, logging or TLS rule must be flagged.
var findings = Synth.NagFindings(stack => _ = new CfnBucket(stack, "Careless"));
Assert.Contains(findings, f => f.StartsWith("AwsSolutions-S1 @", StringComparison.Ordinal));
Assert.Contains(findings, f => f.StartsWith("AwsSolutions-S10 @", StringComparison.Ordinal));
}
[Fact]
public void An_acknowledged_finding_is_not_reported_but_the_others_still_are()
{
var findings = Synth.NagFindings(stack =>
{
var scratch = new CfnBucket(stack, "Careless");
// cdk-nag v3: acknowledge with the exact rule ID and a reason a reviewer can disagree with.
Validations.Of(scratch).Acknowledge(new[]
{
new Acknowledgment { Id = "AwsSolutions-S1", Reason = "Scratch bucket for this test: access logs are not needed." },
});
});
Assert.DoesNotContain(findings, f => f.StartsWith("AwsSolutions-S1 @", StringComparison.Ordinal));
Assert.Contains(findings, f => f.StartsWith("AwsSolutions-S10 @", StringComparison.Ordinal));
}
}The coarse snapshot (from the lab)
The Module 10 lab adds one more test, SnapshotTests, which counts resources by CloudFormation type and compares the counts with a file committed next to the test. A snapshot of the whole template would break on every CDK upgrade (asset hashes, logical IDs), and reviewers would learn to accept it blindly. Counting resource types still catches the questions that matter in a pull request: "why does this change add a NAT gateway, remove an alarm, or add an IAM policy?" The committed file looks like this (trimmed):
{
"app": {
"AWS::CloudWatch::Alarm": 5,
"AWS::ECS::Service": 1,
"AWS::RDS::DBInstance": 1,
"AWS::SNS::Topic": 1
},
"foundation": {
"AWS::EC2::VPCEndpoint": 5,
"AWS::ECR::Repository": 1
}
}To accept an intended change, set UPDATE_SNAPSHOTS=1 (or delete the file), run the tests, and commit the diff with the code change. In CI (CI=true) a missing snapshot fails the build, so nobody can "pass" by deleting the file.
Code explained line by line
xunit.v3on Microsoft.Testing.Platform. The test project hasOutputTypeExeand the runner choice lives inglobal.json.dotnet test --project ...(or--solution ...) runs it. No VSTest adapter packages are needed.xunit.runner.jsonwith parallelism off. jsii, the bridge to the CDK's Node.js process, is not designed for parallel calls. Disabling test parallelism avoids intermittent failures.Synth.Flags. Tests createnew App()directly and do not readcdk.json, so they must set the same feature flags the real app gets fromcdk.json. Forgetting this gives errors in tests that never occur in the CLI (or the reverse).RequireNode(). Locally, a missing Node.js skips the test (Assert.SkipUnless). In CI,Assert.Truefails it. The difference matters: in the lab, all 28 CDK tests skipped silently on a machine without Node.js while a real dependency cycle sat in the code.Template.FromStack(stack). Synthesizes the whole app (not only that stack) and returns an object to query. The first call in a process starts Node.js and takes several seconds.Match.ObjectLikeandMatch.ArrayWith.ObjectLikeignores extra properties.ArrayWithrequires the listed elements, in order, among others. Together they say "somewhere in the statement list there is a Deny with this condition" without freezing the whole policy.HasResourcewithDeletionPolicy.HasResourcePropertieslooks insideProperties;DeletionPolicyandUpdateReplacePolicyare siblings ofProperties, so you useHasResource.Reader_grant_includes_kms_decrypt.... Positive and negative in one test: the policy must containkms:Decrypt, and the serialized policies must not contains3:PutObjectors3:DeleteObject. Negative checks protect least privilege.Annotations.FromStack. An aspect error is an annotation, not an exception. The CDK CLI refuses to continue, but a plainSynth()orTemplate.FromStackdoes not throw, so tests read annotations withFindError/HasError.Synth.NagFindings. cdk-nag v3 is a CDK policy-validation plugin. The context key@aws-cdk/core:validationReportJsonmakes the CDK writepolicy-validation-report.jsoninto the output folder; the helper readspluginReportsandviolationsfrom it and returns"rule @ construct path"strings.Verbose = trueadds finding details.Cdk_nag_really_detects_a_careless_bucket. The positive control. If the plugin silently stopped running, the "no findings" test would still pass. Proving that a known-bad bucket is flagged (AwsSolutions-S1for missing access logs,AwsSolutions-S10for missing TLS enforcement) guards against that.Validations.Of(scratch).Acknowledge(...). cdk-nag v3 removed the old suppression API. You acknowledge with the CDK's ownValidationsAPI, with the exact rule ID and a reason. Plain rule IDs such asAwsSolutions-S1work for single-finding rules; rules that report per resource or per action need the full finding ID, for exampleAwsSolutions-IAM5[Resource::*]. Prefix matching is not supported ⚠ VERIFY in the cdk-nag README for your version.StartsWith("AwsSolutions-S1 @").AwsSolutions-S10also containsAwsSolutions-S1as a prefix. A first draft of this test usedContainsand failed for exactly that reason. Match whole IDs.
Reading a cdk-nag finding
A finding has a rule ID, a construct path and a short explanation. The AWS Solutions pack (and the others: HIPAA Security, NIST 800-53 rev 4 and rev 5, PCI DSS 3.2.1, Serverless) report like this:
AwsSolutions-S1 @ test/Careless The S3 Bucket has server access logs disabled.
AwsSolutions-S10 @ test/Careless The S3 Bucket or bucket policy does not require requests to use SSL.For each finding you have three honest choices:
| Choice | When | Example |
|---|---|---|
| Fix | The control is right and cheap | Add EnforceSSL = true |
| Acknowledge with a reason | The rule does not apply here, or the risk is accepted | "ELB access logs need a retained S3 bucket that outlives teardown; enabled in test and prod" |
| Change the design | The rule exposes a real problem | Replace a wildcard IAM statement with a narrower grant |
The Module 10 lab's AppStack is the worked example. Its acknowledgments, each with a reason a reviewer can disagree with:
Validations.Of(this).Acknowledge(
[
new Acknowledgment { Id = "AwsSolutions-ELB2", Reason = "Lab: ALB access logs need a retained S3 bucket that outlives teardown. Enable them in test/prod (Module 11)." },
new Acknowledgment { Id = "AwsSolutions-ECS2", Reason = "Only non-secret settings are plain environment variables; the database credentials use ECS secrets from Secrets Manager." },
new Acknowledgment { Id = "AwsSolutions-IAM5[Resource::*]", Reason = "Task execution role: ecr:GetAuthorizationToken has no resource-level permissions." },
]);A bank-grade suppression policy goes further than a reason string: an owner, a ticket reference, and an expiry date after which the acknowledgment must be renewed. cdk-nag does not enforce expiry for you; do it in a helper that refuses short reasons and a unit test that scans your acknowledgments for expired dates.
public static class Acknowledgments
{
/// <summary>A reason must say why, and carry a ticket and an expiry, or the helper refuses it.</summary>
public static Acknowledgment Ack(string id, string reason, string ticket, DateOnly expires)
{
if (reason.Length < 30)
throw new ArgumentException($"Acknowledgment {id}: write a reason a reviewer can disagree with (30+ characters).");
if (expires < DateOnly.FromDateTime(DateTime.UtcNow))
throw new InvalidOperationException($"Acknowledgment {id} expired on {expires:yyyy-MM-dd} ({ticket}). Fix the finding or renew with a new review.");
return new Acknowledgment { Id = id, Reason = $"{reason} [{ticket}, review by {expires:yyyy-MM-dd}]" };
}
}Because the helper throws at synthesis time, an expired acknowledgment fails every build until someone reviews it.
Running the suite three ways
On the course machine, with the three modes verified for this lesson's project:
| Mode | Command | Result |
|---|---|---|
| No Node.js, locally | dotnet test ... | 10 skipped: not red, not green, visible in the output |
| No Node.js, CI mode | CI=true dotnet test ... | 10 failed: the agent is misconfigured, and the build says so |
| Node.js 22 | CI=true dotnet test ... | 10 passed |
For the whole Module 10 lab: 50 tests: 22 pure C# tests (settings, profiles, the drift report) that always run, and 28 CDK tests that need Node.js. Without Node.js: 22 passed and 28 skipped. With Node.js 22: 50 passed (this includes the cdk-nag test in dev and prod and the resource-count snapshot).
A harmless warning appears when the tests load cdk-nag with this version pair: ReflectionTypeLoadException while searching for JSII types ... Method 'get_StackTemplates' in type '_Proxy' ... does not have an implementation. It is printed by the jsii runtime and does not affect results ⚠ VERIFY whether a newer Cdklabs.CdkNag removes it.
Security considerations
⚠ Learning shortcut — not for production
The tests acknowledge findings with plain reason strings and no expiry, and they run on your laptop. In production, acknowledgments carry a ticket and an expiry (helper above), the suite runs in a pipeline on an agent with no cloud credentials, and a failing nag test blocks the merge. A passing run is attached to the release record as evidence.
- Tests need no credentials. If a unit test asks for AWS access, you are testing the wrong layer. Use fake account IDs from the documentation range (
111122223333). - A test that never failed proves nothing. Write the test first, watch it fail, then make it pass. The positive control for cdk-nag is the same idea applied to a tool.
- Skips are silent holes. Fail in CI when a prerequisite is missing.
- Do not log secrets in assertion messages. Failure output goes to build logs.
- cdk-nag packs are not a compliance claim. The PCI DSS 3.2.1 or NIST packs help find known misconfigurations; passing them does not mean the environment is compliant. The compliance function decides that.
- Pull-request builds run untrusted code. Give the test job read-only repository access, no secrets, and no network to internal systems.
- Treat acknowledgments as risk acceptances. Reviewers read them like exception requests.
Banking use case
Harbourline's platform repository has a required status check, iac-tests, on every pull request. It runs the settings tests, the construct assertions, the coarse snapshot and cdk-nag for dev and prod. The pull-request page shows the test summary and a link to the cdk diff. When the platform team changes EvidenceBucket, the snapshot of resource counts and the control assertions change in the same pull request, and a security reviewer approves both. Each quarter, the second line samples ten acknowledgments and checks the reason, the ticket and whether the expiry was honoured.
Common mistakes
- Asserting everything. A test per property of every resource turns each harmless change into a red build. Test the controls.
- Forgetting the feature flags in
new App()inside tests, which gives different output from the CLI. - Using
Contains("AwsSolutions-S1")and matchingAwsSolutions-S10. Match whole rule IDs. - Expecting aspect errors to throw. They are annotations; read them with
Annotations. - Letting Node.js skips pass in CI. Fail the build instead.
- Synthesizing in every test. One expensive synthesis shared by many tests (a
Lazy<>as in the lab) turns a 5-minute suite into 30 seconds. - A full-template snapshot. It will be accepted blindly after the first CDK upgrade.
- Acknowledging without a reason or with a copy-pasted reason.
- Testing implementation, not behaviour. "There is exactly one
AWS::IAM::Policy" breaks when you add a harmless grant; "the task role has nos3:*" does not.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| All CDK tests skipped | Node.js not on PATH | Install Node.js 22 or 24; in CI set CI=true so a missing Node fails |
DependencyCycle: ... would create a cyclic reference | A cross-stack grant edits a resource policy | Import the resource by ARN in the consumer (see the previous lesson) |
objectOwnership must be set to "ObjectWriter" when accessControl is "LogDeliveryWrite" in tests only | The test App lacks the feature flag cdk.json provides | Set @aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy in the test context |
HasResourceProperties fails but the template looks right | A token or Fn::GetAtt where you expected a string | Use Match.AnyValue() for deploy-time values |
| Aspect test passes but the error never appears | You expected an exception | Read Annotations.FromStack(stack) |
no policy-validation-report.json was written | The plugin did not run: missing context key or plugin added after synth | Set @aws-cdk/core:validationReportJson and call AddPlugins before Synth() |
| Nag finding ID with brackets will not acknowledge | v3 matches exact finding IDs | Copy the full ID, for example AwsSolutions-IAM5[Resource::*] |
| Tests hang or fail randomly | Parallel jsii calls | parallelizeTestCollections and parallelizeAssembly false in xunit.runner.json |
Unsupported feature flag '@aws-cdk/aws-kms:defaultKeyPolicies' | The flag existed in CDK v1 and is gone in v2 | Remove it; v2 behaves as if it were on |
| Snapshot test fails in CI with "missing" | Snapshot file not committed | Run locally, commit the file |
Cost and cleanup
Cost: free. Tests synthesize on your machine and never contact AWS. Nothing is deployed, so nothing is billing.
# remove build output and the temporary cdk-nag report folders
find . -type d \( -name bin -o -name obj -o -name TestResults \) -prune -exec rm -rf {} +
rm -rf "${TMPDIR:-/tmp}"/hl-nag-* 2>/dev/null || trueExercises
- 🟢 Guided: create the test project, add
Synth.csandEvidenceBucketTests.cs, and run the suite without Node.js and then with it. Break one control inEvidenceBucket(removeEnforceSSL = true) and watch the TLS test fail. - 🟡 Challenge: add a test that a prod
EvidenceBuckethas aRetainpolicy on the key and both buckets, and thatCustom::S3AutoDeleteObjectscount is zero. Then add theAcknowledgments.Ackhelper and a test that an expired acknowledgment throws. - 🔴 Live problem: the nightly build is green, but production shows an S3 bucket without TLS enforcement. Your tests pass. List at least four reasons the control could be missing in production while tests pass (hint: think about what the tests do not see), and say which later control would catch each.
Assignment
In your portfolio repository add tests/ for your Harbourline.Constructs library: at least five assertions (one per control), the resource-count snapshot, the cdk-nag test with a positive control, and a GitHub Actions workflow (or a design document) that installs Node.js 22, sets CI=true, runs dotnet test and uploads the TRX or console summary.
Solutions
Without Node.js and with CI unset, all 10 tests are reported as skipped; with Node.js they pass. Removing EnforceSSL = true makes Two_buckets_are_created_and_each_has_a_tls_only_policy fail, because the TLS-deny statement disappears from both bucket policies. The point of removing it yourself: you now know the test can fail.
Use Synth.EvidenceBucketTemplate("prod") and HasResource("AWS::S3::Bucket", new Dictionary<string, object> { ["DeletionPolicy"] = "Retain", ["UpdateReplacePolicy"] = "Retain" }), and HasResource("AWS::KMS::Key", new Dictionary<string, object> { ["DeletionPolicy"] = "Retain" }), then ResourceCountIs("Custom::S3AutoDeleteObjects", 0). To prove both buckets are retained rather than any one, use template.FindResources("AWS::S3::Bucket") and assert every entry has DeletionPolicy Retain. For the helper test, call Acknowledgments.Ack("AwsSolutions-X", new string('x', 40), "SEC-123", new DateOnly(2020, 1, 1)) inside Assert.Throws<InvalidOperationException>.
Possible reasons: (1) someone changed the bucket in the console (drift; caught by drift detection and AWS Config); (2) the bucket was created outside the code, by hand or another tool (inventory and tag-based checks); (3) the deployed commit is older than the tested one, or the pipeline deployed from a branch without the check (release evidence and branch protection); (4) an acknowledgment or aspect exemption disabled the rule for that resource (suppression review with expiry); (5) the stack in production is a different stack that the tests never synthesize (test coverage of the real app entry point; the lab's tests call the same HarbourlineApp.Build as Program.cs for exactly this reason); (6) the Region or account differs from what tests assume (environment-specific assertions in each profile). Detective controls (Config rules, drift detection) and preventive ones (SCPs) cover what build-time tests cannot.
Knowledge check
Answer: The CDK construct library is TypeScript. .NET calls it through the jsii bridge, which starts a Node.js process, and synthesis runs inside it. Without Node.js the tests cannot synthesize.
Answer: A skipped test is invisible in a green build. If every CDK test skips, the pipeline reports success while checking nothing. Failing in CI turns a misconfigured agent into an obvious red build.
Answer: At least one resource of that type whose properties contain the given ones; extra properties are ignored. Use Match.Absent() to require that a property is missing.
Answer: Validations.Of(construct).Acknowledge(new Acknowledgment { Id = ..., Reason = ... }) with the exact rule or finding ID and a reason. The v3 release removed the old suppression API.
Answer: To prove the tool really runs. If the plugin silently produced no report, a test asserting "no findings" would still pass. A deliberately bad bucket that must produce AwsSolutions-S1 and AwsSolutions-S10 guards against false comfort.
Answer: A full snapshot changes on harmless things (asset hashes, logical ID hashes after upgrades), so reviewers approve it blindly. Resource counts per type still reveal surprising additions and removals.
Interview questions
- "How do you test infrastructure code without deploying it?" Synthesize in a unit test and assert on the template (resources, properties, counts, annotations), add a coarse snapshot, and run a policy pack such as cdk-nag. Integration tests in a sandbox account come later and are separate.
- "What would you assert and what would you leave alone?" Controls: encryption, TLS, public access, IAM breadth, retention, deletion policies, resource counts for expensive types. Not incidental properties such as generated names.
- "How do you manage cdk-nag exceptions?" Acknowledge by exact ID with a reason, a ticket and an expiry, review them periodically, and fail the build when one expires.
- "What did you learn about silent test skips?" They hide real defects (a dependency cycle in the lab). Fail on missing prerequisites in CI.
Certification practice
A team wants every pull request to prove that CDK-defined S3 buckets enforce encryption and TLS before any deployment. The build agent must not hold AWS credentials. Which approach fits?
A. Deploy the stack to a test account in every pull request and inspect it by hand.
B. Unit tests that synthesize the stack and assert on the CloudFormation template, plus cdk-nag with the AWS Solutions pack.
C. Run aws s3api get-bucket-encryption in the pipeline against production.
D. Ask reviewers to read the C# code.
Answer: B. Synthesis and template assertions need no credentials and run in seconds. A is slow and needs credentials. C checks after the fact, in production. D is manual and error-prone.
An organisation uses cdk-nag with an AWS Solutions rule pack and wants to allow a justified exception for one resource while keeping the rule active everywhere else, with an audit trail. What is the best approach?
A. Remove the rule pack from the app. B. Acknowledge the specific finding on that construct with a written reason, and review acknowledgments periodically. C. Edit the generated template by hand after synthesis. D. Disable validation in CI only.
Answer: B. Acknowledgments are scoped to a construct and carry a reason, keeping the rule active elsewhere. A and D remove the control. C breaks reproducibility and is invisible in code review.
A CDK test suite reports success, but the build log shows that all infrastructure tests were skipped because Node.js is not installed on the build agent. What should the team change?
A. Nothing: skipped tests are the same as passed tests. B. Install a supported Node.js version on the agent and make the suite fail when Node.js is missing in CI. C. Delete the tests. D. Run the tests only on developers' laptops.
Answer: B. The CDK needs Node.js to synthesize, and a pipeline must not report green when it checked nothing. A, C and D leave the control unverified.
Completion checklist
- I built the test project and ran it with and without Node.js
- I wrote one assertion per control and watched one fail on purpose
- I ran cdk-nag as a test and proved it detects a bad bucket
- I acknowledged a finding with the v3 API and a reason
- I can explain why the suite fails in CI when Node.js is missing
Key takeaways
- Synthesize in memory, assert on the template: fast, credential-free evidence.
- Assert controls, not incidental properties; keep snapshots coarse.
- cdk-nag v3 is a plugin; acknowledge with exact IDs and written reasons through the
ValidationsAPI. - Prove your checks work with a positive control; a check that cannot fail is decoration.
- Fail in CI when a prerequisite such as Node.js is missing; silent skips hid a real bug in the lab.
Related lessons and next steps
- Previous: CDK stacks, environments and configuration
- Next: Lab: one environment, two tools
- Compare with: Terraform fundamentals and Policy-as-code and secure deployment
Further reading
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
CDK stacks, environments and configuration
Split an app into stacks by lifecycle, pass values between them without creating dependency cycles, drive dev, test and prod from one codebase with typed settings, and understand what cdk bootstrap creates and how to narrow it.
Terraform fundamentals
Write, plan and apply your first Terraform configuration for AWS: an encrypted, private audit-evidence bucket for Harbourline Bank. You learn providers, resources, data sources, variables, outputs and the init, plan, apply and destroy workflow.