Skip to Content
Cloud Engineering Academy
10. Infrastructure as Code

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.

advanced⏱ 2 h 30 min🟢 FreeDOP-C02SAP-C03

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, Match and Annotations.
  • 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 test and policy scanners.

Prerequisites

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:

LayerNeeds Node.js?What it provesExample
Pure C# testsNoSettings and helpers behaveAn invalid CIDR is rejected
Fine-grained assertionsYesA resource has specific propertiesThe bucket blocks public access
SnapshotYesThe shape of the template did not change by surpriseThe stack still has 2 buckets and 5 alarms
Policy scan (cdk-nag)YesThe template meets a rule packNo unacknowledged AWS Solutions findings

What problem this solves

ProblemCheck that catches it
Someone removes EnforceSSL from a shared constructAssertion 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 IAMCoarse snapshot plus cdk diff in the pull request
An unencrypted raw bucket sneaks inAspect and cdk-nag
A suppression with no reasonHelper 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 equivalentWhat's different
Pester tests over ARM or Bicep outputxUnit tests over the synthesized templateSame idea; here the "template" is produced by running your C#
ARM-TTK (template test toolkit)cdk-nag, cfn-lintRule packs applied during synthesis
Azure Policy audit modecdk-nag acknowledgments with reasonsFindings fail the build unless acknowledged
bicep build plus snapshot in GitCoarse snapshot testCount resources by type, not the whole file
What-if in a PRcdk diff in a PRComplements 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.csproj

On 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:

CallMeaning
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.StringLikeRegexpPartial 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.

global.json (repository root)
{
  "sdk": {
    "version": "10.0.100",
    "rollForward": "latestFeature"
  },
  "test": {
    "runner": "Microsoft.Testing.Platform"
  }
}
tests/Harbourline.Evidence.Cdk.Tests/Harbourline.Evidence.Cdk.Tests.csproj
<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>
tests/Harbourline.Evidence.Cdk.Tests/xunit.runner.json
{
  "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
  "parallelizeTestCollections": false,
  "parallelizeAssembly": false
}
tests/Harbourline.Evidence.Cdk.Tests/Synth.cs
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;
        }
    });
}
tests/Harbourline.Evidence.Cdk.Tests/EvidenceBucketTests.cs
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.*"));
    }
}
tests/Harbourline.Evidence.Cdk.Tests/NagTests.cs
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):

tests/Harbourline.Environment.Cdk.Tests/snapshots/dev-resource-counts.json
{
  "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

  1. xunit.v3 on Microsoft.Testing.Platform. The test project has OutputType Exe and the runner choice lives in global.json. dotnet test --project ... (or --solution ...) runs it. No VSTest adapter packages are needed.
  2. xunit.runner.json with parallelism off. jsii, the bridge to the CDK's Node.js process, is not designed for parallel calls. Disabling test parallelism avoids intermittent failures.
  3. Synth.Flags. Tests create new App() directly and do not read cdk.json, so they must set the same feature flags the real app gets from cdk.json. Forgetting this gives errors in tests that never occur in the CLI (or the reverse).
  4. RequireNode(). Locally, a missing Node.js skips the test (Assert.SkipUnless). In CI, Assert.True fails 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.
  5. 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.
  6. Match.ObjectLike and Match.ArrayWith. ObjectLike ignores extra properties. ArrayWith requires 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.
  7. HasResource with DeletionPolicy. HasResourceProperties looks inside Properties; DeletionPolicy and UpdateReplacePolicy are siblings of Properties, so you use HasResource.
  8. Reader_grant_includes_kms_decrypt.... Positive and negative in one test: the policy must contain kms:Decrypt, and the serialized policies must not contain s3:PutObject or s3:DeleteObject. Negative checks protect least privilege.
  9. Annotations.FromStack. An aspect error is an annotation, not an exception. The CDK CLI refuses to continue, but a plain Synth() or Template.FromStack does not throw, so tests read annotations with FindError/HasError.
  10. Synth.NagFindings. cdk-nag v3 is a CDK policy-validation plugin. The context key @aws-cdk/core:validationReportJson makes the CDK write policy-validation-report.json into the output folder; the helper reads pluginReports and violations from it and returns "rule @ construct path" strings. Verbose = true adds finding details.
  11. 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-S1 for missing access logs, AwsSolutions-S10 for missing TLS enforcement) guards against that.
  12. Validations.Of(scratch).Acknowledge(...). cdk-nag v3 removed the old suppression API. You acknowledge with the CDK's own Validations API, with the exact rule ID and a reason. Plain rule IDs such as AwsSolutions-S1 work for single-finding rules; rules that report per resource or per action need the full finding ID, for example AwsSolutions-IAM5[Resource::*]. Prefix matching is not supported ⚠ VERIFY in the cdk-nag README for your version.
  13. StartsWith("AwsSolutions-S1 @"). AwsSolutions-S10 also contains AwsSolutions-S1 as a prefix. A first draft of this test used Contains and 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:

ChoiceWhenExample
FixThe control is right and cheapAdd EnforceSSL = true
Acknowledge with a reasonThe 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 designThe rule exposes a real problemReplace 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:

ModeCommandResult
No Node.js, locallydotnet test ...10 skipped: not red, not green, visible in the output
No Node.js, CI modeCI=true dotnet test ...10 failed: the agent is misconfigured, and the build says so
Node.js 22CI=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 matching AwsSolutions-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 no s3:*" does not.

Troubleshooting

SymptomLikely causeFix
All CDK tests skippedNode.js not on PATHInstall Node.js 22 or 24; in CI set CI=true so a missing Node fails
DependencyCycle: ... would create a cyclic referenceA cross-stack grant edits a resource policyImport the resource by ARN in the consumer (see the previous lesson)
objectOwnership must be set to "ObjectWriter" when accessControl is "LogDeliveryWrite" in tests onlyThe test App lacks the feature flag cdk.json providesSet @aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy in the test context
HasResourceProperties fails but the template looks rightA token or Fn::GetAtt where you expected a stringUse Match.AnyValue() for deploy-time values
Aspect test passes but the error never appearsYou expected an exceptionRead Annotations.FromStack(stack)
no policy-validation-report.json was writtenThe plugin did not run: missing context key or plugin added after synthSet @aws-cdk/core:validationReportJson and call AddPlugins before Synth()
Nag finding ID with brackets will not acknowledgev3 matches exact finding IDsCopy the full ID, for example AwsSolutions-IAM5[Resource::*]
Tests hang or fail randomlyParallel jsii callsparallelizeTestCollections 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 v2Remove it; v2 behaves as if it were on
Snapshot test fails in CI with "missing"Snapshot file not committedRun 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 || true

Exercises

  • 🟢 Guided: create the test project, add Synth.cs and EvidenceBucketTests.cs, and run the suite without Node.js and then with it. Break one control in EvidenceBucket (remove EnforceSSL = true) and watch the TLS test fail.
  • 🟡 Challenge: add a test that a prod EvidenceBucket has a Retain policy on the key and both buckets, and that Custom::S3AutoDeleteObjects count is zero. Then add the Acknowledgments.Ack helper 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

Knowledge check

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

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 Validations API.
  • 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.

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.

On this page