Security & Cloud

Policy as Code for AWS CDK: Residency Guards and Keyless CI

How we fail CDK synthesis when data would leave Jakarta, keep cdk-nag suppressions honest, and deploy from GitHub Actions through OIDC with no stored keys.

Weaveward security & cloud editorial illustration

Most cloud guardrails live in a review checklist: someone is supposed to notice that a bucket landed in Singapore, that a suppression no longer applies, or that a pipeline still holds an access key. Checklists fail quietly. For teams in Indonesia the stakes are concrete, because "where does the personal data live?" must be answered under UU PDP and sector rules, and the honest answer has to come from the infrastructure.

Our position: the rules that matter most should run on every synthesis, fail the build when broken, and be impossible to silence without a written reason. Everything below comes from Cloud Platform Kit, an AWS CDK v2 prototype we built for Asia Pacific (Jakarta), ap-southeast-3. It runs on synthetic profiles and has never been deployed to a real account, so read the numbers as what the code produces at synthesis, not as operational results.

You will get a residency guard written as a CDK Aspect, cdk-nag suppressions that cannot go stale, tests that pin the guard itself, keyless OIDC deploys, and a map of what policy as code cannot see.

Where each check belongs

Policy as code is a set of checks that run at different moments, and each moment sees a different slice of reality. Synthesis sees the construct tree with full type information, which makes it the best place to reject a design. It cannot see what happens after deployment, or what the application does with data once it runs.

Layer When it runs What it catches What it misses
CDK Aspect (residency guard) Every synthesis Resources or copies outside approved regions, before a template exists Anything not defined in this CDK app
cdk-nag and a custom pack Every synthesis, as a validation plugin Encryption, public access, logging, tags, deletion protection Runtime behaviour, intent behind a suppression
Assertion tests npm test in CI Regressions in the guard and in environment-specific settings Rules nobody wrote a test for
Workflow checker Lint step in CI Stored keys, missing OIDC permission, unpinned actions, ungated production What happens inside an allowed step
IAM boundary, SCPs, AWS Config At request time or continuously in AWS Console changes, drift, other tools Design intent; findings arrive after the fact

The kit implements the first four layers and a permissions boundary. It ships no service control policies or AWS Config rules; we come back to that gap.

A residency guard that fails closed

The kit's guard is an Aspect added at AspectPriority.READONLY, so it runs after mutating aspects and judges the final tree. Aspects do not cross Stage boundaries, so the kit attaches it to every stage rather than once to the app. Below is a condensed version of the region check; the real one in infra/src/policy/residency/ also inspects edge origins and copy destinations.

import { AspectPriority, Aspects, CfnResource, type IAspect, Stack, Token, Validations } from "aws-cdk-lib";
import type { IConstruct } from "constructs";

// Global types that carry no personal data and cannot live in Jakarta anyway.
const REGION_FREE = new Set(["AWS::CertificateManager::Certificate"]);

export class ResidencyGuard implements IAspect {
  constructor(private readonly approved: ReadonlySet<string>) {}

  visit(node: IConstruct): void {
    if (!CfnResource.isCfnResource(node)) return; // every L1 resource, any service
    const region = Stack.of(node).region;
    if (Token.isUnresolved(region)) {
      Validations.of(node).addError("CPK-RES2", "Stack has no explicit region, so residency cannot be proven");
      return;
    }
    if (this.approved.has(region) || REGION_FREE.has(node.cfnResourceType)) return;
    Validations.of(node).addError("CPK-RES1", `Resource would be created in ${region}, outside the approved regions`);
  }
}

export const guardResidency = (scope: IConstruct, approved: Iterable<string>): void => {
  Aspects.of(scope).add(new ResidencyGuard(new Set(approved)), { priority: AspectPriority.READONLY });
};

Three design choices carry most of the weight.

Fail closed on resource type. The guard checks every CfnResource, not a list of known data stores. A list of "sensitive types" is always one service behind; a DynamoDB table added next quarter is caught on day one. The exception list stays short: ACM certificates and CLOUDFRONT-scope web ACLs, which CloudFront needs in us-east-1 and which store no personal data.

Fail on uncertainty. A region-agnostic stack resolves its region to a token. Treating that as "probably fine" is how residency guarantees evaporate, so an unresolved region is its own error, CPK-RES2.

