Skip to content

Commit d6092ff

Browse files
committed
fix(types): match the default redact words on word boundaries, as ObjectLogger does
Claude-Session: https://claude.ai/code/session_01Utp6CZHczeF42DiDgkJPmk Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5a62315 commit d6092ff

4 files changed

Lines changed: 108 additions & 8 deletions

File tree

‎packages/core/src/logger-error-cause.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,15 @@ describe('parity — the logger and the fault log render one shape', () => {
132132
['a string cause', () => new Error('w', { cause: 'socket hang up' })],
133133
['an object cause', () => new Error('w', { cause: { code: 'ECONNRESET' } })],
134134
['a cause redacted like the error', () => new Error('w', { cause: { code: 'E1', password: 'p', apiKey: 'k' } })],
135+
['field names under the default redact words, whole-word matched', () => new Error('w', {
136+
cause: {
137+
keys: ['a'], tokens: 3, monkey: 'm', keyword: 'k', secretary: 's', tokenizer: 't',
138+
apiKey: 'x', apikey: 'x', accesstoken: 'x', refresh_tokens: ['x'], clientSecret: 'x', password: 'x', API_KEY: 'x',
139+
},
140+
})],
141+
['an array inside an object cause', () => new Error('w', {
142+
cause: { code: 'E3', attempts: [{ host: 'db-1', password: 'x' }, { host: 'db-2', authToken: 'y' }] },
143+
})],
135144
['an object cause that cannot be serialized', () => {
136145
const loop: Record<string, unknown> = { code: 'E2' };
137146
loop.self = loop;

‎packages/core/src/logger.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,9 @@ const CAUSE_DEPTH_LIMIT = 5;
201201
* fault log prints on its console fallback. A copy rather than an import:
202202
* this entry is browser-safe and `@objectstack/client` bundles it without
203203
* depending on `@objectstack/types`, whose root entry would come along with
204-
* `@objectstack/spec` behind it. `logger-error-cause.test.ts` pins the two to one output.
204+
* `@objectstack/spec` behind it. `logger-error-cause.test.ts` pins the two to one output,
205+
* the field-name rule for object causes included (the types copy carries this
206+
* file's whole-word matcher for its default list).
205207
*/
206208
function renderError(
207209
error: Error,

‎packages/types/src/server-fault-log-cause.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,22 @@ describe('a cause is redacted like the error', () => {
151151
for (const value of ['hunter2', 'sk-live-1', 't-1']) expect(chain[0].message).not.toContain(value);
152152
});
153153

154+
it('by whole words, as the logger matches its redact list', () => {
155+
const [line] = faultCauseChain(withCause('w', {
156+
keys: ['a'], tokens: 3, monkey: 'm', keyword: 'k', secretary: 's',
157+
apiKey: 'x', apikey: 'x', refresh_tokens: ['x'], password: 'x',
158+
}));
159+
expect(JSON.parse(line.message)).toEqual({
160+
keys: ['a'], tokens: 3, monkey: 'm', keyword: 'k', secretary: 's',
161+
apiKey: '***REDACTED***', apikey: '***REDACTED***', refresh_tokens: '***REDACTED***', password: '***REDACTED***',
162+
});
163+
});
164+
165+
it('inside an array in an object cause', () => {
166+
const [line] = faultCauseChain(withCause('w', { attempts: [{ host: 'db-1', password: 'x' }, { host: 'db-2' }] }));
167+
expect(JSON.parse(line.message)).toEqual({ attempts: [{ host: 'db-1', password: '***REDACTED***' }, { host: 'db-2' }] });
168+
});
169+
154170
it('on the console fallback line', () => {
155171
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
156172
try {

‎packages/types/src/server-fault-log.ts‎

Lines changed: 80 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -305,10 +305,11 @@ export const FAULT_CAUSE_DEPTH_LIMIT = 5;
305305
* A link whose read throws ends the chain in a marker link too.
306306
*
307307
* A non-Error object cause is serialized with `isRedacted` applied key by
308-
* key, the same rule a logger applies to its own fields. The default is the
309-
* logger's default redact list (`LoggerConfig.redact`), matched on the
310-
* lower-cased name, so the console fallback, which has no logger config,
311-
* errs towards withholding.
308+
* key, at every depth. The default is `ObjectLogger`'s own rule over its
309+
* default redact list (`LoggerConfig.redact`'s default words, whole-word
310+
* matched). ⚠️ Only the default words: the console fallback has no logger
311+
* config, so a host's own `redact` list is not applied to the line it writes;
312+
* a door handed a configured logger gets that logger's list instead.
312313
*
313314
* ⛔ Operator-only. It feeds the log line; no door puts it on the wire, and a
314315
* 5xx answer withholds even the wrapper's own sentence.
@@ -360,12 +361,84 @@ function causeOf(value: unknown): unknown {
360361
}
361362
}
362363

363-
/** `LoggerConfig.redact`'s default words (`@objectstack/spec` `logging.zod.ts`). */
364+
/**
365+
* `LoggerConfig.redact`'s default words (`@objectstack/spec` `logging.zod.ts`),
366+
* which `ObjectLogger` also applies when it is given none.
367+
*/
364368
const DEFAULT_REDACTED_WORDS = ['password', 'token', 'secret', 'key'] as const;
365369

370+
/**
371+
* The default field-name rule, matched the way `ObjectLogger` matches its
372+
* redact list: on word boundaries, the maintainer's ruling on #5573, so a bare
373+
* `keys` / `tokens` or a `monkey` / `keyword` / `secretary` is not withheld,
374+
* while `apiKey`, `refresh_tokens` and `accesstoken` are.
375+
*
376+
* A copy of `@objectstack/core`'s matcher (`tokenizeFieldName` and
377+
* `fieldWordsMatchPattern` in `logger.ts`), for the same reason
378+
* {@link faultCauseChain} is one; `logger-error-cause.test.ts` there runs a
379+
* fixture of these spellings through both and fails on any drift.
380+
*/
366381
function isDefaultRedactedFieldName(key: string): boolean {
367-
const lower = key.toLowerCase();
368-
return DEFAULT_REDACTED_WORDS.some((word) => lower.includes(word));
382+
const nameWords = tokenizeFieldName(key);
383+
return DEFAULT_REDACTED_WORDS.some((word) => fieldWordsMatchPattern(nameWords, [word]));
384+
}
385+
386+
function tokenizeFieldName(name: string): string[] {
387+
return name
388+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
389+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
390+
.replace(/([a-zA-Z])([0-9])/g, '$1 $2')
391+
.split(/[^A-Za-z0-9]+/)
392+
.filter(Boolean)
393+
.map((word) => word.toLowerCase());
394+
}
395+
396+
function singularizeWord(word: string): string {
397+
if (/(?:ss|us|is)$/.test(word)) return word;
398+
if (/(?:ch|sh|s|x|z)es$/.test(word)) return word.slice(0, -2);
399+
if (/[a-z0-9]s$/.test(word)) return word.slice(0, -1);
400+
return word;
401+
}
402+
403+
/** Glued qualifiers that mark the secret sense: `apikey`, `accesstoken`, `clientsecret`. */
404+
const CONCATENATED_SECRET_QUALIFIERS = new Set([
405+
'access', 'account', 'admin', 'api', 'app', 'auth', 'bearer', 'client', 'csrf', 'db', 'database',
406+
'encryption', 'id', 'jwt', 'master', 'oauth', 'private', 'public', 'refresh', 'root', 'secret',
407+
'service', 'session', 'shared', 'sign', 'signing', 'ssh', 'token', 'user', 'webhook', 'xsrf',
408+
]);
409+
410+
function isQualifiedConcatenation(word: string, redactWord: string): boolean {
411+
for (const base of [word, singularizeWord(word)]) {
412+
if (base.length <= redactWord.length || !base.endsWith(redactWord)) continue;
413+
if (CONCATENATED_SECRET_QUALIFIERS.has(base.slice(0, base.length - redactWord.length))) return true;
414+
}
415+
return false;
416+
}
417+
418+
function containsWordRun(words: string[], run: string[]): boolean {
419+
for (let i = 0; i + run.length <= words.length; i++) {
420+
if (run.every((word, offset) => words[i + offset] === word)) return true;
421+
}
422+
return false;
423+
}
424+
425+
function fieldWordsMatchPattern(nameWords: string[], patternWords: string[]): boolean {
426+
if (patternWords.length === 0 || nameWords.length === 0) return false;
427+
if (patternWords.length > 1) {
428+
const glued = patternWords.join('');
429+
return (
430+
containsWordRun(nameWords, patternWords) ||
431+
nameWords.some((word) => word === glued || singularizeWord(word) === glued)
432+
);
433+
}
434+
const redactWord = patternWords[0];
435+
const isCompound = nameWords.filter((word) => /[a-z]/.test(word)).length > 1;
436+
return nameWords.some(
437+
(word) =>
438+
word === redactWord ||
439+
(isCompound && singularizeWord(word) === redactWord) ||
440+
isQualifiedConcatenation(word, redactWord),
441+
);
369442
}
370443

371444
function causeLine(cause: unknown, isRedacted: (key: string) => boolean): FaultCauseLine {

0 commit comments

Comments
 (0)