Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(iam): policies aren't minimized as far as possible #19764

Merged
merged 2 commits into from
Apr 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 23 additions & 16 deletions packages/@aws-cdk/aws-iam/lib/private/merge-statements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,33 @@ import { StatementSchema, normalizeStatement, IamValue } from './postprocess-pol
export function mergeStatements(statements: StatementSchema[]): StatementSchema[] {
const compStatements = statements.map(makeComparable);

let i = 0;
while (i < compStatements.length) {
let didMerge = false;

for (let j = i + 1; j < compStatements.length; j++) {
const merged = tryMerge(compStatements[i], compStatements[j]);
if (merged) {
compStatements[i] = merged;
compStatements.splice(j, 1);
didMerge = true;
break;
// Keep trying until nothing changes anymore
while (onePass()) { /* again */ }
return compStatements.map(renderComparable);

// Do one optimization pass, return 'true' if we merged anything
function onePass() {
let ret = false;
let i = 0;
while (i < compStatements.length) {
let didMerge = false;

for (let j = i + 1; j < compStatements.length; j++) {
const merged = tryMerge(compStatements[i], compStatements[j]);
if (merged) {
compStatements[i] = merged;
compStatements.splice(j, 1);
ret = didMerge = true;
break;
}
}
}

if (!didMerge) {
i++;
if (!didMerge) {
i++;
}
}
return ret;
}

return compStatements.map(renderComparable);
}

/**
Expand Down
30 changes: 30 additions & 0 deletions packages/@aws-cdk/aws-iam/test/merge-statements.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,36 @@ test('fail merging typed and untyped principals', () => {
]);
});

test('keep merging even if it requires multiple passes', () => {
// [A, R1], [B, R1], [A, R2], [B, R2]
// -> [{A, B}, R1], [{A, B], R2]
// -> [{A, B}, {R1, R2}]
assertMerged([
new iam.PolicyStatement({
actions: ['service:A'],
resources: ['R1'],
}),
new iam.PolicyStatement({
actions: ['service:B'],
resources: ['R1'],
}),
new iam.PolicyStatement({
actions: ['service:A'],
resources: ['R2'],
}),
new iam.PolicyStatement({
actions: ['service:B'],
resources: ['R2'],
}),
], [
{
Effect: 'Allow',
Action: ['service:A', 'service:B'],
Resource: ['R1', 'R2'],
},
]);
});

function assertNoMerge(statements: iam.PolicyStatement[]) {
const app = new App();
const stack = new Stack(app, 'Stack');
Expand Down