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

feat(iam): avoid duplicate statements in policy documents #2254

Merged
merged 9 commits into from
Apr 16, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -191,20 +191,6 @@
}
]
},
{
"Action": [
"codebuild:BatchGetBuilds",
"codebuild:StartBuild",
"codebuild:StopBuild"
],
"Effect": "Allow",
"Resource": {
"Fn::GetAtt": [
"MyBuildProject30DB9D6E",
"Arn"
]
}
},
{
"Action": [
"codebuild:BatchGetBuilds",
Expand Down Expand Up @@ -531,39 +517,6 @@
}
]
},
{
"Action": [
"s3:GetObject*",
"s3:GetBucket*",
"s3:List*",
"s3:DeleteObject*",
"s3:PutObject*",
"s3:Abort*"
],
"Effect": "Allow",
"Resource": [
{
"Fn::GetAtt": [
"MyBucketF68F3FF0",
"Arn"
]
},
{
"Fn::Join": [
"",
[
{
"Fn::GetAtt": [
"MyBucketF68F3FF0",
"Arn"
]
},
"/*"
]
]
}
]
},
{
"Action": [
"s3:GetObject*",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,20 +278,6 @@
]
}
},
{
"Action": [
"codebuild:BatchGetBuilds",
"codebuild:StartBuild",
"codebuild:StopBuild"
],
"Effect": "Allow",
"Resource": {
"Fn::GetAtt": [
"MyBuildProject30DB9D6E",
"Arn"
]
}
},
{
"Action": [
"codebuild:BatchGetBuilds",
Expand Down
31 changes: 26 additions & 5 deletions packages/@aws-cdk/aws-iam/lib/policy-document.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import cdk = require('@aws-cdk/cdk');
import { Default, RegionInfo } from '@aws-cdk/region-info';
import crypto = require('crypto');
import { IPrincipal } from './principals';
import { mergePrincipal } from './util';

Expand All @@ -11,7 +12,7 @@ export class PolicyDocument extends cdk.Token {
* @param defaultDocument An IAM policy document to use as an initial
* policy. All statements of this document will be copied in.
*/
constructor(private readonly baseDocument?: any) {
constructor(private readonly baseDocument: any = {}) {
super();
}

Expand All @@ -20,10 +21,20 @@ export class PolicyDocument extends cdk.Token {
return undefined;
}

const doc = this.baseDocument || { };
doc.Statement = doc.Statement || [ ];
doc.Version = doc.Version || '2012-10-17';
doc.Statement = doc.Statement.concat(this.statements);
const doc = {
...this.baseDocument,
Statement: this.baseDocument.Statement || [],
Version: this.baseDocument.Version || '2012-10-17'
};

const hashes: string[] = [];
for (const statement of this.statements) {
if (!hashes.includes(statement.hash)) {
doc.Statement.push(statement);
}
hashes.push(statement.hash);
}

return doc;
}

Expand Down Expand Up @@ -517,6 +528,16 @@ export class PolicyStatement extends cdk.Token {
return result;
}
}

/**
* The hash of this statement. Used to avoid duplicates.
*/
public get hash(): string {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the idea of having a hash for a statement, but this is actually not necessary for comparison purposes (JSON.stringify(this.toJson()) is sufficient). Opinions?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is IAM, which is sensitive, so I am definitely not comfortable with the idea of making a hash-comparison, because in the improbable cause of a collision, it'll have awkward consequences.

I am however not sure that JSON.stringify will work though, as there can be any amount of unresolved Tokens here that may or may not be represented by the same string.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am however not sure that JSON.stringify will work though, as there can be any amount of unresolved Tokens here that may or may not be represented by the same string.

If this is the case then the comparison will fail and it will leave the statements as is, which is suboptimal but safe?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC, toJson will throw in this case...

return crypto
.createHash('sha256')
.update(JSON.stringify(this.toJson()))
.digest('hex');
}
}

export enum PolicyStatementEffect {
Expand Down
83 changes: 68 additions & 15 deletions packages/@aws-cdk/aws-iam/test/test.policy-document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,23 +219,51 @@ export = {
test.done();
},

'the { AWS: "*" } principal is represented as `Anyone` or `AnyPrincipal`'(test: Test) {
const stack = new Stack();
const p = new PolicyDocument();
'{ AWS: "*" } principal': {
'is represented as `Anyone`'(test: Test) {
const stack = new Stack();
const p = new PolicyDocument();

p.addStatement(new PolicyStatement().addPrincipal(new Anyone()));
p.addStatement(new PolicyStatement().addPrincipal(new AnyPrincipal()));
p.addStatement(new PolicyStatement().addAnyPrincipal());
p.addStatement(new PolicyStatement().addPrincipal(new Anyone()));

test.deepEqual(stack.node.resolve(p), {
Statement: [
{ Effect: 'Allow', Principal: '*' },
{ Effect: 'Allow', Principal: '*' },
{ Effect: 'Allow', Principal: '*' }
],
Version: '2012-10-17'
});
test.done();
test.deepEqual(stack.node.resolve(p), {
Statement: [
{ Effect: 'Allow', Principal: '*' }
],
Version: '2012-10-17'
});
test.done();
},

'is represented as `AnyPrincipal`'(test: Test) {
const stack = new Stack();
const p = new PolicyDocument();

p.addStatement(new PolicyStatement().addPrincipal(new AnyPrincipal()));

test.deepEqual(stack.node.resolve(p), {
Statement: [
{ Effect: 'Allow', Principal: '*' }
],
Version: '2012-10-17'
});
test.done();
},

'is represented as `addAnyPrincipal`'(test: Test) {
const stack = new Stack();
const p = new PolicyDocument();

p.addStatement(new PolicyStatement().addAnyPrincipal());

test.deepEqual(stack.node.resolve(p), {
Statement: [
{ Effect: 'Allow', Principal: '*' }
],
Version: '2012-10-17'
});
test.done();
}
},

'addAwsPrincipal/addArnPrincipal are the aliases'(test: Test) {
Expand Down Expand Up @@ -425,4 +453,29 @@ export = {
test.done();
}
},

'duplicate statements'(test: Test) {
const stack = new Stack();
const p = new PolicyDocument();

const statement = new PolicyStatement()
.addResources('resource1', 'resource2')
.addActions('action1', 'action2')
.addServicePrincipal('service')
.addConditions({
a: {
b: 'c'
},
d: {
e: 'f'
}
});

p.addStatement(statement);
p.addStatement(statement);
p.addStatement(statement);

test.equal(stack.node.resolve(p).Statement.length, 1);
test.done();
}
};
18 changes: 8 additions & 10 deletions packages/@aws-cdk/aws-lambda/lib/log-retention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,14 @@ export class LogRetention extends cdk.Construct {
lambdaPurpose: 'LogRetention',
});

if (provider.role && !provider.role.node.tryFindChild('DefaultPolicy')) { // Avoid duplicate statements
provider.role.addToPolicy(
new iam.PolicyStatement()
.addActions('logs:PutRetentionPolicy', 'logs:DeleteRetentionPolicy')
// We need '*' here because we will also put a retention policy on
// the log group of the provider function. Referencing it's name
// creates a CF circular dependency.
.addAllResources()
);
}
provider.addToRolePolicy(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a note here that duplicate statements will be deduplicated by PolicyDocument

new iam.PolicyStatement()
.addActions('logs:PutRetentionPolicy', 'logs:DeleteRetentionPolicy')
// We need '*' here because we will also put a retention policy on
// the log group of the provider function. Referencing it's name
// creates a CF circular dependency.
.addAllResources()
);

// Need to use a CfnResource here to prevent lerna dependency cycles
// @aws-cdk/aws-cloudformation -> @aws-cdk/aws-lambda -> @aws-cdk/aws-cloudformation
Expand Down