-
Notifications
You must be signed in to change notification settings - Fork 202
/
compileIamRole.js
718 lines (647 loc) · 23.4 KB
/
compileIamRole.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
'use strict';
const _ = require('lodash');
const BbPromise = require('bluebird');
const path = require('path');
const { isIntrinsic, translateLocalFunctionNames, trimAliasFromLambdaArn } = require('../../utils/aws');
const { getArnPartition } = require('../../utils/arn');
const logger = require('../../utils/logger');
function getTaskStates(states, stateMachineName) {
return _.flatMap(states, (state) => {
switch (state.Type) {
case 'Task': {
return [state];
}
case 'Parallel': {
const parallelStates = _.flatMap(state.Branches, branch => _.values(branch.States));
return getTaskStates(parallelStates, stateMachineName);
}
case 'Map': {
const mapStates = state.ItemProcessor ? state.ItemProcessor.States : state.Iterator.States;
const taskStates = getTaskStates(mapStates, stateMachineName);
if (state.ItemProcessor && state.ItemProcessor.ProcessorConfig
&& state.ItemProcessor.ProcessorConfig.Mode === 'DISTRIBUTED') {
taskStates.push({
Resource: 'arn:aws:states:::states:startExecution',
Mode: 'DISTRIBUTED',
StateMachineName: stateMachineName,
});
}
if (state.ItemReader) {
taskStates.push(state.ItemReader);
}
if (state.ResultWriter) {
taskStates.push(state.ResultWriter);
}
return taskStates;
}
default: {
return [];
}
}
});
}
function sqsQueueUrlToArn(serverless, queueUrl) {
const regex = /https:\/\/sqs.(.*).amazonaws.com\/(.*)\/(.*)/g;
const match = regex.exec(queueUrl);
if (match) {
const region = match[1];
const accountId = match[2];
const queueName = match[3];
const partition = getArnPartition(region);
return `arn:${partition}:sqs:${region}:${accountId}:${queueName}`;
}
if (isIntrinsic(queueUrl)) {
if (queueUrl.Ref) {
// most likely we'll see a { Ref: LogicalId }, which we need to map to
// { Fn::GetAtt: [ LogicalId, Arn ] } to get the ARN
return {
'Fn::GetAtt': [queueUrl.Ref, 'Arn'],
};
}
// in case of for example { Fn::ImportValue: sharedValueToImport }
// we need to use "*" as ARN
return '*';
}
logger.log(`Unable to parse SQS queue url [${queueUrl}]`);
return [];
}
function getSqsPermissions(serverless, state) {
if (_.has(state, 'Parameters.QueueUrl')
|| _.has(state, ['Parameters', 'QueueUrl.$'])) {
// if queue URL is provided by input, then need pervasive permissions (i.e. '*')
const queueArn = state.Parameters['QueueUrl.$']
? '*'
: sqsQueueUrlToArn(serverless, state.Parameters.QueueUrl);
return [{ action: 'sqs:SendMessage', resource: queueArn }];
}
logger.log('SQS task missing Parameters.QueueUrl or Parameters.QueueUrl.$');
return [];
}
function getSnsPermissions(serverless, state) {
if (_.has(state, 'Parameters.TopicArn')
|| _.has(state, ['Parameters', 'TopicArn.$'])) {
// if topic ARN is provided by input, then need pervasive permissions
const topicArn = state.Parameters['TopicArn.$'] ? '*' : state.Parameters.TopicArn;
return [{ action: 'sns:Publish', resource: topicArn }];
}
logger.log('SNS task missing Parameters.TopicArn or Parameters.TopicArn.$');
return [];
}
function getDynamoDBArn(tableName) {
if (isIntrinsic(tableName)) {
// most likely we'll see a { Ref: LogicalId }, which we need to map to
// { Fn::GetAtt: [ LogicalId, Arn ] } to get the ARN
if (tableName.Ref) {
return {
'Fn::GetAtt': [tableName.Ref, 'Arn'],
};
}
// but also support importing the table name from an external stack that exports it
// as we still want to support direct state machine actions interacting with those tables
if (tableName['Fn::ImportValue']) {
return {
'Fn::Join': [
':',
[
'arn',
{ Ref: 'AWS::Partition' },
'dynamodb',
{ Ref: 'AWS::Region' },
{ Ref: 'AWS::AccountId' },
{
'Fn::Join': [
'/',
[
'table',
tableName,
],
],
},
],
],
};
}
}
return {
'Fn::Join': [
':',
[
'arn',
{ Ref: 'AWS::Partition' },
'dynamodb',
{ Ref: 'AWS::Region' },
{ Ref: 'AWS::AccountId' },
`table/${tableName}`,
],
],
};
}
function getBatchPermissions() {
return [{
action: 'batch:SubmitJob,batch:DescribeJobs,batch:TerminateJob',
resource: '*',
}, {
action: 'events:PutTargets,events:PutRule,events:DescribeRule',
resource: {
'Fn::Join': [
':',
[
'arn',
{ Ref: 'AWS::Partition' },
'events',
{ Ref: 'AWS::Region' },
{ Ref: 'AWS::AccountId' },
'rule/StepFunctionsGetEventsForBatchJobsRule',
],
],
},
}];
}
function getGluePermissions() {
return [{
action: 'glue:StartJobRun,glue:GetJobRun,glue:GetJobRuns,glue:BatchStopJobRun',
resource: '*',
}];
}
function getEcsPermissions() {
return [{
action: 'ecs:RunTask,ecs:StopTask,ecs:DescribeTasks,iam:PassRole',
resource: '*',
}, {
action: 'events:PutTargets,events:PutRule,events:DescribeRule',
resource: {
'Fn::Join': [
':',
[
'arn',
{ Ref: 'AWS::Partition' },
'events',
{ Ref: 'AWS::Region' },
{ Ref: 'AWS::AccountId' },
'rule/StepFunctionsGetEventsForECSTaskRule',
],
],
},
}];
}
function getDynamoDBPermissions(action, state) {
let resource;
if (state.Parameters['TableName.$']) {
// When the TableName is only known at runtime, we
// have to provide * permissions during deployment.
resource = '*';
} else if (state.Parameters['IndexName.$'] || state.Parameters.IndexName) {
// When the Parameters contain an IndexName, we have to build a
// longer arn that includes the index.
const indexName = state.Parameters['IndexName.$']
// We must provide * here instead of state.Parameters['IndexName.$'], because we don't know
// which index will be targeted when we the step function runs
? '*'
: state.Parameters.IndexName;
resource = getDynamoDBArn(`${state.Parameters.TableName}/index/${indexName}`);
} else {
resource = getDynamoDBArn(state.Parameters.TableName);
}
return [{
action,
resource,
}];
}
function getBatchDynamoDBPermissions(action, state) {
if (state.Parameters['RequestItems.$']) {
// When the RequestItems object is only known at runtime,
// we have to provide * permissions during deployment.
return [{
action,
resource: '*',
}];
}
// If RequestItems is specified it must contain the target
// table names as keys. We can use these to generate roles
// whether the array of requests for that table is known
// at deploy time or not
const tableNames = Object.keys(state.Parameters.RequestItems);
return tableNames.map(tableName => ({
action,
resource: getDynamoDBArn(tableName.replace('.$', '')),
}));
}
function getRedshiftDataPermissions(action, state) {
if (['redshift-data:ExecuteStatement', 'redshift-data:BatchExecuteStatement'].includes(action)) {
const clusterName = _.has(state, 'Parameters.ClusterIdentifier') ? state.Parameters.ClusterIdentifier : '*';
const dbName = _.has(state, 'Parameters.Database') ? state.Parameters.Database : '*';
const dbUser = _.has(state, 'Parameters.DbUser') ? state.Parameters.DbUser : '*';
return [{
action,
resource: { 'Fn::Sub': `arn:\${AWS::Partition}:redshift:\${AWS::Region}:\${AWS::AccountId}:cluster:${clusterName}` },
}, {
action: 'redshift:GetClusterCredentials',
resource: [
{ 'Fn::Sub': `arn:\${AWS::Partition}:redshift:\${AWS::Region}:\${AWS::AccountId}:dbname:${clusterName}/${dbName}` },
{ 'Fn::Sub': `arn:\${AWS::Partition}:redshift:\${AWS::Region}:\${AWS::AccountId}:dbuser:${clusterName}/${dbUser}` },
],
}];
}
return [{
action,
resource: '*',
}];
}
function getLambdaPermissions(state) {
// function name can be name-only, name-only with alias, full arn or partial arn
// https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestParameters
const functionName = state.Parameters.FunctionName;
if (_.isString(functionName)) {
const segments = functionName.split(':');
let functionArns;
if (functionName.match(/^arn:aws(-[a-z]+)*:lambda/)) {
// full ARN
functionArns = [
functionName,
`${functionName}:*`,
];
} else if (segments.length === 3 && segments[0].match(/^\d+$/)) {
// partial ARN
functionArns = [
{ 'Fn::Sub': `arn:\${AWS::Partition}:lambda:\${AWS::Region}:${functionName}` },
{ 'Fn::Sub': `arn:\${AWS::Partition}:lambda:\${AWS::Region}:${functionName}:*` },
];
} else {
// name-only (with or without alias)
functionArns = [
{
'Fn::Sub': `arn:\${AWS::Partition}:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${functionName}`,
},
{
'Fn::Sub': `arn:\${AWS::Partition}:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${functionName}:*`,
},
];
}
return [{
action: 'lambda:InvokeFunction',
resource: functionArns,
}];
} if (_.has(functionName, 'Fn::GetAtt')) {
// because the FunctionName parameter can be either a name or ARN
// so you should be able to use Fn::GetAtt here to get the ARN
const functionArn = translateLocalFunctionNames.bind(this)(functionName);
return [{
action: 'lambda:InvokeFunction',
resource: [
functionArn,
{ 'Fn::Sub': ['${functionArn}:*', { functionArn }] },
],
}];
} if (_.has(functionName, 'Ref')) {
// because the FunctionName parameter can be either a name or ARN
// so you should be able to use Ref here to get the function name
const functionArn = translateLocalFunctionNames.bind(this)(functionName);
return [{
action: 'lambda:InvokeFunction',
resource: [
{
'Fn::Sub': [
'arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${functionArn}',
{ functionArn },
],
},
{
'Fn::Sub': [
'arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${functionArn}:*',
{ functionArn },
],
},
],
}];
}
if (state.Parameters['FunctionName.$']) {
return [{
action: 'lambda:InvokeFunction',
resource: state.Parameters.AllowedFunctions ? state.Parameters.AllowedFunctions : '*',
}];
}
// hope for the best...
return [{
action: 'lambda:InvokeFunction',
resource: functionName,
}];
}
function getStepFunctionsPermissions(state) {
let stateMachineArn = state.Mode === 'DISTRIBUTED' ? {
'Fn::Sub': [
`arn:aws:states:\${AWS::Region}:\${AWS::AccountId}:stateMachine:${state.StateMachineName}`,
{},
],
} : null;
if (!stateMachineArn) {
stateMachineArn = state.Parameters['StateMachineArn.$'] ? '*'
: state.Parameters.StateMachineArn;
}
return [{
action: 'states:StartExecution',
resource: stateMachineArn,
}, {
action: 'states:DescribeExecution,states:StopExecution',
// this is excessive but mirrors behaviour in the console
// also, DescribeExecution supports executions as resources but StopExecution
// doesn't support resources
resource: '*',
}, {
action: 'events:PutTargets,events:PutRule,events:DescribeRule',
resource: {
'Fn::Sub': [
'arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:rule/StepFunctionsGetEventsForStepFunctionsExecutionRule',
{},
],
},
}];
}
function getCodeBuildPermissions(state) {
const projectName = state.Parameters.ProjectName;
return [{
action: 'codebuild:StartBuild,codebuild:StopBuild,codebuild:BatchGetBuilds',
resource: {
'Fn::Sub': [
`arn:\${AWS::Partition}:codebuild:$\{AWS::Region}:$\{AWS::AccountId}:project/${projectName}`,
{},
],
},
}, {
action: 'events:PutTargets,events:PutRule,events:DescribeRule',
resource: {
'Fn::Sub': [
'arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:rule/StepFunctionsGetEventForCodeBuildStartBuildRule',
{},
],
},
}];
}
function getSageMakerPermissions(state) {
const transformJobName = state.Parameters.TransformJobName ? `${state.Parameters.TransformJobName}` : '';
return [
{
action: 'sagemaker:CreateTransformJob,sagemaker:DescribeTransformJob,sagemaker:StopTransformJob',
resource: {
'Fn::Sub': [
`arn:\${AWS::Partition}:sagemaker:$\{AWS::Region}:$\{AWS::AccountId}:transform-job/${transformJobName}*`,
{},
],
},
},
{
action: 'sagemaker:ListTags',
resource: '*',
},
{
action: 'events:PutTargets,events:PutRule,events:DescribeRule',
resource: {
'Fn::Sub': [
'arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:rule/StepFunctionsGetEventsForSageMakerTransformJobsRule',
{},
],
},
},
];
}
function getEventBridgePermissions(state) {
const eventBuses = new Set();
for (const entry of state.Parameters.Entries) {
eventBuses.add(entry.EventBusName || 'default');
}
return [
{
action: 'events:PutEvents',
resource: [...eventBuses].map(eventBus => ({
'Fn::Sub': [
'arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/${eventBus}',
{ eventBus },
],
})),
},
];
}
function getS3ObjectPermissions(action, state) {
const bucket = state.Parameters.Bucket || '*';
const key = state.Parameters.Key || '*';
const prefix = state.Parameters.Prefix;
let arn;
if (prefix) {
arn = `arn:aws:s3:::${bucket}/${prefix}/${key}`;
} else if (bucket === '*' && key === '*') {
arn = '*';
} else {
arn = `arn:aws:s3:::${bucket}/${key}`;
}
return [{
action,
resource: [
arn,
],
}];
}
// if there are multiple permissions with the same action, then collapsed them into one
// permission instead, and collect the resources into an array
function consolidatePermissionsByAction(permissions) {
return _.chain(permissions)
.groupBy(perm => perm.action)
.mapValues((perms) => {
// find the unique resources
let resources = _.uniqWith(_.flatMap(perms, p => p.resource), _.isEqual);
if (_.includes(resources, '*')) {
resources = '*';
}
return {
action: perms[0].action,
resource: resources,
};
})
.values()
.value(); // unchain
}
function consolidatePermissionsByResource(permissions) {
return _.chain(permissions)
.groupBy(p => JSON.stringify(p.resource))
.mapValues((perms) => {
// find unique actions
const actions = _.uniq(_.flatMap(perms, p => p.action.split(',')));
return {
action: actions.join(','),
resource: perms[0].resource,
};
})
.values()
.value(); // unchain
}
function getIamPermissions(taskStates) {
return _.flatMap(taskStates, (state) => {
const resourceName = typeof state.Resource === 'string' ? state.Resource.replace(/^arn:aws(-[a-z]+)*:/, 'arn:aws:') : state.Resource;
switch (resourceName) {
case 'arn:aws:states:::sqs:sendMessage':
case 'arn:aws:states:::sqs:sendMessage.waitForTaskToken':
return getSqsPermissions(this.serverless, state);
case 'arn:aws:states:::sns:publish':
case 'arn:aws:states:::sns:publish.waitForTaskToken':
return getSnsPermissions(this.serverless, state);
case 'arn:aws:states:::dynamodb:updateItem':
case 'arn:aws:states:::aws-sdk:dynamodb:updateItem':
case 'arn:aws:states:::aws-sdk:dynamodb:updateItem.waitForTaskToken':
return getDynamoDBPermissions('dynamodb:UpdateItem', state);
case 'arn:aws:states:::dynamodb:putItem':
case 'arn:aws:states:::aws-sdk:dynamodb:putItem':
case 'arn:aws:states:::aws-sdk:dynamodb:putItem.waitForTaskToken':
return getDynamoDBPermissions('dynamodb:PutItem', state);
case 'arn:aws:states:::dynamodb:getItem':
return getDynamoDBPermissions('dynamodb:GetItem', state);
case 'arn:aws:states:::dynamodb:deleteItem':
return getDynamoDBPermissions('dynamodb:DeleteItem', state);
case 'arn:aws:states:::aws-sdk:dynamodb:updateTable':
return getDynamoDBPermissions('dynamodb:UpdateTable', state);
case 'arn:aws:states:::aws-sdk:dynamodb:query':
return getDynamoDBPermissions('dynamodb:Query', state);
case 'arn:aws:states:::aws-sdk:dynamodb:batchGetItem':
return getBatchDynamoDBPermissions('dynamodb:BatchGetItem', state);
case 'arn:aws:states:::aws-sdk:dynamodb:batchWriteItem':
return getBatchDynamoDBPermissions('dynamodb:BatchWriteItem', state);
case 'arn:aws:states:::aws-sdk:redshiftdata:executeStatement':
return getRedshiftDataPermissions('redshift-data:ExecuteStatement', state);
case 'arn:aws:states:::aws-sdk:redshiftdata:batchExecuteStatement':
return getRedshiftDataPermissions('redshift-data:BatchExecuteStatement', state);
case 'arn:aws:states:::aws-sdk:redshiftdata:listStatements':
return getRedshiftDataPermissions('redshift-data:ListStatements', state);
case 'arn:aws:states:::aws-sdk:redshiftdata:describeStatement':
return getRedshiftDataPermissions('redshift-data:DescribeStatement', state);
case 'arn:aws:states:::aws-sdk:redshiftdata:getStatementResult':
return getRedshiftDataPermissions('redshift-data:GetStatementResult', state);
case 'arn:aws:states:::aws-sdk:redshiftdata:cancelStatement':
return getRedshiftDataPermissions('redshift-data:CancelStatement', state);
case 'arn:aws:states:::batch:submitJob.sync':
case 'arn:aws:states:::batch:submitJob':
return getBatchPermissions();
case 'arn:aws:states:::glue:startJobRun.sync':
case 'arn:aws:states:::glue:startJobRun':
return getGluePermissions();
case 'arn:aws:states:::ecs:runTask.sync':
case 'arn:aws:states:::ecs:runTask.waitForTaskToken':
case 'arn:aws:states:::ecs:runTask':
return getEcsPermissions();
case 'arn:aws:states:::lambda:invoke':
case 'arn:aws:states:::lambda:invoke.waitForTaskToken':
return getLambdaPermissions.bind(this)(state);
case 'arn:aws:states:::states:startExecution':
case 'arn:aws:states:::states:startExecution.sync':
case 'arn:aws:states:::states:startExecution.sync:2':
case 'arn:aws:states:::states:startExecution.waitForTaskToken':
return getStepFunctionsPermissions(state);
case 'arn:aws:states:::codebuild:startBuild':
case 'arn:aws:states:::codebuild:startBuild.sync':
return getCodeBuildPermissions(state);
case 'arn:aws:states:::sagemaker:createTransformJob.sync':
return getSageMakerPermissions(state);
case 'arn:aws:states:::events:putEvents':
case 'arn:aws:states:::events:putEvents.waitForTaskToken':
return getEventBridgePermissions(state);
case 'arn:aws:states:::s3:getObject':
case 'arn:aws:states:::aws-sdk:s3:getObject':
return getS3ObjectPermissions('s3:GetObject', state);
case 'arn:aws:states:::s3:putObject':
case 'arn:aws:states:::aws-sdk:s3:putObject':
return getS3ObjectPermissions('s3:PutObject', state);
default:
if (isIntrinsic(state.Resource) || !!state.Resource.match(/arn:aws(-[a-z]+)*:lambda/)) {
const trimmedArn = trimAliasFromLambdaArn(state.Resource);
const functionArn = translateLocalFunctionNames.bind(this)(trimmedArn);
return [{
action: 'lambda:InvokeFunction',
resource: [
functionArn,
{ 'Fn::Sub': ['${functionArn}:*', { functionArn }] },
],
}];
}
logger.log('Cannot generate IAM policy statement for Task state', state);
return [];
}
});
}
function getIamStatements(iamPermissions, stateMachineObj) {
// when the state machine doesn't define any Task states, and therefore doesn't need ANY
// permission, then we should follow the behaviour of the AWS console and return a policy
// that denies access to EVERYTHING
if (_.isEmpty(iamPermissions) && _.isEmpty(stateMachineObj.iamRoleStatements)) {
return [{
Effect: 'Deny',
Action: '*',
Resource: '*',
}];
}
const iamStatements = iamPermissions.map(p => ({
Effect: 'Allow',
Action: p.action.split(','),
Resource: p.resource,
}));
if (!_.isEmpty(stateMachineObj.iamRoleStatements)) {
iamStatements.push(...stateMachineObj.iamRoleStatements);
}
return iamStatements;
}
module.exports = {
compileIamRole() {
logger.config(this.serverless, this.v3Api);
const service = this.serverless.service;
const permissionsBoundary = service.provider.rolePermissionsBoundary;
this.getAllStateMachines().forEach((stateMachineId) => {
const stateMachineObj = this.getStateMachine(stateMachineId);
const stateMachineName = stateMachineObj.name || stateMachineId;
if (stateMachineObj.role) {
return;
}
if (!stateMachineObj.definition) {
throw new Error(`Missing "definition" for state machine ${stateMachineId}`);
}
const taskStates = getTaskStates(stateMachineObj.definition.States, stateMachineName);
let iamPermissions = getIamPermissions.bind(this)(taskStates);
if (stateMachineObj.loggingConfig) {
iamPermissions.push({
action: 'logs:CreateLogDelivery,logs:GetLogDelivery,logs:UpdateLogDelivery,logs:DeleteLogDelivery,logs:ListLogDeliveries,logs:PutResourcePolicy,logs:DescribeResourcePolicies,logs:DescribeLogGroups',
resource: '*',
});
}
if (stateMachineObj.tracingConfig) {
iamPermissions.push({
action: 'xray:PutTraceSegments,xray:PutTelemetryRecords,xray:GetSamplingRules,xray:GetSamplingTargets',
resource: '*',
});
}
iamPermissions = consolidatePermissionsByAction(iamPermissions);
iamPermissions = consolidatePermissionsByResource(iamPermissions);
const iamStatements = getIamStatements(iamPermissions, stateMachineObj);
const iamRoleStateMachineExecutionTemplate = this.serverless.utils.readFileSync(
path.join(__dirname,
'..',
'..',
'iam-role-statemachine-execution-template.txt'),
);
let iamRoleJson = iamRoleStateMachineExecutionTemplate
.replace('[PolicyName]', this.getStateMachinePolicyName())
.replace('[Statements]', JSON.stringify(iamStatements));
if (permissionsBoundary) {
const jsonIamRole = JSON.parse(iamRoleJson);
jsonIamRole.Properties.PermissionsBoundary = permissionsBoundary;
iamRoleJson = JSON.stringify(jsonIamRole);
}
const stateMachineLogicalId = this.getStateMachineLogicalId(
stateMachineId,
stateMachineObj,
);
const iamRoleStateMachineLogicalId = `${stateMachineLogicalId}Role`;
const newIamRoleStateMachineExecutionObject = {
[iamRoleStateMachineLogicalId]: JSON.parse(iamRoleJson),
};
_.merge(
this.serverless.service.provider.compiledCloudFormationTemplate.Resources,
newIamRoleStateMachineExecutionObject,
);
});
return BbPromise.resolve();
},
};