Skip to content

Commit

Permalink
fix: correctly parse SendGrid callback payload for verification
Browse files Browse the repository at this point in the history
SendGrid requires the payload to be parsed in text, byte for byte.
Since we parse the payload as JSON using `bodyParser.json()`, we
unintentionally strip away the whitespace characters and mess up the
encoding.

Fix the payload and parse it correctly before verifying the callback.
  • Loading branch information
zwliew committed Apr 15, 2021
1 parent afb6a9a commit 201d0f4
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion backend/src/email/utils/callback/parsers/sendgrid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,19 @@ type SendgridRecord = {
'smtp-id': string
timestamp: number
}

function stringifyPayload(payload: SendgridEvent): string {
return `[${payload.map((event) => JSON.stringify(event)).join(',\r\n')}]\r\n`
}

const isEvent = (req: Request): boolean => {
const signature = req.get(SIGNATURE_HEADER)
const timestamp = req.get(TIMESTAMP_HEADER)
if (!(signature && timestamp && req.body)) {
return false
}
const decodedSignature = Signature.fromBase64(signature)
const timestampPayload = timestamp + req.body
const timestampPayload = timestamp + stringifyPayload(req.body)
if (!Ecdsa.verify(timestampPayload, decodedSignature, PUBLIC_KEY)) {
throw new Error('Invalid record')
}
Expand Down

0 comments on commit 201d0f4

Please sign in to comment.