forked from IMAP-Science-Operations-Center/sds-data-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsds_api_manager_construct.py
More file actions
382 lines (348 loc) · 13 KB
/
Copy pathsds_api_manager_construct.py
File metadata and controls
382 lines (348 loc) · 13 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
"""Configure the SDS API Manager."""
import aws_cdk as cdk
from aws_cdk import aws_iam as iam
from aws_cdk import aws_lambda as lambda_
from aws_cdk import aws_secretsmanager as secrets
from constructs import Construct
from .api_gateway_construct import ApiGateway
def add_stable_route(api, base_path, http_method, lambda_function, prefix_list):
"""Add routes to handle variations in path formatting.
When the prefix of the route is passed in, any trailing '/' will be
removed and checked for a starting '/'. This ensures that each route
variation a user could call will result in a proper response.
The two main routes handled and registered are a normalized (/api/upload)
and a route with subpaths handled in proxy (/api/upload/{proxy+}).
Parameters
----------
api : obj
The APIGateway stack.
base_path : str
The base route path (e.g., "/upload").
http_method : str
The HTTP method to allow (e.g., "GET", "POST").
lambda_function : obj
The lambda function.
prefix_list : list[str]
List of route prefixes.
"""
# remove trailing backslash to circumvent error
for prefix in prefix_list:
clean = f"{prefix}{base_path}".rstrip("/")
# add a starting '/' if not present
if not clean.startswith("/"):
clean = "/" + clean
# the proxy route for subcommands
proxy = f"{clean}/{{proxy+}}"
# register both base (clean) and proxy routes
for path in [clean, proxy]:
api.add_route(
route=path,
http_method=http_method,
lambda_function=lambda_function,
)
class SdsApiManager(Construct):
"""Construct for API Management."""
def __init__(
self,
scope: Construct,
construct_id: str,
code: lambda_.Code,
api: ApiGateway,
env: cdk.Environment,
data_bucket,
vpc,
rds_security_group,
db_secret_name: str,
layers: list,
account_name: str,
**kwargs,
) -> None:
"""Initialize the SdsApiManagerConstruct.
Parameters
----------
scope : obj
Parent construct
construct_id : str
A unique string identifier for this construct
code : lambda_.Code
Lambda code bundle
api : obj
The APIGateway stack
env : obj
The CDK environment
data_bucket : obj
The data bucket
vpc : obj
The VPC
rds_security_group : obj
The RDS security group
db_secret_name : str
The DB secret name
layers : list
List of Lambda layers arns
account_name : str
The account name. Eg. 'prod' or 'dev'
kwargs : dict
Keyword arguments
"""
super().__init__(scope, construct_id, **kwargs)
s3_write_policy = iam.PolicyStatement(
effect=iam.Effect.ALLOW,
actions=["s3:PutObject"],
resources=[
f"{data_bucket.bucket_arn}/*",
],
)
s3_read_policy = iam.PolicyStatement(
effect=iam.Effect.ALLOW,
actions=["s3:GetObject"],
resources=[
f"{data_bucket.bucket_arn}/*",
],
)
# landing page redirect
landing_page_lambda = lambda_.Function(
self,
id="LandingPageLambda",
code=code,
handler="SDSCode.api_lambdas.landing_page_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
)
# Redirect root '/' to the landing page
api.add_route(
route="/",
http_method="GET",
lambda_function=landing_page_lambda,
)
# upload API lambda
upload_api_lambda = lambda_.Function(
self,
id="UploadAPILambda",
function_name="upload-api-handler",
code=code,
handler="SDSCode.api_lambdas.upload_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
timeout=cdk.Duration.minutes(1),
memory_size=1000,
allow_public_subnet=True,
vpc=vpc,
security_groups=[rds_security_group],
environment={
"S3_BUCKET": data_bucket.bucket_name,
"SECRET_NAME": db_secret_name,
"REGION": env.region,
},
layers=layers,
)
upload_api_lambda.add_to_role_policy(s3_write_policy)
upload_api_lambda.add_to_role_policy(s3_read_policy)
upload_api_lambda.apply_removal_policy(cdk.RemovalPolicy.DESTROY)
# basic route: /upload/{proxy+}
# oauth2 JWT authorizer: /authorized/upload/{proxy+}
# API key authorizer: /api-key/upload/{proxy+}
auth_route_prefixes = ["", "/authorized", "/api-key"]
# We need to restrict upload API on production. Production
# account only can allow upload through API key.
if account_name == "prod":
upload_route_prefixes = ["/api-key"]
else:
upload_route_prefixes = auth_route_prefixes
# {proxy+} is used to allow for any pathParams after /upload/
add_stable_route(
api, "/upload", "GET", upload_api_lambda, upload_route_prefixes
)
# query API lambda
query_api_lambda = lambda_.Function(
self,
id="QueryAPILambda",
function_name="query-api-handler",
code=code,
handler="SDSCode.api_lambdas.query_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
timeout=cdk.Duration.minutes(1),
memory_size=1000,
allow_public_subnet=True,
vpc=vpc,
security_groups=[rds_security_group],
environment={
"REGION": env.region,
"SECRET_NAME": db_secret_name,
"S3_BUCKET": data_bucket.bucket_name,
},
layers=layers,
)
# {proxy+} is used to allow for any pathParams after /query/
add_stable_route(api, "/query", "GET", query_api_lambda, auth_route_prefixes)
# SPICE query API lambda
spice_query_api_lambda = lambda_.Function(
self,
id="SPICEQueryAPILambda",
function_name="spice-query-api-handler",
code=code,
handler="SDSCode.api_lambdas.spice_query_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
timeout=cdk.Duration.minutes(5),
memory_size=1000,
allow_public_subnet=True,
vpc=vpc,
security_groups=[rds_security_group],
environment={
"REGION": env.region,
"SECRET_NAME": db_secret_name,
},
layers=layers,
)
for prefix in auth_route_prefixes:
api.add_route(
route=f"{prefix}/spice-query",
http_method="GET",
lambda_function=spice_query_api_lambda,
)
# SPICE metakernel API lambda
spice_metakernel_api_lambda = lambda_.Function(
self,
id="SPICEMetakernelAPILambda",
function_name="spice-metakernel-api-handler",
code=code,
handler="SDSCode.api_lambdas.spice_metakernel_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
timeout=cdk.Duration.minutes(5), # Reduce after issue #719 is done
memory_size=1000,
allow_public_subnet=True,
vpc=vpc,
security_groups=[rds_security_group],
environment={
"REGION": env.region,
"SECRET_NAME": db_secret_name,
},
layers=layers,
)
for prefix in auth_route_prefixes:
api.add_route(
route=f"{prefix}/metakernel",
http_method="GET",
lambda_function=spice_metakernel_api_lambda,
)
# download API lambda
download_api_lambda = lambda_.Function(
self,
id="DownloadAPILambda",
function_name="download-api-handler",
code=code,
handler="SDSCode.api_lambdas.download_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
allow_public_subnet=True,
vpc=vpc,
security_groups=[rds_security_group],
timeout=cdk.Duration.minutes(1),
environment={
"S3_BUCKET": data_bucket.bucket_name,
"REGION": env.region,
"SECRET_NAME": db_secret_name,
},
layers=layers,
)
download_api_lambda.add_to_role_policy(s3_read_policy)
# {proxy+} is used to allow for any pathParams after /download/
add_stable_route(
api, "/download", "GET", download_api_lambda, auth_route_prefixes
)
# NOTE: The frontend wants to be able to make a HEAD request to be able to
# get the result without needing to follow the redirect.
add_stable_route(
api, "/download", "HEAD", download_api_lambda, auth_route_prefixes
)
spin_repoint_query_api_lambda = lambda_.Function(
self,
id="spin-repoint-query-api",
function_name="spin-repoint-query-api",
code=code,
handler="SDSCode.api_lambdas.spin_repoint_table_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
timeout=cdk.Duration.minutes(1),
memory_size=1000,
allow_public_subnet=True,
vpc=vpc,
security_groups=[rds_security_group],
environment={
"SECRET_NAME": db_secret_name,
},
layers=layers,
)
# API to query batch job information
batch_job_query_api_lambda = lambda_.Function(
self,
id="BatchJobQueryAPILambda",
function_name="batch-job-query-api-handler",
code=code,
handler="SDSCode.api_lambdas.batch_job_query_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
timeout=cdk.Duration.minutes(1),
memory_size=1000,
allow_public_subnet=True,
vpc=vpc,
security_groups=[rds_security_group],
environment={
"SECRET_NAME": db_secret_name,
},
layers=layers,
)
for prefix in auth_route_prefixes:
# {proxy+} is used to allow for any pathParams after /processing-jobs/
api.add_route(
route=f"{prefix}/processing-jobs",
http_method="GET",
lambda_function=batch_job_query_api_lambda,
)
# API to query batch job logs
batch_logs_api_lambda = lambda_.Function(
self,
id="BatchLogsAPILambda",
function_name="batch-logs-api-handler",
code=code,
handler="SDSCode.api_lambdas.batch_logs_api.lambda_handler",
runtime=lambda_.Runtime.PYTHON_3_12,
timeout=cdk.Duration.minutes(1),
memory_size=1000,
allow_public_subnet=True,
layers=layers,
)
for prefix in auth_route_prefixes:
api.add_route(
# {id+} is used to allow for any pathParams after /batch-logs/
# This is needed because the log stream ID can contain slashes
route=f"{prefix}/processing-logs/{{id+}}",
http_method="GET",
lambda_function=batch_logs_api_lambda,
)
batch_logs_read_policy = iam.PolicyStatement(
effect=iam.Effect.ALLOW,
actions=["logs:GetLogEvents"],
resources=[
"arn:aws:logs:*:*:log-group:/aws/batch/*",
],
)
batch_logs_api_lambda.add_to_role_policy(batch_logs_read_policy)
rds_secret = secrets.Secret.from_secret_name_v2(
self, "rds_secret", db_secret_name
)
rds_secret.grant_read(grantee=spin_repoint_query_api_lambda)
rds_secret.grant_read(grantee=query_api_lambda)
rds_secret.grant_read(grantee=download_api_lambda)
rds_secret.grant_read(grantee=spice_query_api_lambda)
rds_secret.grant_read(grantee=spice_metakernel_api_lambda)
rds_secret.grant_read(grantee=upload_api_lambda)
rds_secret.grant_read(grantee=batch_job_query_api_lambda)
for prefix in auth_route_prefixes:
# Add spin table route
api.add_route(
route=f"{prefix}/spin-table",
http_method="GET",
lambda_function=spin_repoint_query_api_lambda,
)
# Same handler, but add a route to the repointing table
api.add_route(
route=f"{prefix}/repoint-table",
http_method="GET",
lambda_function=spin_repoint_query_api_lambda,
)