Errors, not findings. In aws-cdk-lib 2.271.0, an error added through Validations.of(node).addError() is documented as not acknowledgeable. That is the property we want: a cdk-nag finding can be accepted with a reason, a residency breach cannot. Approving a region means changing the typed profile, a visible diff rather than a suppression buried in a stack.

Residency is more than the stack's region

A bucket in Jakarta can still leak. The full guard follows data that moves:

  • Copy destinations (CPK-RES4): backup plan copy actions, S3 replication rules, DynamoDB global table replicas and log subscription filters. The region is read from the destination ARN, and an ARN without a region, such as an S3 bucket ARN, fails as unverifiable
  • Edge origins (CPK-RES3): a CloudFront distribution may only front a bucket tagged with the public classification. CloudFront serves and caches from edge locations worldwide, so a personal-data origin behind it is a transfer, whatever the bucket's region says

Indonesia has one AWS region, so a recovery copy that survives the loss of that region has to leave the country. The kit keeps that copy off by default. Turning it on means approving a second region with a transfer basis, and the Zod profile schema refuses that entry until it records the reference of an approved transfer decision. The legal judgement stays with people; the code insists it is written down.

One honest limit from the kit's own status document: a copy destination passed in as a CloudFormation parameter is not resolved at synthesis, so CPK-RES4 cannot check its region.

Rule packs whose suppressions cannot rot

For general hygiene the kit runs cdk-nag's AwsSolutions pack plus its own CPK pack: encryption at rest declared on every data store, customer-managed keys for personal data, mandatory tags, no bucket that can become public, and retention plus deletion protection in production only. In cdk-nag 3, packs register through CDK's native plugin API, Validations.of(app).addPlugins(...), and suppressions become Validations.of(scope).acknowledge({ id, reason }).

Suppressions are where rule packs decay. A reason like "not needed" gets copied around, the resource it covered is deleted, and the stack-scoped suppression now hides the next real finding. The kit closes that gap in three steps:

  1. It subclasses AwsSolutionsChecks and wraps applyRule so every outcome, pass or acknowledged or fail, lands in a ledger
  2. Acknowledgements come only from one catalogue file, and a test holds each reason to at least twelve words
  3. After synthesis, any acknowledgement that matches no acknowledged finding in the ledger fails the build

The catalogue also records real trade-offs. cdk-nag's AwsSolutions-CFR3 wants CloudFront access logs, but the kit's acknowledgement explains that standard CloudFront logs carry viewer IP addresses and cannot be delivered to a bucket in ap-southeast-3, so enabling them would move personal data out of the approved region for a distribution that serves only public assets. Residency overrides a generic best practice, and the reason sits next to the rule ID.

With aws-cdk-lib 2.271.0 and cdk-nag 3.0.2, the production profile synthesises 136 resources with 204 recorded checks: 190 passed, 14 acknowledged with a reason and none failing. Across development, staging and production the pipeline synthesises 18 stacks and 571 checks in about 8 seconds on our development machine.

Testing the guard, not just the stacks

A guard that silently stops firing is worse than no guard, because people trust it. So the negative path gets tests: build a small app that violates the rule and assert that synthesis fails. These run offline: the kit takes availability zones from its profiles, performs no context lookups, and its tests scrub credential variables.

import { App, Stack, Validations } from "aws-cdk-lib";
import { Match, Template } from "aws-cdk-lib/assertions";
import { Bucket } from "aws-cdk-lib/aws-s3";
import { describe, expect, it } from "vitest";
import { createDeployRole } from "./ci-identity";
import { guardResidency } from "./residency-guard";

const guardedApp = (): App => {
  // Errors join the validation report, so app.synth() throws in-process.
  const app = new App({ context: { "@aws-cdk/core:annotationsInValidationReport": true } });
  guardResidency(app, ["ap-southeast-3"]);
  return app;
};

describe("platform guardrails", () => {
  it("fails synthesis for a bucket outside Jakarta, even when acknowledged", () => {
    const app = guardedApp();
    const bucket = new Bucket(new Stack(app, "Elsewhere", { env: { region: "ap-southeast-1" } }), "Records");
    Validations.of(bucket).acknowledge({ id: "CPK-RES1", reason: "attempt to silence the guard" });
    expect(() => app.synth()).toThrow(/CPK-RES1/);
  });

  it("lets only one repository's production environment assume the deploy role", () => {
    const stack = new Stack(guardedApp(), "Security", { env: { region: "ap-southeast-3" } });
    createDeployRole(stack, "example-org/cloud-platform-kit", "production");
    Template.fromStack(stack).hasResourceProperties("AWS::IAM::Role", {
      AssumeRolePolicyDocument: Match.objectLike({
        Statement: [Match.objectLike({
          Action: "sts:AssumeRoleWithWebIdentity",
          Condition: { StringEquals: {
            "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
            "token.actions.githubusercontent.com:sub": "repo:example-org/cloud-platform-kit:environment:production",
          } },
        })],
      }),
    });
  });
});

