Skip to content

Commit 05692cb

Browse files
authored
fix: exclude token query string from logs (#188)
1 parent dbc75b1 commit 05692cb

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

src/monitoring/logger.ts

+16-4
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,27 @@
11
import pino from 'pino'
22
import { getConfig } from '../utils/config'
3+
import { FastifyRequest } from 'fastify'
4+
import { URL } from 'url'
35

46
const { logLevel } = getConfig()
57

68
export const logger = pino({
79
transport: buildTransport(),
810
formatters: {
9-
level(label, number) {
10-
return { level: number }
11+
level(label) {
12+
return { level: label }
1113
},
1214
},
1315
serializers: {
1416
res(reply) {
1517
return {
16-
url: reply.url,
1718
statusCode: reply.statusCode,
1819
}
1920
},
2021
req(request) {
2122
return {
2223
method: request.method,
23-
url: request.url,
24+
url: redactQueryParamFromRequest(request, ['token']),
2425
headers: whitelistHeaders(request.headers),
2526
hostname: request.hostname,
2627
remoteAddress: request.ip,
@@ -92,3 +93,14 @@ const whitelistHeaders = (headers: Record<string, unknown>) => {
9293

9394
return responseMetadata
9495
}
96+
97+
export function redactQueryParamFromRequest(req: FastifyRequest, params: string[]) {
98+
const lUrl = new URL(req.url, `${req.protocol}://${req.hostname}`)
99+
100+
params.forEach((param) => {
101+
if (lUrl.searchParams.has(param)) {
102+
lUrl.searchParams.set(param, 'redacted')
103+
}
104+
})
105+
return `${lUrl.pathname}${lUrl.search}`
106+
}

src/plugins/log-request.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import fastifyPlugin from 'fastify-plugin'
2+
import { redactQueryParamFromRequest } from '../monitoring'
23

34
interface RequestLoggerOptions {
45
excludeUrls?: string[]
@@ -12,7 +13,7 @@ export default (options: RequestLoggerOptions) =>
1213
}
1314

1415
const rMeth = req.method
15-
const rUrl = req.url
16+
const rUrl = redactQueryParamFromRequest(req, ['token'])
1617
const uAgent = req.headers['user-agent']
1718
const rId = req.id
1819
const cIP = req.ip

0 commit comments

Comments
 (0)