Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert resources do not have properties

Hi I was wondering if there was a recommended pattern for asserting that certain resources do not have properties in the CDK. For example if you're defining IAM policies and you would like to enforce no wildcards are defined in a test that uses the /assertions package in the CDK, what would the "proper" way to do this be? Make your own matcher based off Matcher.objectLike that does the inverse?

Sample IAM definition

// this would be fine
const secretsManagerReadAccess = new iam.PolicyStatement({
  actions: ["SecretsManager:GetSecretValue"],
  resources: ["arn:aws:secretsmanager:us-east-1:ACCOUNTID:secret:SECRET_NAME"],
});
// this should blow up in a test
const secretsManagerWildcardAccess = new iam.PolicyStatement({
  actions: ["SecretsManager:*"],
  resources: ["arn:aws:secretsmanager:us-east-1:ACCOUNTID:secret:*"],
});
// the worst possible, probably not written correctly but you get the idea
const everything = new iam.PolicyStatement({
  actions: ["*:*"],
  resources: ["arn:aws:*:us-east-1:ACCOUNTID:*:*"],
});

Edit: I guess what might be a better way to phrase this is, how would you black-list certain patterns within your CDK definitions?

like image 228
Dakota Lewallen Avatar asked Sep 01 '25 10:09

Dakota Lewallen


1 Answers

You can chain Matchers, and you can use Captures to construct pattern filters.

const actionCapture = new Capture();
template.hasResourceProperties(
  "AWS::IAM::Role",
  Match.not(Match.objectLike({
    PolicyDocument: {
      Statement: [
        {
          Action: actionCapture,
        },
      ],
    },
  }))
);
expect(actionCapture.asString()).toEqual(expect.not.stringContaining("*"));

For more examples, consult the Developer Guide.

like image 139
gshpychka Avatar answered Sep 04 '25 00:09

gshpychka