diff --git a/.changeset/eight-falcons-explode.md b/.changeset/eight-falcons-explode.md new file mode 100644 index 0000000000..d9a1a2fe1f --- /dev/null +++ b/.changeset/eight-falcons-explode.md @@ -0,0 +1,5 @@ +--- +'@backstage/backend-app-api': patch +--- + +Fixed an issue were the log redaction didn't properly escape RegExp characters. diff --git a/packages/backend-app-api/src/logging/WinstonLogger.test.ts b/packages/backend-app-api/src/logging/WinstonLogger.test.ts new file mode 100644 index 0000000000..5d8cfc9c90 --- /dev/null +++ b/packages/backend-app-api/src/logging/WinstonLogger.test.ts @@ -0,0 +1,38 @@ +/* + * Copyright 2023 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { WinstonLogger } from './WinstonLogger'; + +function msg(message: string) { + return { message, level: 'info' }; +} + +describe('WinstonLogger', () => { + it('redacter should redact and escape regex', () => { + const redacter = WinstonLogger.redacter(); + expect(redacter.format.transform(msg('hello (world)'))).toEqual( + msg('hello (world)'), + ); + redacter.add(['hello']); + expect(redacter.format.transform(msg('hello (world)'))).toEqual( + msg('[REDACTED] (world)'), + ); + redacter.add(['(world)']); + expect(redacter.format.transform(msg('hello (world)'))).toEqual( + msg('[REDACTED] [REDACTED]'), + ); + }); +}); diff --git a/packages/backend-app-api/src/logging/WinstonLogger.ts b/packages/backend-app-api/src/logging/WinstonLogger.ts index cfee65d053..d32b816523 100644 --- a/packages/backend-app-api/src/logging/WinstonLogger.ts +++ b/packages/backend-app-api/src/logging/WinstonLogger.ts @@ -27,6 +27,7 @@ import { transports, transport as Transport, } from 'winston'; +import { escapeRegExp } from '../lib/escapeRegExp'; /** * @public @@ -98,10 +99,10 @@ export class WinstonLogger implements RootLoggerService { } } if (added > 0) { - redactionPattern = new RegExp( - `(${Array.from(redactionSet).join('|')})`, - 'g', - ); + const redactions = Array.from(redactionSet) + .map(r => escapeRegExp(r)) + .join('|'); + redactionPattern = new RegExp(`(${redactions})`, 'g'); } }, };