chore: safer way to do redactions

Signed-off-by: blam <ben@blam.sh>
This commit is contained in:
blam
2024-05-15 15:03:13 +02:00
parent 3e8148e39c
commit 7d30d95dee
6 changed files with 42 additions and 9 deletions
+2
View File
@@ -85,6 +85,7 @@
"globby": "^11.0.0",
"isbinaryfile": "^5.0.0",
"isolated-vm": "^4.5.0",
"json-stringify-safe": "^5.0.1",
"jsonschema": "^1.2.6",
"knex": "^3.0.0",
"lodash": "^4.17.21",
@@ -107,6 +108,7 @@
"@backstage/cli": "workspace:^",
"@backstage/plugin-scaffolder-node-test-utils": "workspace:^",
"@types/fs-extra": "^11.0.0",
"@types/json-stringify-safe": "^5.0.3",
"@types/nunjucks": "^3.1.4",
"@types/supertest": "^2.0.8",
"@types/zen-observable": "^0.8.0",
@@ -21,6 +21,7 @@ import { JsonObject } from '@backstage/types';
import { Format, TransformableInfo } from 'logform';
import Transport, { TransportStreamOptions } from 'winston-transport';
import { Logger, format, createLogger, transports } from 'winston';
import stringify from 'json-stringify-safe';
/**
* Escapes a given string to be used inside a RegExp.
@@ -108,15 +109,21 @@ export class WinstonLogger implements RootLoggerService {
let redactionPattern: RegExp | undefined = undefined;
const replace = (obj: TransformableInfo) => {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object') {
obj[key] = replace(obj[key] as TransformableInfo);
} else if (typeof obj[key] === 'string') {
obj[key] = obj[key]?.replace(redactionPattern, '[REDACTED]');
}
if (!redactionPattern) {
return obj;
}
const stringifiedFields = stringify(obj);
const redacted = JSON.parse(
stringifiedFields.replace(redactionPattern, '[REDACTED]'),
);
for (const key in redacted) {
if (obj && Object.hasOwn(obj, key)) {
obj[key] = redacted[key];
}
}
return obj;
};
return {