-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
application-security-check.ts
184 lines (169 loc) · 6.78 KB
/
application-security-check.ts
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
import * as path from 'path';
import * as codebuild from '@aws-cdk/aws-codebuild';
import * as cp from '@aws-cdk/aws-codepipeline';
import * as iam from '@aws-cdk/aws-iam';
import * as lambda from '@aws-cdk/aws-lambda';
import { Duration, Tags } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { CDKP_DEFAULT_CODEBUILD_IMAGE } from './default-codebuild-image';
/**
* Properties for an ApplicationSecurityCheck
*/
export interface ApplicationSecurityCheckProps {
/**
* The pipeline that will be automatically approved
*
* Will have a tag added to it.
*/
readonly codePipeline: cp.Pipeline;
}
/**
* A construct containing both the Lambda and CodeBuild Project
* needed to conduct a security check on any given application stage.
*
* The Lambda acts as an auto approving mechanism that should only be
* triggered when the CodeBuild Project registers no security changes.
*
* The CodeBuild Project runs a security diff on the application stage,
* and exports the link to the console of the project.
*/
export class ApplicationSecurityCheck extends Construct {
/**
* A lambda function that approves a Manual Approval Action, given
* the following payload:
*
* {
* "PipelineName": [CodePipelineName],
* "StageName": [CodePipelineStageName],
* "ActionName": [ManualApprovalActionName]
* }
*/
public readonly preApproveLambda: lambda.Function;
/**
* A CodeBuild Project that runs a security diff on the application stage.
*
* - If the diff registers no security changes, CodeBuild will invoke the
* pre-approval lambda and approve the ManualApprovalAction.
* - If changes are detected, CodeBuild will exit into a ManualApprovalAction
*/
public readonly cdkDiffProject: codebuild.Project;
constructor(scope: Construct, id: string, props: ApplicationSecurityCheckProps) {
super(scope, id);
Tags.of(props.codePipeline).add('SECURITY_CHECK', 'ALLOW_APPROVE', {
includeResourceTypes: ['AWS::CodePipeline::Pipeline'],
});
this.preApproveLambda = new lambda.Function(this, 'CDKPipelinesAutoApprove', {
handler: 'index.handler',
runtime: lambda.Runtime.NODEJS_14_X,
code: lambda.Code.fromAsset(path.resolve(__dirname, 'approve-lambda')),
timeout: Duration.minutes(5),
});
this.preApproveLambda.addToRolePolicy(new iam.PolicyStatement({
actions: ['codepipeline:GetPipelineState', 'codepipeline:PutApprovalResult'],
conditions: {
StringEquals: {
'aws:ResourceTag/SECURITY_CHECK': 'ALLOW_APPROVE',
},
},
resources: ['*'],
}));
const invokeLambda =
'aws lambda invoke' +
` --function-name ${this.preApproveLambda.functionName}` +
' --invocation-type Event' +
' --cli-binary-format raw-in-base64-out' +
' --payload "$payload"' +
' lambda.out';
const message = [
'An upcoming change would broaden security changes in $PIPELINE_NAME.',
'Review and approve the changes in CodePipeline to proceed with the deployment.',
'',
'Review the changes in CodeBuild:',
'',
'$LINK',
'',
'Approve the changes in CodePipeline (stage $STAGE_NAME, action $ACTION_NAME):',
'',
'$PIPELINE_LINK',
];
const publishNotification =
'aws sns publish' +
' --topic-arn $NOTIFICATION_ARN' +
' --subject "$NOTIFICATION_SUBJECT"' +
` --message "${message.join('\n')}"`;
this.cdkDiffProject = new codebuild.Project(this, 'CDKSecurityCheck', {
environment: {
buildImage: CDKP_DEFAULT_CODEBUILD_IMAGE,
},
buildSpec: codebuild.BuildSpec.fromObject({
version: 0.2,
phases: {
build: {
commands: [
'npm install -g aws-cdk',
// $CODEBUILD_INITIATOR will always be Code Pipeline and in the form of:
// "codepipeline/example-pipeline-name-Xxx"
'export PIPELINE_NAME="$(node -pe \'`${process.env.CODEBUILD_INITIATOR}`.split("/")[1]\')"',
'payload="$(node -pe \'JSON.stringify({ "PipelineName": process.env.PIPELINE_NAME, "StageName": process.env.STAGE_NAME, "ActionName": process.env.ACTION_NAME })\' )"',
// ARN: "arn:aws:codebuild:$region:$account_id:build/$project_name:$project_execution_id$"
'ARN=$CODEBUILD_BUILD_ARN',
'REGION="$(node -pe \'`${process.env.ARN}`.split(":")[3]\')"',
'ACCOUNT_ID="$(node -pe \'`${process.env.ARN}`.split(":")[4]\')"',
'PROJECT_NAME="$(node -pe \'`${process.env.ARN}`.split(":")[5].split("/")[1]\')"',
'PROJECT_ID="$(node -pe \'`${process.env.ARN}`.split(":")[6]\')"',
// Manual Approval adds 'http/https' to the resolved link
'export LINK="https://$REGION.console.aws.amazon.com/codesuite/codebuild/$ACCOUNT_ID/projects/$PROJECT_NAME/build/$PROJECT_NAME:$PROJECT_ID/?region=$REGION"',
'export PIPELINE_LINK="https://$REGION.console.aws.amazon.com/codesuite/codepipeline/pipelines/$PIPELINE_NAME/view?region=$REGION"',
// Run invoke only if cdk diff passes (returns exit code 0)
// 0 -> true, 1 -> false
ifElse({
condition: 'cdk diff -a . --security-only --fail $STAGE_PATH/\\*',
thenStatements: [
invokeLambda,
'export MESSAGE="No security-impacting changes detected."',
],
elseStatements: [
`[ -z "\${NOTIFICATION_ARN}" ] || ${publishNotification}`,
'export MESSAGE="Deployment would make security-impacting changes. Click the link below to inspect them, then click Approve if all changes are expected."',
],
}),
],
},
},
env: {
'exported-variables': [
'LINK',
'MESSAGE',
],
},
}),
});
// this is needed to check the status the stacks when doing `cdk diff`
this.cdkDiffProject.addToRolePolicy(new iam.PolicyStatement({
actions: ['sts:AssumeRole'],
resources: ['*'],
conditions: {
'ForAnyValue:StringEquals': {
'iam:ResourceTag/aws-cdk:bootstrap-role': ['deploy'],
},
},
}));
this.preApproveLambda.grantInvoke(this.cdkDiffProject);
}
}
interface ifElseOptions {
readonly condition: string,
readonly thenStatements: string[],
readonly elseStatements?: string[]
}
const ifElse = ({ condition, thenStatements, elseStatements }: ifElseOptions): string => {
let statement = thenStatements.reduce((acc, ifTrue) => {
return `${acc} ${ifTrue};`;
}, `if ${condition}; then`);
if (elseStatements) {
statement = elseStatements.reduce((acc, ifFalse) => {
return `${acc} ${ifFalse};`;
}, `${statement} else`);
}
return `${statement} fi`;
};