Improve log data sanitization (#14671)

* Improve log data sanitization

Extract the log sanitizer into its own module, match field names regardless of case and separators, extend the filtered fields, sanitize Sentry extras as a whole, keep serializable values such as dates, and apply the depth limit only to nested objects.

* Call toJSON once when sanitizing log data
This commit is contained in:
Tom Moor authored and GitHub committed 2026-11-19 17:59:44 -05:00
1 parent d18cf8fffc
commit 620ef924a1
3 files changed
+281 -54

No files matched your search

+8 -54
View File
@@ -1,12 +1,13 @@
/* oxlint-disable no-console */
import type { IncomingMessage } from "node:http";
import { styleText } from "node:util";
import { isArray, isEmpty, isObject } from "es-toolkit/compat";
import { isEmpty } from "es-toolkit/compat";
import winston from "winston";
import env from "@server/env";
import Metrics from "@server/logging/Metrics";
import Sentry from "@server/logging/sentry";
import { ShutdownHelper } from "@server/utils/ShutdownHelper";
import { sanitize } from "./sanitize";
import * as Tracing from "./tracer";
type LogCategory =
@@ -142,8 +143,9 @@ class Logger {
sentry.withScope((scope) => {
scope.setLevel("error");
for (const key in extra) {
scope.setExtra(key, this.sanitize(extra[key]));
const sanitizedExtra = this.sanitize(extra);
for (const key in sanitizedExtra) {
scope.setExtra(key, sanitizedExtra[key]);
}
if (request) {
@@ -187,61 +189,13 @@ class Logger {
* @param input The data to sanitize
* @returns The sanitized data
*/
private sanitize = <T>(input: T, level = 0): T => {
// Errors have non-enumerable message/stack which are dropped by spreads
// and JSON serialization, so convert them to a plain object up-front.
if (input instanceof Error) {
return {
name: input.name,
message: input.message,
stack: input.stack,
} as unknown as T;
}
private sanitize = <T>(input: T): T => {
// Short circuit if we're not in production to enable easier debugging
if (!env.isProduction) {
if (!env.isProduction && !(input instanceof Error)) {
return input;
}
const sensitiveFields = [
"accessToken",
"refreshToken",
"token",
"password",
"content",
];
if (level > 3) {
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
return "[…]" as any as T;
}
if (isArray(input)) {
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
return input.map((item) => this.sanitize(item, level + 1)) as any as T;
}
if (isObject(input)) {
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
const output: Record<string, any> = { ...input };
for (const key of Object.keys(output)) {
if (sensitiveFields.includes(key)) {
output[key] = "[Filtered]";
} else if (isObject(output[key])) {
output[key] = this.sanitize(output[key], level + 1);
} else if (isArray(output[key])) {
output[key] = output[key].map((value: unknown) =>
this.sanitize(value, level + 1)
);
} else {
output[key] = this.sanitize(output[key], level + 1);
}
}
return output as T;
}
return input;
return sanitize(input);
};
}
+180
View File
@@ -0,0 +1,180 @@
import { sanitize } from "./sanitize";
describe("sanitize", () => {
it("should return primitives unchanged", () => {
expect(sanitize("text")).toEqual("text");
expect(sanitize(42)).toEqual(42);
expect(sanitize(true)).toEqual(true);
expect(sanitize(null)).toEqual(null);
expect(sanitize(undefined)).toEqual(undefined);
});
it("should filter sensitive fields", () => {
expect(
sanitize({
id: "123",
accessToken: "a",
refreshToken: "b",
token: "c",
password: "d",
content: "e",
verificationCode: "f",
deleteConfirmationCode: "g",
})
).toEqual({
id: "123",
accessToken: "[Filtered]",
refreshToken: "[Filtered]",
token: "[Filtered]",
password: "[Filtered]",
content: "[Filtered]",
verificationCode: "[Filtered]",
deleteConfirmationCode: "[Filtered]",
});
});
it("should filter additional sensitive fields", () => {
expect(sanitize({ apiKey: "a", secret: "b", authorization: "c" })).toEqual({
apiKey: "[Filtered]",
secret: "[Filtered]",
authorization: "[Filtered]",
});
});
it("should match sensitive fields regardless of case and separators", () => {
expect(
sanitize({
access_token: "a",
"refresh-token": "b",
AccessToken: "c",
API_KEY: "d",
Authorization: "e",
PASSWORD: "f",
})
).toEqual({
access_token: "[Filtered]",
"refresh-token": "[Filtered]",
AccessToken: "[Filtered]",
API_KEY: "[Filtered]",
Authorization: "[Filtered]",
PASSWORD: "[Filtered]",
});
});
it("should not filter fields that only contain a sensitive name", () => {
expect(sanitize({ tokenId: "a", contentType: "b", apiKeyId: "c" })).toEqual(
{ tokenId: "a", contentType: "b", apiKeyId: "c" }
);
});
it("should filter sensitive fields that have object values", () => {
expect(sanitize({ content: { type: "doc" } })).toEqual({
content: "[Filtered]",
});
});
it("should filter sensitive fields in nested objects", () => {
expect(
sanitize({ props: { to: "user@example.com", token: "secret" } })
).toEqual({ props: { to: "user@example.com", token: "[Filtered]" } });
});
it("should filter sensitive fields in arrays", () => {
expect(sanitize([{ token: "a" }, { id: "1" }])).toEqual([
{ token: "[Filtered]" },
{ id: "1" },
]);
expect(sanitize({ items: [{ password: "a" }] })).toEqual({
items: [{ password: "[Filtered]" }],
});
});
it("should not mutate the input", () => {
const input = { token: "a", nested: { password: "b" } };
sanitize(input);
expect(input).toEqual({ token: "a", nested: { password: "b" } });
});
it("should convert errors to plain objects", () => {
const error = new Error("Failed");
expect(sanitize(error)).toEqual({
name: "Error",
message: "Failed",
stack: error.stack,
});
});
it("should convert nested errors to plain objects", () => {
const error = new Error("Failed");
expect(sanitize({ error })).toEqual({
error: { name: "Error", message: "Failed", stack: error.stack },
});
});
it("should keep dates", () => {
const date = new Date("2026-01-01T00:00:00.000Z");
expect(JSON.stringify(sanitize({ date }))).toEqual(
JSON.stringify({ date })
);
});
it("should keep URLs", () => {
expect(sanitize({ url: new URL("https://example.com/path") })).toEqual({
url: "https://example.com/path",
});
});
it("should filter sensitive fields in serialized values", () => {
const model = {
toJSON: () => ({ id: "1", accessToken: "secret" }),
};
expect(sanitize({ model })).toEqual({
model: { id: "1", accessToken: "[Filtered]" },
});
});
it("should filter sensitive fields when toJSON returns the same value", () => {
const model = {
id: "1",
token: "secret",
toJSON() {
return this;
},
};
expect(JSON.stringify(sanitize({ model }))).toEqual(
JSON.stringify({ model: { id: "1", token: "[Filtered]" } })
);
});
it("should not call toJSON on its own result", () => {
const model = {
id: "1",
token: "secret",
toJSON() {
return { ...this };
},
};
expect(JSON.stringify(sanitize({ model }))).toEqual(
JSON.stringify({ model: { id: "1", token: "[Filtered]" } })
);
});
it("should keep values at the maximum depth", () => {
expect(sanitize({ a: { b: { c: { d: "value" } } } })).toEqual({
a: { b: { c: { d: "value" } } },
});
});
it("should truncate objects deeper than the maximum depth", () => {
expect(sanitize({ a: { b: { c: { d: { e: "value" } } } } })).toEqual({
a: { b: { c: { d: "[…]" } } },
});
});
it("should not recurse forever on circular references", () => {
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
const input: Record<string, any> = { id: "1" };
input.self = input;
expect(() => JSON.stringify(sanitize(input))).not.toThrow();
});
});
+93
View File
@@ -0,0 +1,93 @@
import { isArray, isObject } from "es-toolkit/compat";
/**
* Removes sensitive fields from data attached to logs and errors, and limits
* the depth of nested data.
*
* @param input the data to sanitize.
* @param level the current nesting level.
* @returns the sanitized data.
*/
export function sanitize<T>(input: T, level = 0): T {
// Errors have non-enumerable message/stack which are dropped by spreads
// and JSON serialization, so convert them to a plain object up-front.
if (input instanceof Error) {
return {
name: input.name,
message: input.message,
stack: input.stack,
} as unknown as T;
}
// Sanitize the serialized form of values such as dates, URLs and models,
// as this is what appears in the log output.
const value: unknown = hasToJSON(input) ? input.toJSON() : input;
return sanitizeValue(value, level) as T;
}
/**
* Sanitizes a value without calling its toJSON method, as JSON serialization
* only calls it once.
*
* @param input the value to sanitize.
* @param level the current nesting level.
* @returns the sanitized value.
*/
function sanitizeValue(input: unknown, level: number): unknown {
if (typeof input !== "object" || input === null) {
return input;
}
if (level > 3) {
return "[…]";
}
if (isArray(input)) {
return input.map((item) => sanitize(item, level + 1));
}
const output: Record<string, unknown> = { ...input };
for (const key of Object.keys(output)) {
output[key] = isSensitiveField(key)
? "[Filtered]"
: sanitize(output[key], level + 1);
}
return output;
}
const sensitiveFields = new Set([
"accesstoken",
"refreshtoken",
"token",
"password",
"content",
"verificationcode",
"deleteconfirmationcode",
"apikey",
"secret",
"authorization",
]);
/**
* Checks if a field name is sensitive, ignoring case, underscores and hyphens.
*
* @param key the field name to check.
* @returns true if the field should be filtered.
*/
function isSensitiveField(key: string): boolean {
return sensitiveFields.has(key.toLowerCase().replace(/[_-]/g, ""));
}
/**
* Checks if a value has a toJSON method.
*
* @param value the value to check.
* @returns true if the value has a toJSON method.
*/
function hasToJSON(value: unknown): value is { toJSON: () => unknown } {
return (
isObject(value) && "toJSON" in value && typeof value.toJSON === "function"
);
}