Reputation: 93
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?
Upvotes: 4
Views: 2072
Reputation: 11512
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.
Upvotes: 3