diff --git a/packages/services/service-common/src/helpers.ts b/packages/services/service-common/src/helpers.ts index 9f7e858d0f..6dafa739f9 100644 --- a/packages/services/service-common/src/helpers.ts +++ b/packages/services/service-common/src/helpers.ts @@ -32,3 +32,7 @@ export function invariant( const value: string = provided ? `${prefix}: ${provided}` : prefix; throw new Error(value); } + +export function maskToken(token: string) { + return token.substring(0, 3) + '*'.repeat(token.length - 6) + token.substring(token.length - 3); +} diff --git a/packages/services/service-common/src/sentry.ts b/packages/services/service-common/src/sentry.ts index 83f0e38b24..10d7b9e9da 100644 --- a/packages/services/service-common/src/sentry.ts +++ b/packages/services/service-common/src/sentry.ts @@ -1,42 +1,46 @@ import type { FastifyInstance, FastifyPluginAsync } from 'fastify'; import fp from 'fastify-plugin'; import * as Sentry from '@sentry/node'; -import { cleanRequestId } from './helpers'; +import { cleanRequestId, maskToken } from './helpers'; const plugin: FastifyPluginAsync = async server => { server.decorateReply('sentry', null); server.setErrorHandler((err, req, reply) => { Sentry.withScope(scope => { - scope.setUser({ - ip_address: req.ip, - }); - + scope.setUser({ ip_address: req.ip }); const requestId = cleanRequestId(req.headers['x-request-id']); - + const tokenHeader = req.headers['x-api-token'] || req.headers.authorization; + const maskedToken = typeof tokenHeader === 'string' ? maskToken(tokenHeader) : null; if (requestId) { scope.setTag('request_id', requestId); } - const { referer } = req.headers; - if (referer) { scope.setTag('referer', referer); } - scope.setTag('path', req.raw.url); scope.setTag('method', req.raw.method); + if (maskedToken) { + scope.setTag('masked_token', maskedToken); + } req.log.error(err); Sentry.captureException(err); - req.log.warn('Replying with 500 Internal Server Error'); + if (err.code === 'FST_ERR_CRT_BODY_TOO_LARGE') { + req.log.warn('Payload too large'); + void reply.status(413).send({ + error: 413, + message: 'Payload Too Large', + }); + return; + } - void reply.status(500).send( - JSON.stringify({ - error: 500, - message: 'Internal Server Error', - }), - ); + req.log.warn('Replying with 500 Internal Server Error'); + void reply.status(500).send({ + error: 500, + message: 'Internal Server Error', + }); }); }); };