Skip to content

Commit 4e050c3

Browse files
authoredOct 5, 2018
feat: Manage IAM permissions for (some) CFN CodePipeline actions (#843)
When adding CloudFormation actions to CodePipeline, the pipeline's role must be granted appropriate permissions on the CloudFormation stacks in order for the pipeline to work. This adds the relevant permission management to the ChangeSet actions (`CreateReplaceChangeSet`, `ExecuteChangeSet`). A bonus BREAKING CHANGE is that the `Artifact.subartifact` method of the CodePipeline API was renamed to `Artifact.atPath`.
1 parent bebfef0 commit 4e050c3

10 files changed

+427
-17
lines changed
 

Diff for: ‎packages/@aws-cdk/aws-cloudformation/lib/pipeline-actions.ts

+31
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,11 @@ export class PipelineExecuteChangeSetAction extends PipelineCloudFormationAction
8888
ActionMode: 'CHANGE_SET_EXECUTE',
8989
ChangeSetName: props.changeSetName,
9090
});
91+
92+
props.stage.pipelineRole.addToPolicy(new cdk.PolicyStatement()
93+
.addAction('cloudformation:ExecuteChangeSet')
94+
.addResource(stackArnFromName(props.stackName))
95+
.addCondition('StringEquals', { 'cloudformation:ChangeSetName': props.changeSetName }));
9196
}
9297
}
9398

@@ -243,6 +248,24 @@ export class PipelineCreateReplaceChangeSetAction extends PipelineCloudFormation
243248
});
244249

245250
this.addInputArtifact(props.templatePath.artifact);
251+
if (props.templateConfiguration && props.templateConfiguration.artifact.name !== props.templatePath.artifact.name) {
252+
this.addInputArtifact(props.templateConfiguration.artifact);
253+
}
254+
255+
const stackArn = stackArnFromName(props.stackName);
256+
// Allow the pipeline to check for Stack & ChangeSet existence
257+
props.stage.pipelineRole.addToPolicy(new cdk.PolicyStatement()
258+
.addAction('cloudformation:DescribeStacks')
259+
.addResource(stackArn));
260+
// Allow the pipeline to create & delete the specified ChangeSet
261+
props.stage.pipelineRole.addToPolicy(new cdk.PolicyStatement()
262+
.addActions('cloudformation:CreateChangeSet', 'cloudformation:DeleteChangeSet', 'cloudformation:DescribeChangeSet')
263+
.addResource(stackArn)
264+
.addCondition('StringEquals', { 'cloudformation:ChangeSetName': props.changeSetName }));
265+
// Allow the pipeline to pass this actions' role to CloudFormation
266+
props.stage.pipelineRole.addToPolicy(new cdk.PolicyStatement()
267+
.addAction('iam:PassRole')
268+
.addResource(this.role.roleArn));
246269
}
247270
}
248271

@@ -337,3 +360,11 @@ export enum CloudFormationCapabilities {
337360
*/
338361
NamedIAM = 'CAPABILITY_NAMED_IAM'
339362
}
363+
364+
function stackArnFromName(stackName: string): string {
365+
return cdk.ArnUtils.fromComponents({
366+
service: 'cloudformation',
367+
resource: 'stack',
368+
resourceName: `${stackName}/*`
369+
});
370+
}

Diff for: ‎packages/@aws-cdk/aws-cloudformation/package-lock.json

+14-3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: ‎packages/@aws-cdk/aws-cloudformation/package.json

