-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRestApiGateway.test.ts
More file actions
389 lines (343 loc) · 12.1 KB
/
RestApiGateway.test.ts
File metadata and controls
389 lines (343 loc) · 12.1 KB
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
import {App, Stack} from "aws-cdk-lib"
import {Template, Match} from "aws-cdk-lib/assertions"
import {ManagedPolicy, PolicyStatement} from "aws-cdk-lib/aws-iam"
import {
describe,
test,
beforeAll,
expect
} from "vitest"
import {RestApiGateway} from "../../src/constructs/RestApiGateway.js"
describe("RestApiGateway without mTLS", () => {
let stack: Stack
let app: App
let template: Template
beforeAll(() => {
app = new App()
stack = new Stack(app, "RestApiGatewayStack")
const testPolicy = new ManagedPolicy(stack, "TestPolicy", {
description: "test execution policy",
statements: [
new PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: ["arn:aws:lambda:eu-west-2:123456789012:function:test-function"]
})
]
})
const apiGateway = new RestApiGateway(stack, "TestApiGateway", {
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: undefined,
forwardCsocLogs: false,
csocApiGatewayDestination: "",
executionPolicies: [testPolicy],
enableServiceDomain: true
})
// Add a dummy method to satisfy API Gateway validation
apiGateway.api.root.addMethod("GET")
template = Template.fromStack(stack)
})
test("creates CloudWatch log group with correct properties", () => {
template.hasResourceProperties("AWS::Logs::LogGroup", {
LogGroupName: "/aws/apigateway/test-stack-apigw",
KmsKeyId: {"Fn::ImportValue": "account-resources:CloudwatchLogsKmsKeyArn"},
RetentionInDays: 30
})
})
test("creates Splunk subscription filter", () => {
template.hasResourceProperties("AWS::Logs::SubscriptionFilter", {
FilterPattern: "",
RoleArn: {"Fn::ImportValue": "lambda-resources:SplunkSubscriptionFilterRole"},
DestinationArn: {"Fn::ImportValue": "lambda-resources:SplunkDeliveryStream"}
})
})
test("does not create CSOC subscription filter", () => {
const filters = template.findResources("AWS::Logs::SubscriptionFilter")
const filterCount = Object.keys(filters).length
expect(filterCount).toBe(1)
})
test("creates ACM certificate", () => {
template.hasResourceProperties("AWS::CertificateManager::Certificate", {
DomainName: {
"Fn::Join": ["", [
"test-stack.",
{"Fn::ImportValue": "eps-route53-resources:EPS-domain"}
]]
},
DomainValidationOptions: [{
DomainName: {
"Fn::Join": ["", [
"test-stack.",
{"Fn::ImportValue": "eps-route53-resources:EPS-domain"}
]]
},
HostedZoneId: {"Fn::ImportValue": "eps-route53-resources:EPS-ZoneID"}
}],
ValidationMethod: "DNS"
})
})
test("creates REST API Gateway with correct configuration", () => {
template.hasResourceProperties("AWS::ApiGateway::RestApi", {
Name: "test-stack-apigw",
EndpointConfiguration: {
Types: ["REGIONAL"]
},
DisableExecuteApiEndpoint: false
})
})
test("creates API Gateway domain name with TLS 1.2", () => {
template.hasResourceProperties("AWS::ApiGateway::DomainName", {
DomainName: {
"Fn::Join": ["", [
"test-stack.",
{"Fn::ImportValue": "eps-route53-resources:EPS-domain"}
]]
},
EndpointConfiguration: {
Types: ["REGIONAL"]
},
SecurityPolicy: "TLS_1_2"
})
})
test("creates deployment with logging and metrics enabled", () => {
template.hasResourceProperties("AWS::ApiGateway::Stage", {
MethodSettings: [{
LoggingLevel: "INFO",
MetricsEnabled: true,
DataTraceEnabled: false,
HttpMethod: "*",
ResourcePath: "/*"
}],
AccessLogSetting: Match.objectLike({
Format: Match.stringLikeRegexp("requestId")
})
})
})
test("creates IAM role for API Gateway execution", () => {
template.hasResourceProperties("AWS::IAM::Role", {
AssumeRolePolicyDocument: {
Statement: [{
Action: "sts:AssumeRole",
Effect: "Allow",
Principal: {
Service: "apigateway.amazonaws.com"
}
}],
Version: "2012-10-17"
}
})
})
test("creates Route53 A record", () => {
template.hasResourceProperties("AWS::Route53::RecordSet", {
Name: {
"Fn::Join": ["", [
"test-stack.",
{"Fn::ImportValue": "eps-route53-resources:EPS-domain"},
"."
]]
},
Type: "A"
})
})
test("sets guard metadata on stage", () => {
const stages = template.findResources("AWS::ApiGateway::Stage")
const stageKeys = Object.keys(stages)
expect(stageKeys.length).toBeGreaterThan(0)
const stage = stages[stageKeys[0]]
expect(stage.Metadata).toBeDefined()
expect(stage.Metadata.guard).toBeDefined()
expect(stage.Metadata.guard.SuppressedRules).toContain("API_GW_CACHE_ENABLED_AND_ENCRYPTED")
})
})
describe("RestApiGateway with CSOC logs", () => {
let stack: Stack
let app: App
let template: Template
beforeAll(() => {
app = new App()
stack = new Stack(app, "RestApiGatewayStack")
const testPolicy = new ManagedPolicy(stack, "TestPolicy", {
description: "test execution policy",
statements: [
new PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: ["arn:aws:lambda:eu-west-2:123456789012:function:test-function"]
})
]
})
const apiGateway = new RestApiGateway(stack, "TestApiGateway", {
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: undefined,
forwardCsocLogs: true,
csocApiGatewayDestination: "arn:aws:logs:eu-west-2:123456789012:destination:csoc-destination",
executionPolicies: [testPolicy],
enableServiceDomain: true
})
// Add a dummy method to satisfy API Gateway validation
apiGateway.api.root.addMethod("GET")
template = Template.fromStack(stack)
})
test("creates both Splunk and CSOC subscription filters", () => {
const filters = template.findResources("AWS::Logs::SubscriptionFilter")
const filterCount = Object.keys(filters).length
expect(filterCount).toBe(2)
})
test("creates CSOC subscription filter with correct destination", () => {
template.hasResourceProperties("AWS::Logs::SubscriptionFilter", {
FilterPattern: "",
DestinationArn: "arn:aws:logs:eu-west-2:123456789012:destination:csoc-destination"
})
})
})
describe("RestApiGateway with mTLS", () => {
let stack: Stack
let app: App
let template: Template
beforeAll(() => {
app = new App()
stack = new Stack(app, "RestApiGatewayStack")
const testPolicy = new ManagedPolicy(stack, "TestPolicy", {
description: "test execution policy",
statements: [
new PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: ["arn:aws:lambda:eu-west-2:123456789012:function:test-function"]
})
]
})
const apiGateway = new RestApiGateway(stack, "TestApiGateway", {
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: "truststore.pem",
forwardCsocLogs: false,
csocApiGatewayDestination: "",
executionPolicies: [testPolicy],
enableServiceDomain: true
})
// Add a dummy method to satisfy API Gateway validation
apiGateway.api.root.addMethod("GET")
template = Template.fromStack(stack)
})
test("creates trust store deployment log group", () => {
template.hasResourceProperties("AWS::Logs::LogGroup", {
LogGroupName: "/aws/lambda/test-stack-truststore-deployment",
KmsKeyId: {"Fn::ImportValue": "account-resources:CloudwatchLogsKmsKeyArn"},
RetentionInDays: 30
})
})
test("creates trust store deployment policy with S3 permissions", () => {
interface PolicyResource {
Properties?: {
PolicyDocument?: {
Statement?: Array<{Action?: Array<string>}>
}
}
}
interface Statement {
Action?: Array<string>
}
const policies = template.findResources("AWS::IAM::ManagedPolicy")
const trustStorePolicy = Object.values(policies).find((p: PolicyResource) =>
p.Properties?.PolicyDocument?.Statement?.some((s: Statement) =>
s.Action?.includes("s3:ListBucket")
)
) as PolicyResource
expect(trustStorePolicy).toBeDefined()
const statements = trustStorePolicy.Properties?.PolicyDocument?.Statement ?? []
expect(statements.some((s: Statement) => s.Action?.includes("s3:ListBucket"))).toBe(true)
expect(statements.some((s: Statement) => s.Action?.includes("s3:GetObject"))).toBe(true)
expect(statements.some((s: Statement) => s.Action?.includes("kms:Decrypt"))).toBe(true)
expect(statements.some((s: Statement) => s.Action?.includes("logs:CreateLogStream"))).toBe(true)
})
test("creates trust store deployment role", () => {
template.hasResourceProperties("AWS::IAM::Role", {
AssumeRolePolicyDocument: {
Statement: Match.arrayWith([
Match.objectLike({
Action: "sts:AssumeRole",
Effect: "Allow",
Principal: {
Service: "lambda.amazonaws.com"
}
})
]),
Version: "2012-10-17"
}
})
})
test("creates bucket deployment custom resource", () => {
const customResources = template.findResources("Custom::CDKBucketDeployment")
expect(Object.keys(customResources).length).toBeGreaterThan(0)
})
test("disables execute-api endpoint when mTLS is enabled", () => {
template.hasResourceProperties("AWS::ApiGateway::RestApi", {
Name: "test-stack-apigw",
DisableExecuteApiEndpoint: true
})
})
test("configures mTLS on domain name", () => {
interface DomainNameResource {
Properties: {
MutualTlsAuthentication: {
TruststoreUri: unknown
}
}
}
const domainNames = template.findResources("AWS::ApiGateway::DomainName")
const domainName = Object.values(domainNames)[0] as DomainNameResource
expect(domainName.Properties.MutualTlsAuthentication).toBeDefined()
expect(domainName.Properties.MutualTlsAuthentication.TruststoreUri).toBeDefined()
})
})
describe("RestApiGateway validation errors", () => {
test("throws when forwardCsocLogs is true and csocApiGatewayDestination is empty string", () => {
const app = new App()
const stack = new Stack(app, "ValidationStack1")
const testPolicy = new ManagedPolicy(stack, "TestPolicy", {
description: "test execution policy",
statements: [
new PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: ["arn:aws:lambda:eu-west-2:123456789012:function:test-function"]
})
]
})
expect(() => new RestApiGateway(stack, "TestApiGateway", {
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: undefined,
forwardCsocLogs: true,
csocApiGatewayDestination: "",
executionPolicies: [testPolicy]
})).toThrow("csocApiGatewayDestination must be provided when forwardCsocLogs is true")
})
})
describe("RestApiGateway enableServiceDomain default behaviour", () => {
test("creates custom domain resources when enableServiceDomain is omitted", () => {
const app = new App()
const stack = new Stack(app, "EnableServiceDomainDefaultStack")
const testPolicy = new ManagedPolicy(stack, "TestPolicy", {
description: "test execution policy",
statements: [
new PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: ["arn:aws:lambda:eu-west-2:123456789012:function:test-function"]
})
]
})
const apiGateway = new RestApiGateway(stack, "TestApiGateway", {
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: undefined,
forwardCsocLogs: false,
csocApiGatewayDestination: "",
executionPolicies: [testPolicy]
})
apiGateway.api.root.addMethod("GET")
const template = Template.fromStack(stack)
template.resourceCountIs("AWS::CertificateManager::Certificate", 1)
template.resourceCountIs("AWS::ApiGateway::DomainName", 1)
template.resourceCountIs("AWS::Route53::RecordSet", 2)
})
})