Skip to content

Commit 1174c13

Browse files
committed
fix(types,core): guard each cause link, align object-cause rendering, declare the widening
Rework for the contract review: a link whose read throws ends the chain in a marker in both copies; object causes render under the same rules in both copies; Clause-2 reads yes (widening); docblocks name the parity test. Claude-Session: https://claude.ai/code/session_01Utp6CZHczeF42DiDgkJPmk Co-authored-by: Claude <noreply@anthropic.com>
1 parent d12137d commit 1174c13

5 files changed

Lines changed: 152 additions & 15 deletions

File tree

‎.changeset/37598-fault-log-cause-chain.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
fix: the 5xx fault log and `ObjectLogger` print an error's `cause` chain
88

9-
Clause-②: no
9+
Clause-②: yes (widening)
1010
Metadata-protocol: none
1111

1212
A server fault thrown with the original error on `cause` used to log the wrapper's message and stack only, so the root cause was missing from the operator's line. `logServerFault` (`@objectstack/types`) now prints the chain as `causes` beside `stack` on its console fallback, and `ObjectLogger` (`@objectstack/core`) prints it as `error.causes` for every `logger.error` / `logger.fatal` that passes an error. Each link carries its message and stack; a cycle stops at the first repeat and a chain stops after five links, each saying so in a last link. Nothing reaches a response body.

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

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,34 @@ describe('ObjectLogger — an error record carries the cause chain', () => {
8686
});
8787
});
8888