+2
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,11 @@
5757
"license": "Apache-2.0",
5858
"devDependencies": {
5959
"@aws-cdk/assert": "^0.10.0",
60+
"@types/lodash": "^4.14.116",
6061
"cdk-build-tools": "^0.10.0",
6162
"cdk-integ-tools": "^0.10.0",
6263
"cfn2ts": "^0.10.0",
64+
"lodash": "^4.17.11",
6365
"pkglint": "^0.10.0"
6466
},
6567
"dependencies": {

Diff for: ‎packages/@aws-cdk/aws-cloudformation/test/test.cloudformation.ts

-8
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
import cpapi = require('@aws-cdk/aws-codepipeline-api');
2+
import iam = require('@aws-cdk/aws-iam');
3+
import cdk = require('@aws-cdk/cdk');
4+
import _ = require('lodash');
5+
import nodeunit = require('nodeunit');
6+
import cloudformation = require('../lib');
7+
8+
export = nodeunit.testCase({
9+
CreateReplaceChangeSet: {
10+
works(test: nodeunit.Test) {
11+
const stack = new cdk.Stack();
12+
const pipelineRole = new RoleDouble(stack, 'PipelineRole');
13+
const stage = new StageDouble({ pipelineRole });
14+
const artifact = new cpapi.Artifact(stack as any, 'TestArtifact');
15+
const action = new cloudformation.PipelineCreateReplaceChangeSetAction(stack, 'Action', {
16+
stage,
17+
changeSetName: 'MyChangeSet',
18+
stackName: 'MyStack',
19+
templatePath: artifact.atPath('path/to/file')
20+
});
21+
22+
_assertPermissionGranted(test, pipelineRole.statements, 'iam:PassRole', action.role.roleArn);
23+
24+
const stackArn = cdk.ArnUtils.fromComponents({
25+
service: 'cloudformation',
26+
resource: 'stack',
27+
resourceName: 'MyStack/*'
28+
});
29+
const changeSetCondition = { StringEquals: { 'cloudformation:ChangeSetName': 'MyChangeSet' } };
30+
_assertPermissionGranted(test, pipelineRole.statements, 'cloudformation:DescribeStacks', stackArn);
31+
_assertPermissionGranted(test, pipelineRole.statements, 'cloudformation:DescribeChangeSet', stackArn, changeSetCondition);
32+
_assertPermissionGranted(test, pipelineRole.statements, 'cloudformation:CreateChangeSet', stackArn, changeSetCondition);
33+
_assertPermissionGranted(test, pipelineRole.statements, 'cloudformation:DeleteChangeSet', stackArn, changeSetCondition);
34+
35+
test.deepEqual(action.inputArtifacts, [artifact],
36+
'The inputArtifact was correctly registered');
37+
38+
_assertActionMatches(test, stage.actions, 'AWS', 'CloudFormation', 'Deploy', {
39+
ActionMode: 'CHANGE_SET_CREATE_REPLACE',
40+
StackName: 'MyStack',
41+
ChangeSetName: 'MyChangeSet'
42+
});
43+
44+
test.done();
45+
}
46+
},
47+
ExecuteChangeSet: {
48+
works(test: nodeunit.Test) {
49+
const stack = new cdk.Stack();
50+
const pipelineRole = new RoleDouble(stack, 'PipelineRole');
51+
const stage = new StageDouble({ pipelineRole });
52+
new cloudformation.PipelineExecuteChangeSetAction(stack, 'Action', {
53+
stage,
54+
changeSetName: 'MyChangeSet',
55+
stackName: 'MyStack',
56+
});
57+
58+
const stackArn = cdk.ArnUtils.fromComponents({
59+
service: 'cloudformation',
60+
resource: 'stack',
61+
resourceName: 'MyStack/*'
62+
});
63+
_assertPermissionGranted(test, pipelineRole.statements, 'cloudformation:ExecuteChangeSet', stackArn,
64+
{ StringEquals: { 'cloudformation:ChangeSetName': 'MyChangeSet' } });
65+
66+
_assertActionMatches(test, stage.actions, 'AWS', 'CloudFormation', 'Deploy', {
67+
ActionMode: 'CHANGE_SET_EXECUTE',
68+
StackName: 'MyStack',
69+
ChangeSetName: 'MyChangeSet'
70+
});
71+
72+
test.done();
73+
}
74+
}
75+
});
76+
77+
interface PolicyStatementJson {
78+
Effect: 'Allow' | 'Deny';
79+
Action: string | string[];
80+
Resource: string | string[];
81+
Condition: any;
82+
}
83+
84+
function _assertActionMatches(test: nodeunit.Test,
85+
actions: cpapi.Action[],
86+
owner: string,
87+
provider: string,
88+
category: string,
89+
configuration?: { [key: string]: any }) {
90+
const configurationStr = configuration
91+
? `configuration including ${JSON.stringify(cdk.resolve(configuration), null, 2)}`
92+
: '';
93+
const actionsStr = JSON.stringify(actions.map(a =>
94+
({ owner: a.owner, provider: a.provider, category: a.category, configuration: cdk.resolve(a.configuration) })
95+
), null, 2);
96+
test.ok(_hasAction(actions, owner, provider, category, configuration),
97+
`Expected to find an action with owner ${owner}, provider ${provider}, category ${category}${configurationStr}, but found ${actionsStr}`);
98+
}
99+
100+
function _hasAction(actions: cpapi.Action[], owner: string, provider: string, category: string, configuration?: { [key: string]: any}) {
101+
for (const action of actions) {
102+
if (action.owner !== owner) { continue; }
103+
if (action.provider !== provider) { continue; }
104+
if (action.category !== category) { continue; }
105+
if (configuration && !action.configuration) { continue; }
106+
if (configuration) {
107+
for (const key of Object.keys(configuration)) {
108+
if (!_.isEqual(cdk.resolve(action.configuration[key]), cdk.resolve(configuration[key]))) {
109+
continue;
110+
}
111+
}
112+
}
113+
return true;
114+
}
115+
return false;
116+
}
117+
118+
function _assertPermissionGranted(test: nodeunit.Test, statements: PolicyStatementJson[], action: string, resource: string, conditions?: any) {
119+
const conditionStr = conditions
120+
? ` with condition(s) ${JSON.stringify(cdk.resolve(conditions))}`
121+
: '';
122+
const statementsStr = JSON.stringify(cdk.resolve(statements), null, 2);
123+
test.ok(_grantsPermission(statements, action, resource, conditions),
124+
`Expected to find a statement granting ${action} on ${cdk.resolve(resource)}${conditionStr}, found:\n${statementsStr}`);
125+
}
126+
127+
function _grantsPermission(statements: PolicyStatementJson[], action: string, resource: string, conditions?: any) {
128+
for (const statement of statements.filter(s => s.Effect === 'Allow')) {
129+
if (!_isOrContains(statement.Action, action)) { continue; }
130+
if (!_isOrContains(statement.Resource, resource)) { continue; }
131+
if (conditions && !_isOrContains(statement.Condition, conditions)) { continue; }
132+
return true;
133+
}
134+
return false;
135+
}
136+
137+
function _isOrContains(entity: string | string[], value: string): boolean {
138+
const resolvedValue = cdk.resolve(value);
139+
const resolvedEntity = cdk.resolve(entity);
140+
if (_.isEqual(resolvedEntity, resolvedValue)) { return true; }
141+
if (!Array.isArray(resolvedEntity)) { return false; }
142+
for (const tested of entity) {
143+
if (_.isEqual(tested, resolvedValue)) { return true; }
144+
}
145+
return false;
146+
}
147+
148+
class StageDouble implements cpapi.IStage {
149+
public readonly name: string;
150+
public readonly pipelineArn: string;
151+
public readonly pipelineRole: iam.Role;
152+
153+
public readonly actions = new Array<cpapi.Action>();
154+
155+
constructor({ name, pipelineName, pipelineRole }: { name?: string, pipelineName?: string, pipelineRole: iam.Role }) {
156+
this.name = name || 'TestStage';
157+
this.pipelineArn = cdk.ArnUtils.fromComponents({ service: 'codepipeline', resource: 'pipeline', resourceName: pipelineName || 'TestPipeline' });
158+
this.pipelineRole = pipelineRole;
159+
}
160+
161+
public grantPipelineBucketReadWrite() {
162+
throw new Error('Unsupported');
163+
}
164+
165+
public _attachAction(action: cpapi.Action) {
166+
this.actions.push(action);
167+
}
168+
}
169+
170+
class RoleDouble extends iam.Role {
171+
public readonly statements = new Array<PolicyStatementJson>();
172+
173+
constructor(parent: cdk.Construct, id: string, props: iam.RoleProps = { assumedBy: new cdk.ServicePrincipal('test') }) {
174+
super(parent, id, props);
175+
}
176+
177+
public addToPolicy(statement: cdk.PolicyStatement) {
178+
super.addToPolicy(statement);
179+
this.statements.push(statement.toJson());
180+
}
181+
}

Diff for: ‎packages/@aws-cdk/aws-codepipeline-api/lib/artifact.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export class Artifact extends Construct {
1414
* Output is in the form "<artifact-name>::<file-name>"
1515
* @param fileName The name of the file
1616
*/
17-
public subartifact(fileName: string) {
17+
public atPath(fileName: string) {
1818
return new ArtifactPath(this, fileName);
1919
}
2020

0 commit comments

Comments
 (0)