The context flag is the detail that trips teams up. Without @aws-cdk/core:annotationsInValidationReport, an error annotation is only metadata: the CDK CLI still refuses to deploy, but app.synth() inside a test returns normally. We hit exactly that while verifying this snippet. With the flag on, which the kit sets in cdk.json, errors join the policy validation report and synthesis throws, so tests and the CLI fail the same way.

Beyond the guard, the kit's assertion tests check what differs by environment: Multi-AZ and deletion protection only in production, the WAF association, no public buckets, mandatory tags. Asserting "production differs from dev in exactly these ways" beats snapshotting a 136-resource template that changes on every CDK upgrade.

Keyless delivery through OIDC

Stored AWS keys in CI are a standing credential with no expiry and no context. GitHub's OIDC provider replaces them with a short-lived token per job, and the AWS role decides which tokens it accepts. That trust condition is the whole security model.

import { Duration, type Stack } from "aws-cdk-lib";
import { OidcProviderNative, PolicyStatement, Role, WebIdentityPrincipal } from "aws-cdk-lib/aws-iam";

const HOST = "token.actions.githubusercontent.com";
const AUDIENCE = "sts.amazonaws.com";

export const createDeployRole = (stack: Stack, repository: string, environment: string): Role => {
  const provider = new OidcProviderNative(stack, "GithubOidcProvider", { url: `https://${HOST}`, clientIds: [AUDIENCE] });
  const role = new Role(stack, "GithubDeployRole", {
    assumedBy: new WebIdentityPrincipal(provider.oidcProviderArn, {
      StringEquals: {
        [`${HOST}:aud`]: AUDIENCE,
        [`${HOST}:sub`]: `repo:${repository}:environment:${environment}`,
      },
    }),
    maxSessionDuration: Duration.hours(1),
  });
  const bootstrap = (name: string): string =>
    `arn:${stack.partition}:iam::${stack.account}:role/cdk-hnb659fds-${name}-${stack.account}-${stack.region}`;
  role.addToPolicy(new PolicyStatement({
    actions: ["sts:AssumeRole", "sts:TagSession"],
    resources: ["deploy-role", "file-publishing-role", "image-publishing-role", "lookup-role"].map(bootstrap),
  }));
  return role;
};

The sub condition uses StringEquals on the environment form, repo:<owner>/<repo>:environment:<name>. A wildcard such as repo:org/repo:* would let any branch, pull request or environment assume a role that can deploy production. Pinning to the environment means only a job that declared that GitHub environment, where reviewers and branch rules live, gets a usable token. GitHub's documentation also notes that repositories created after 15 July 2026, or opted in to immutable subject claims, emit a sub that includes owner and repository IDs, so check which format yours uses or the role will refuse every token.

Least privilege here is layered. The kit's deploy role can do almost nothing directly: assume the four CDK bootstrap roles, push to one ECR repository, and call ecr:GetAuthorizationToken, which only accepts * as its resource. A separate diff role trusts only pull_request tokens and can assume only the read-only lookup role, so a pull request can show a cdk diff but change nothing. Every role the kit creates carries a permissions boundary that denies identity escalation, audit tampering and regions outside the approved list, exempting global services through NotAction as in AWS's region-deny example. The real deployment power sits in the bootstrap's CloudFormation execution role, whose permissions decide what CloudFormation may do, so scope it at bootstrap time too.

The workflow side mirrors the trust policy:

# deploy.yml: production waits for staging, and the caller grants the token
  production:
    needs: staging
    uses: ./.github/workflows/deploy-environment.yml
    with: { stage: Prod, profile: prod, github-environment: production }
    permissions:
      contents: read
      id-token: write
---
# deploy-environment.yml: the job that declares the environment and assumes the role
permissions:
  contents: read
