-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy paths3.service.ts
More file actions
401 lines (365 loc) · 10.3 KB
/
Copy paths3.service.ts
File metadata and controls
401 lines (365 loc) · 10.3 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
390
391
392
393
394
395
396
397
398
399
400
401
import {
CopyObjectCommand,
DeleteObjectCommand,
GetObjectTaggingCommand,
HeadObjectCommand,
S3Client,
Tag,
} from '@aws-sdk/client-s3'
import pino from 'pino'
import { retry } from 'ts-retry-promise'
import { config } from './config'
import {
DeleteS3FileParams,
GetS3FileStreamParams,
GUARD_DUTY_MALWARE_SCAN_TAG,
MoveS3FileParams,
} from './types'
/**
* ts-retry-promise wraps retried errors in its own RetryError, which exposes the
* original failure as `lastError`. We duck-type it (instead of `instanceof`)
* because the package's source/dist dual entry points make `instanceof` unsafe
* under ts-jest.
*/
const isRetryError = (err: unknown): err is { lastError: unknown } =>
!!err && typeof err === 'object' && 'lastError' in err
/**
* Thrown when a HeadObject succeeds but the object has no VersionId.
* Retried like any other transient failure, then surfaced to the caller.
*/
export class MissingS3VersionIdError extends Error {
constructor() {
super('VersionId is empty')
this.name = 'MissingS3VersionIdError'
Object.setPrototypeOf(this, MissingS3VersionIdError.prototype)
}
}
/**
* Thrown when a HeadObject reports ContentLength === 0. S3 has had strong
* read-after-write consistency since 2020, so a 0-byte HeadObject can never
* recover on retry — this error is therefore non-retryable and short-circuits
* immediately so callers can log and bail without wasted invocations.
*/
export class ZeroByteS3ObjectError extends Error {
constructor() {
super('S3 object is 0 bytes')
this.name = 'ZeroByteS3ObjectError'
Object.setPrototypeOf(this, ZeroByteS3ObjectError.prototype)
}
}
export class S3Service {
private readonly s3Client: S3Client
private readonly isDevelopmentEnv: boolean
constructor(
isDevelopmentEnv: boolean,
private readonly logger: pino.Logger,
) {
this.isDevelopmentEnv = isDevelopmentEnv
if (isDevelopmentEnv) {
this.s3Client = new S3Client({
region: 'ap-southeast-1',
endpoint: `http://host.docker.internal:4566`,
forcePathStyle: true,
credentials: {
accessKeyId: '',
secretAccessKey: '',
},
})
} else {
// lambda function should automatically pick configs at runtime in non-dev envs
this.s3Client = new S3Client({
region: 'ap-southeast-1',
})
}
}
async deleteS3File({ bucketName, objectKey, versionId }: DeleteS3FileParams) {
this.logger.info(
{
bucketName,
objectKey,
versionId,
},
'Deleting document from s3',
)
try {
await this.s3Client.send(
new DeleteObjectCommand({
Key: objectKey,
Bucket: bucketName,
VersionId: versionId,
}),
)
this.logger.info(
{
bucketName,
objectKey,
},
'Deleted document from s3',
)
} catch (err) {
this.logger.error(
{
bucketName,
objectKey,
err,
},
'Failed to delete object from s3',
)
throw err
}
}
async moveS3File({
sourceBucketName,
sourceObjectKey,
sourceObjectVersionId,
destinationBucketName,
destinationObjectKey,
}: MoveS3FileParams): Promise<string> {
this.logger.info(
{
sourceBucketName,
sourceObjectKey,
sourceObjectVersionId,
destinationBucketName,
destinationObjectKey,
},
'Moving document in s3',
)
try {
const { VersionId } = await this.s3Client.send(
new CopyObjectCommand({
Key: destinationObjectKey,
Bucket: destinationBucketName,
CopySource: `${sourceBucketName}/${sourceObjectKey}?versionId=${sourceObjectVersionId}`,
}),
)
if (!VersionId) {
this.logger.error(
{
sourceBucketName,
sourceObjectKey,
sourceObjectVersionId,
destinationBucketName,
destinationObjectKey,
},
'VersionId is empty after copying object in s3',
)
throw new Error('VersionId is empty')
}
await this.s3Client.send(
new DeleteObjectCommand({
Key: sourceObjectKey,
Bucket: sourceBucketName,
VersionId: sourceObjectVersionId,
}),
)
this.logger.info(
{
sourceBucketName,
sourceObjectKey,
sourceObjectVersionId,
destinationBucketName,
destinationObjectKey,
destinationVersionId: VersionId,
},
'Moved document in s3',
)
return VersionId
} catch (err) {
this.logger.error(
{
sourceBucketName,
sourceObjectKey,
sourceObjectVersionId,
destinationBucketName,
destinationObjectKey,
err,
},
'Failed to move object in s3',
)
throw err
}
}
async getS3ObjectScanTag({
bucketName,
objectKey,
}: GetS3FileStreamParams): Promise<Tag> {
this.logger.info('Checking for Malware Scan tag...', {
bucketName,
objectKey,
})
// Dev mode doesn't have GuardDuty scanning so, manually tag files as clean
if (this.isDevelopmentEnv) {
this.logger.info(
'Development environment detected, skipping GuardDuty scan',
{
bucketName,
objectKey,
},
)
return {
Key: GUARD_DUTY_MALWARE_SCAN_TAG,
Value: 'NO_THREATS_FOUND',
}
}
try {
const malwareScanTag = await retry(
async () => {
const { TagSet: tagSet } = await this.s3Client.send(
new GetObjectTaggingCommand({ Bucket: bucketName, Key: objectKey }),
)
const malwareScanningTag = tagSet?.find(
(t) => t.Key === GUARD_DUTY_MALWARE_SCAN_TAG,
)
if (!malwareScanningTag) {
this.logger.info('No Malware Scan tag found', {
bucketName,
objectKey,
})
throw Error('No Malware Scan tag found')
}
return malwareScanningTag
},
{
retries: 'INFINITELY',
timeout: config.guarddutyScanCheckTimeout,
delay: config.guarddutyScanCheckDelay,
backoff: 'LINEAR',
maxBackOff: config.guarddutyScanCheckMaxBackoff,
},
)
// return tag once found
this.logger.info(
`GuardDuty scan complete. Tags found for ${bucketName}/${objectKey}: ${malwareScanTag.Value}`,
)
return malwareScanTag
} catch (e) {
if (e instanceof Error && e.message.startsWith('Timeout')) {
this.logger.info('GuardDuty Malware Scan polling timed out', {
bucketName,
objectKey,
})
throw e
} else {
this.logger.error('Retry for retrieving malware scan tag failed', {
bucketName,
objectKey,
})
throw e
}
}
}
/**
* Gets the version ID metadata without loading file content into lambda memory.
* RATIONALE: This aims to reduce the memory usage and hence reduce the memory requirement for the lambda function, saving monetary cost.
* In the event that the object is empty, an error is thrown.
* @param params GetS3FileStreamParams
* @returns Promise<{ versionId: string }>
*/
async getS3ObjectVersionId({
bucketName,
objectKey,
}: GetS3FileStreamParams): Promise<string> {
const logMeta = {
action: 'getS3ObjectVersionId',
bucketName,
objectKey,
}
this.logger.info(
{
meta: {
...logMeta,
status: 'started',
},
},
'Getting object version ID from s3',
)
let attempt = 0
const logMissedAttempt = (err: unknown) => {
this.logger.warn(
{
meta: {
...logMeta,
status: 'missed',
attempt,
},
err,
},
'getS3ObjectVersionId attempt failed',
)
}
try {
// S3 may briefly return NotFound when strong consistency lags, so retry
// with 2s/4s/8s exponential backoff plus jitter before giving up.
return await retry(
async () => {
attempt++
let response
try {
response = await this.s3Client.send(
new HeadObjectCommand({
Key: objectKey,
Bucket: bucketName,
}),
)
} catch (err) {
logMissedAttempt(err)
throw err
}
const { VersionId: versionId, ContentLength } = response
if (!versionId) {
const err = new MissingS3VersionIdError()
logMissedAttempt(err)
throw err
}
if (!ContentLength || ContentLength === 0) {
const err = new ZeroByteS3ObjectError()
logMissedAttempt(err)
throw err
}
this.logger.info(
{
meta: {
...logMeta,
status: 'success',
attempt,
versionId,
contentLength: ContentLength,
},
},
'Retrieved object version ID from s3',
)
return versionId
},
{
retries: 3,
delay: 2000,
backoff: (attempt) =>
1000 * Math.pow(2, attempt) + Math.floor(Math.random() * 1000),
// A 0-byte HeadObject can never recover under S3 strong
// read-after-write consistency, so do not retry it. 404 and
// missing-VersionId still retry as before.
retryIf: (err) => !(err instanceof ZeroByteS3ObjectError),
},
)
} catch (err) {
// ts-retry-promise wraps retried errors in its RetryError (exposed via
// `lastError`); unwrap to the original cause so callers can branch on the
// typed error. The 0-byte case is never retried (see retryIf above) and
// surfaces unwrapped.
const cause = isRetryError(err) ? err.lastError : err
this.logger.error(
{
meta: {
...logMeta,
status: 'failed',
attempts: attempt,
},
err: cause,
},
'Failed to get object version ID from s3',
)
throw cause
}
}
}