|
| 1 | +import { S3 } from "@webiny/aws-sdk/client-s3"; |
| 2 | +import { createEventBridgeEventHandler } from "@webiny/handler-aws"; |
| 3 | +import { createHandlerOnRequest } from "@webiny/handler"; |
| 4 | +import { GuardDutyEvent, ThreatDetectionContext } from "./types"; |
| 5 | +import { processThreatScanResult } from "./processThreatScanResult"; |
| 6 | +import { S3AssetMetadataReader } from "~/assetDelivery/s3/S3AssetMetadataReader"; |
| 7 | +import { EventBridgeEvent } from "@webiny/aws-sdk/types"; |
| 8 | + |
| 9 | +const detailType = "GuardDuty Malware Protection Object Scan Result"; |
| 10 | + |
| 11 | +const bucket = process.env.S3_BUCKET as string; |
| 12 | +const region = process.env.AWS_REGION as string; |
| 13 | + |
| 14 | +export const createThreatDetectionEventHandler = () => { |
| 15 | + const s3 = new S3({ region }); |
| 16 | + |
| 17 | + const handlerOnRequest = createHandlerOnRequest(async request => { |
| 18 | + const payload = request.body as EventBridgeEvent<string, GuardDutyEvent>; |
| 19 | + |
| 20 | + if (payload["detail-type"] !== detailType) { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + const objectKey = payload.detail.s3ObjectDetails.objectKey; |
| 25 | + if (objectKey.endsWith(".metadata")) { |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + try { |
| 30 | + const s3Metadata = new S3AssetMetadataReader(s3, bucket); |
| 31 | + const metadata = await s3Metadata.getMetadata(payload.detail.s3ObjectDetails.objectKey); |
| 32 | + |
| 33 | + request.headers = { |
| 34 | + ...request.headers, |
| 35 | + "x-tenant": metadata.tenant, |
| 36 | + "x-i18n-locale": `default:${metadata.locale};content:${metadata.locale};` |
| 37 | + }; |
| 38 | + } catch { |
| 39 | + // If metadata can't be loaded, we ignore the file. |
| 40 | + // Most likely it's because the file is a rendition of the original file, |
| 41 | + // so we don't need to do anything with it. |
| 42 | + } |
| 43 | + }); |
| 44 | + // Guard Duty event handler. |
| 45 | + const threatScanEventHandler = createEventBridgeEventHandler<typeof detailType, GuardDutyEvent>( |
| 46 | + async ({ payload, next, ...rest }) => { |
| 47 | + const context = rest.context as ThreatDetectionContext; |
| 48 | + |
| 49 | + const threatDetectionEnabled = context.wcp.canUseFileManagerThreatDetection(); |
| 50 | + |
| 51 | + if (!threatDetectionEnabled || payload["detail-type"] !== detailType) { |
| 52 | + return next(); |
| 53 | + } |
| 54 | + |
| 55 | + await processThreatScanResult(context, payload.detail); |
| 56 | + } |
| 57 | + ); |
| 58 | + |
| 59 | + // Assign a human-readable name for easier debugging. |
| 60 | + threatScanEventHandler.name = threatScanEventHandler.type + ".threatDetectionEventHandler"; |
| 61 | + |
| 62 | + return [handlerOnRequest, threatScanEventHandler]; |
| 63 | +}; |
0 commit comments