jobs:
  deploy:
    runs-on: ubuntu-24.04
    environment: ${{ inputs.github-environment }}
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
          role-session-name: deploy-${{ inputs.profile }}-${{ github.run_id }}
          aws-region: ap-southeast-3
      - run: npx cdk deploy "${{ inputs.stage }}/*" --require-approval never --progress events

Two details matter. A reusable workflow cannot grant itself more than its caller passes in, so id-token: write must appear on the calling job as well. And the role ARN comes from an environment-scoped variable, so each environment, in its own AWS account, points at its own role. Reviewers on the production environment are a GitHub setting rather than code, so the kit's checker guards what code can: it parses every workflow and fails on stored AWS keys, a credentials step without id-token: write and role-to-assume, non-read-only default permissions, unpinned actions, deploys reachable from pull request triggers, a production deploy without an environment or predecessor, and an image push before a Trivy scan. The kit documents one gap: actions are pinned to release tags, not commit SHAs, which should change before production use.

A static scorecard people will actually read

Policy output in a CI log is read by whoever broke the build and nobody else. Auditors, stakeholders and the next engineer need a view that needs no AWS access. The kit's synthesis pipeline writes a Zod-validated platform report and SVG diagrams, and a static React scorecard renders them: overview, architecture, every rule's outcome with each acknowledged finding and its reason, resources, SLO alarms, environment differences and a usage-based cost model. CI uploads the built scorecard as an artefact.

Because it reads synthesised templates, the scorecard shows declared intent, not live state: useful for review before anything exists, blind to a bucket someone created by hand. Its burn-rate alarm view follows the method in burn-rate alerting for AI services.

What policy as code cannot see

Synthesis-time checks are strong because they are narrow. The kit's threat model is explicit about what sits outside them, and these are the gaps we would close first in a real engagement.

Gap Example What complements it
Runtime data flows Tasks can reach any address on port 443 through NAT, so the application can send personal data to a SaaS API in another country Egress controls, an inventory of processors and data processing agreements; the guard cannot see request bodies
Resources outside the app A bucket created in the console, or by another tool Service control policies that deny unapproved regions organisation-wide; AWS Config rules for deployed state
Drift after deploy A security group rule edited by hand AWS Config and CloudFormation drift detection
Organisation scope The kit's guardrails are per account, with no SCPs An SCP using aws:RequestedRegion, applied to the organisational unit
Telemetry Personal data in logs or traces Redaction in code; the kit's logger and collector strip identifiers before export

The permissions boundary is the closest the kit gets to runtime enforcement, and it only bounds roles the kit creates. An SCP applies the same region deny to every principal in the account, including people with console access, which turns "the code says Jakarta" into "the account cannot do otherwise". Coarse rules in the organisation, fine-grained rules at synthesis: each covers what the other cannot.

FAQ

Why not rely on an SCP alone for residency?

An SCP rejects the API call during deployment, after the change has been reviewed and merged, and it judges one request at a time. The synthesis guard rejects the design before merge with a rule ID on the exact construct, and it understands relationships an SCP cannot, such as a backup copy pointing at another region or a CloudFront origin holding personal data. Use both.

Should an Aspect fix violations instead of failing?

For tags and similar defaults, a mutating aspect is fine. For residency, no: silently moving or dropping a resource hides a design mistake that someone needs to understand. The guard runs at read-only priority so it judges the final tree after any mutating aspects have run.

Checklist

  • Attach the residency guard to every stage, at read-only priority, and fail closed on resource type
  • Treat an unresolved region and an unverifiable copy destination as errors, not passes
  • Keep residency as unacknowledgeable errors; let hygiene rules be acknowledged only with written reasons
  • Fail the build when an acknowledgement no longer matches a finding
  • Enable @aws-cdk/core:annotationsInValidationReport so tests and the CLI fail the same way
  • Pin the OIDC sub to a repository and a protected environment with StringEquals, and check the claim format your repository emits
  • Grant id-token: write per job, on the caller of any reusable workflow too
  • Scope the CDK bootstrap execution role, not only the CI role
  • Add SCPs, AWS Config and egress controls for what synthesis cannot see

Primary references

The full platform, with its scorecard and runbooks, is in our Cloud Platform Kit case study, and our IT consulting service helps teams put guardrails like these into their own accounts.

Let’s connect the dots

What would this look like for your business?

Let's turn the right ideas into a clear next step.

Discuss your project