89+
describe('a cause is redacted like the error', () => {
90+
it('withholds the named fields of a non-Error object cause, under the logger\'s own redact list', () => {
91+
const chunks: string[] = [];
92+
vi.spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => {
93+
chunks.push(String(chunk));
94+
return true;
95+
}) as never);
96+
const logger = createLogger({ format: 'json', level: 'debug', redact: ['password', 'apiKey', 'pin'] });
97+
logger.error('withheld', new Error('w', { cause: { code: 'ECONNRESET', password: 'hunter2', apiKey: 'sk-live-1', pin: '0000' } }));
98+
const line = chunks.join('');
99+
for (const value of ['hunter2', 'sk-live-1', '0000']) expect(line).not.toContain(value);
100+
const record = JSON.parse(line.trim()) as ErrorRecord;
101+
expect(JSON.parse(record.error?.causes?.[0].message ?? '')).toEqual({
102+
code: 'ECONNRESET',
103+
password: '***REDACTED***',
104+
apiKey: '***REDACTED***',
105+
pin: '***REDACTED***',
106+
});
107+
});
108+
109+
it('a link whose message read throws ends the chain in a marker, and the record is still written', () => {
110+
const unreadable = new Error('unreadable');
111+
Object.defineProperty(unreadable, 'message', { get() { throw new Error('getter'); } });
112+
const record = recordOf((logger) => logger.error('unreadable', new Error('w', { cause: unreadable })));
113+
expect(record.error?.causes).toEqual([{ message: '[cause chain link unreadable: reading it threw]' }]);
114+
});
115+
});
116+
89117
describe('parity — the logger and the fault log render one shape', () => {
90118
const cycle = () => {
91119
const a = new Error('a');
@@ -103,10 +131,27 @@ describe('parity — the logger and the fault log render one shape', () => {
103131
['a deep chain', deep],
104132
['a string cause', () => new Error('w', { cause: 'socket hang up' })],
105133
['an object cause', () => new Error('w', { cause: { code: 'ECONNRESET' } })],
134+
['an object cause with withheld fields', () => new Error('w', { cause: { code: 'E1', password: 'p', apiKey: 'k' } })],
135+
['an object cause that cannot be serialized', () => {
136+
const loop: Record<string, unknown> = { code: 'E2' };
137+
loop.self = loop;
138+
return new Error('w', { cause: loop });
139+
}],
140+
['a link whose message read throws', () => {
141+
const unreadable = new Error('unreadable');
142+
Object.defineProperty(unreadable, 'message', { get() { throw new Error('getter'); } });
143+
return new Error('w', { cause: new Error('mid', { cause: unreadable }) });
144+
}],
145+
['a throwing cause getter', () => {
146+
const hostile = new Error('w');
147+
Object.defineProperty(hostile, 'cause', { get() { throw new Error('getter'); } });
148+
return hostile;
149+
}],
106150
];
107151
it.each(fixtures)('%s', (_name, make) => {
108152
const error = make();
109153
const record = recordOf((logger) => logger.error('parity', error));
110-
expect(record.error?.causes).toEqual(faultCauseChain(error));
154+
// The record omits `causes` when the chain is empty; the fault log's helper answers `[]`.
155+
expect(record.error?.causes ?? []).toEqual(faultCauseChain(error));
111156
});
112157
});

‎packages/core/src/logger.ts‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -194,15 +194,19 @@ const CAUSE_DEPTH_LIMIT = 5;
194194
* used to log as the wrapper alone, so the root cause of a wrapped fault was
195195
* missing from the line. Each link is its message and stack. Bounded both
196196
* ways: a cycle stops at the first repeat, a chain past
197-
* {@link CAUSE_DEPTH_LIMIT} stops there, and either says so in a last link.
197+
* {@link CAUSE_DEPTH_LIMIT} stops there, and either says so in a last link;
198+
* a link whose read throws ends the chain in a marker link too.
198199
*
199200
* The same shape as `faultCauseChain` in `@objectstack/types`, which the 5xx
200201
* fault log prints on its console fallback. A copy rather than an import:
201202
* this entry is browser-safe and `@objectstack/client` bundles it without
202203
* depending on `@objectstack/types`, whose root entry would come along with
203-
* `@objectstack/spec` behind it. `logger.test.ts` pins the two to one output.
204+
* `@objectstack/spec` behind it. `logger-error-cause.test.ts` pins the two to one output.
204205
*/
205-
function renderError(error: Error): { message: string; stack?: string; causes?: Array<{ message: string; stack?: string }> } {
206+
function renderError(
207+
error: Error,
208+
isRedacted: (key: string) => boolean,
209+
): { message: string; stack?: string; causes?: Array<{ message: string; stack?: string }> } {
206210
const causes: Array<{ message: string; stack?: string }> = [];
207211
const seen = new Set<unknown>([error]);
208212
let current = causeOf(error);
@@ -216,7 +220,14 @@ function renderError(error: Error): { message: string; stack?: string; causes?:
216220
break;
217221
}
218222
seen.add(current);
219-
causes.push(causeLine(current));
223+
try {
224+
causes.push(causeLine(current, isRedacted));
225+
} catch {
226+
// A link whose name, message or stack read throws (a hostile getter, a Proxy)
227+
// ends the chain in a marker; it must not cost the whole line.
228+
causes.push({ message: '[cause chain link unreadable: reading it threw]' });
229+
break;
230+
}
220231
current = causeOf(current);
221232
}
222233
return { message: error.message, stack: error.stack, ...(causes.length > 0 ? { causes } : {}) };
@@ -232,13 +243,19 @@ function causeOf(value: unknown): unknown {
232243
}
233244
}
234245

235-
function causeLine(cause: unknown): { message: string; stack?: string } {
246+
/**
247+
* One link as text. A non-Error object cause is serialized with the logger's
248+
* own redaction applied key by key, the same rule the record's fields get.
249+
* A read that throws is the caller's to catch (`renderError` ends the chain).
250+
*/
251+
function causeLine(cause: unknown, isRedacted: (key: string) => boolean): { message: string; stack?: string } {
236252
if (cause instanceof Error) {
237253
return { message: `${cause.name}: ${cause.message}`, ...(cause.stack ? { stack: cause.stack } : {}) };
238254
}
239255
if (typeof cause === 'string') return { message: cause };
240256
try {
241-
return { message: JSON.stringify(cause) ?? String(cause) };
257+
const text = JSON.stringify(cause, (key, value) => (key !== '' && isRedacted(key) ? '***REDACTED***' : value));
258+
return { message: text ?? String(cause) };
242259
} catch {
243260
return { message: String(cause) };
244261
}
@@ -401,7 +418,7 @@ export class ObjectLogger implements Logger {
401418
const context = this.redactSensitive({
402419
...this.bindings,
403420
...meta,
404-
...(error ? { error: renderError(error) } : {}),
421+
...(error ? { error: renderError(error, (key) => this.isRedactedFieldName(key)) } : {}),
405422
});
406423

407424
const hasContext = Object.keys(context).length > 0;

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,49 @@ describe('faultCauseChain — bounded both ways', () => {
118118
expect(faultCauseChain('a string throw')).toEqual([]);
119119
expect(faultCauseChain(undefined)).toEqual([]);
120120
});
121+
122+
it('a link whose message read throws ends the chain in a marker, and the line is still written', () => {
123+
const unreadable = new Error('unreadable');
124+
Object.defineProperty(unreadable, 'message', { get() { throw new Error('getter'); } });
125+
const outer = withCause(OUTER, withCause(MID, unreadable));
126+
expect(faultCauseChain(outer)).toEqual([
127+
expect.objectContaining({ message: `Error: ${MID}` }),
128+
{ message: '[cause chain link unreadable: reading it threw]' },
129+
]);
130+
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
131+
try {
132+
expect(logServerFault({ status: 500, error: outer })).toBe(true);
133+
const meta = faultLines(spy)[0][1] as { causes?: Array<{ message: string }> };
134+
expect(meta.causes?.[1]).toEqual({ message: '[cause chain link unreadable: reading it threw]' });
135+
} finally {
136+
spy.mockRestore();
137+
}
138+
});
139+
});
140+
141+
describe('a cause is redacted like the error', () => {
142+
it('withholds the named fields of a non-Error object cause and keeps the rest', () => {
143+
const chain = faultCauseChain(withCause('w', { code: 'ECONNRESET', password: 'hunter2', apiKey: 'sk-live-1', nested: { authToken: 't-1' } }));
144+
expect(chain).toHaveLength(1);
145+
expect(JSON.parse(chain[0].message)).toEqual({
146+
code: 'ECONNRESET',
147+
password: '***REDACTED***',
148+
apiKey: '***REDACTED***',
149+
nested: { authToken: '***REDACTED***' },
150+
});
151+
for (const value of ['hunter2', 'sk-live-1', 't-1']) expect(chain[0].message).not.toContain(value);
152+
});
153+
154+
it('the console fallback line carries the withheld form', () => {
155+
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
156+
try {
157+
logServerFault({ status: 500, error: withCause(OUTER, { password: 'hunter2' }) });
158+
const meta = faultLines(spy)[0][1] as { causes?: Array<{ message: string }> };
159+
expect(meta.causes).toEqual([{ message: '{"password":"***REDACTED***"}' }]);
160+
} finally {
161+
spy.mockRestore();
162+
}
163+
});
121164
});
122165

123166
describe('logServerFault — an injected logger renders the chain itself', () => {

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

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -302,17 +302,28 @@ export const FAULT_CAUSE_DEPTH_LIMIT = 5;
302302
* Bounded both ways: a cycle (`a.cause = b; b.cause = a`) stops at the first
303303
* repeat, and a chain deeper than {@link FAULT_CAUSE_DEPTH_LIMIT} stops there;
304304
* either says so in a last link, so a cut chain never reads as a whole one.
305+
* A link whose read throws ends the chain in a marker link too.
306+
*
307+
* 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.
305312
*
306313
* ⛔ Operator-only. It feeds the log line; no door puts it on the wire, and a
307314
* 5xx answer withholds even the wrapper's own sentence.
308315
*
309316
* `@objectstack/core`'s `ObjectLogger` renders the same shape for every
310317
* `logger.error(message, err)`. It keeps its own copy because its `./logger`
311318
* entry is browser-safe and bundled by `@objectstack/client`, which does not
312-
* depend on this package; `logger.test.ts` there pins the two to the same
313-
* output.
319+
* depend on this package; `logger-error-cause.test.ts` there pins the two to
320+
* the same output.
314321
*/
315-
export function faultCauseChain(thrown: unknown, limit: number = FAULT_CAUSE_DEPTH_LIMIT): FaultCauseLine[] {
322+
export function faultCauseChain(
323+
thrown: unknown,
324+
isRedacted: (key: string) => boolean = isDefaultRedactedFieldName,
325+
): FaultCauseLine[] {
326+
const limit = FAULT_CAUSE_DEPTH_LIMIT;
316327
const lines: FaultCauseLine[] = [];
317328
const seen = new Set<unknown>([thrown]);
318329
let current = causeOf(thrown);
@@ -326,7 +337,14 @@ export function faultCauseChain(thrown: unknown, limit: number = FAULT_CAUSE_DEP
326337
break;
327338
}
328339
seen.add(current);
329-
lines.push(causeLine(current));
340+
try {
341+
lines.push(causeLine(current, isRedacted));
342+
} catch {
343+
// A link whose name, message or stack read throws (a hostile getter, a Proxy)
344+
// ends the chain in a marker; it must not cost the whole line.
345+
lines.push({ message: '[cause chain link unreadable: reading it threw]' });
346+
break;
347+
}
330348
current = causeOf(current);
331349
}
332350
return lines;
@@ -342,14 +360,28 @@ function causeOf(value: unknown): unknown {
342360
}
343361
}
344362

345-
function causeLine(cause: unknown): FaultCauseLine {
363+
/** `LoggerConfig.redact`'s default words (`@objectstack/spec` `logging.zod.ts`). */
364+
const DEFAULT_REDACTED_WORDS = ['password', 'token', 'secret', 'key'] as const;
365+
366+
function isDefaultRedactedFieldName(key: string): boolean {
367+
const lower = key.toLowerCase();
368+
return DEFAULT_REDACTED_WORDS.some((word) => lower.includes(word));
369+
}
370+
371+
function causeLine(cause: unknown, isRedacted: (key: string) => boolean): FaultCauseLine {
346372
if (cause instanceof Error) {
347373
return {
348374
message: `${cause.name}: ${cause.message}`,
349375
...(cause.stack ? { stack: cause.stack } : {}),
350376
};
351377
}
352-
return { message: typeof cause === 'string' ? cause : safeStringify(cause) };
378+
if (typeof cause === 'string') return { message: cause };
379+
try {
380+
const text = JSON.stringify(cause, (key, value) => (key !== '' && isRedacted(key) ? '***REDACTED***' : value));
381+
return { message: text ?? String(cause) };
382+
} catch {
383+
return { message: String(cause) };
384+
}
353385
}
354386

355387
/**

0 commit comments

Comments
 (0)