diff --git a/.changeset/37598-fault-log-cause-chain.md b/.changeset/37598-fault-log-cause-chain.md new file mode 100644 index 00000000000..0aea2ef8b1e --- /dev/null +++ b/.changeset/37598-fault-log-cause-chain.md @@ -0,0 +1,14 @@ +--- +'@objectstack/types': patch +'@objectstack/core': patch +'@objectstack/service-record-context': patch +--- + +fix: the 5xx fault log and `ObjectLogger` print an error's `cause` chain + +Clause-②: yes (widening) +Metadata-protocol: none + +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. + +`@objectstack/service-record-context` drops the `Caused by:` suffix it appended to a failed read's stack, since the fault line now renders the `cause` itself. diff --git a/packages/core/src/logger-error-cause.test.ts b/packages/core/src/logger-error-cause.test.ts new file mode 100644 index 00000000000..adbcfb5a9b3 --- /dev/null +++ b/packages/core/src/logger-error-cause.test.ts @@ -0,0 +1,166 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `ObjectLogger` prints an error's `cause` chain. + * + * `logger.error(message, err)` used to record `{ message, stack }` of the + * error alone, so a wrapper thrown with the original on `cause` logged + * without its root cause — the 5xx fault line (`logServerFault`, + * `@objectstack/types`) hands its injected logger exactly such a wrapper. + * The record now carries `error.causes`, bounded, in the same shape the fault + * log's console fallback prints; the parity block below pins the two copies + * to one output. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { faultCauseChain } from '@objectstack/types'; + +import { createLogger } from './logger.js'; + +const ROOT = 'SQLITE_IOERR: disk I/O error reading policy_revision.version'; +const MID = 'driver read failed for policy_revision'; +const OUTER = 'The related records of policy could not be read.'; + +const wrapped = () => new Error(OUTER, { cause: new Error(MID, { cause: new Error(ROOT) }) }); + +type ErrorRecord = { error?: { message: string; stack?: string; causes?: Array<{ message: string; stack?: string }> } }; + +/** One `error`-level record as the JSON format writes it to stderr. */ +function recordOf(log: (logger: ReturnType) => void): ErrorRecord { + const chunks: string[] = []; + vi.spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { + chunks.push(String(chunk)); + return true; + }) as never); + log(createLogger({ format: 'json', level: 'debug' })); + const lines = chunks.join('').split('\n').filter(Boolean); + expect(lines).toHaveLength(1); + return JSON.parse(lines[0]) as ErrorRecord; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('ObjectLogger — an error record carries the cause chain', () => { + it('logs each cause\'s message and stack, outermost first', () => { + const record = recordOf((logger) => logger.error('[5xx] 500 GET /api/v1/x — boom', wrapped(), { status: 500 })); + expect(record.error?.message).toBe(OUTER); + expect(record.error?.stack).toContain(OUTER); + const causes = record.error?.causes ?? []; + expect(causes).toHaveLength(2); + expect(causes[0].message).toBe(`Error: ${MID}`); + expect(causes[0].stack).toContain(MID); + expect(causes[1].message).toBe(`Error: ${ROOT}`); + expect(causes[1].stack).toContain(ROOT); + }); + + it('fatal renders it too', () => { + const record = recordOf((logger) => logger.fatal('down', wrapped())); + expect(record.error?.causes?.[1].message).toBe(`Error: ${ROOT}`); + }); + + it('CONTROL — an error with no cause carries no causes field', () => { + const record = recordOf((logger) => logger.error('plain', new Error(OUTER))); + expect(record.error).toBeDefined(); + expect(record.error).not.toHaveProperty('causes'); + }); + + it('stops a cycle at its first repeat, and says so', () => { + const a = new Error('a'); + const b = new Error('b', { cause: a }); + (a as { cause?: unknown }).cause = b; + const record = recordOf((logger) => logger.error('cycle', a)); + expect(record.error?.causes?.map((c) => c.message)).toEqual([ + 'Error: b', + '[cause chain cycle: this link repeats an earlier one]', + ]); + }); + + it('stops a deep chain after five links, and says so', () => { + let error = new Error('link 0'); + for (let i = 1; i <= 20; i += 1) error = new Error(`link ${i}`, { cause: error }); + const causes = recordOf((logger) => logger.error('deep', error)).error?.causes ?? []; + expect(causes).toHaveLength(6); + expect(causes[5]).toEqual({ message: '[cause chain truncated after 5 links]' }); + }); +}); + +describe('a cause is redacted like the error', () => { + it('under the logger\'s own redact list', () => { + const chunks: string[] = []; + vi.spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { + chunks.push(String(chunk)); + return true; + }) as never); + const logger = createLogger({ format: 'json', level: 'debug', redact: ['password', 'apiKey', 'pin'] }); + logger.error('withheld', new Error('w', { cause: { code: 'ECONNRESET', password: 'hunter2', apiKey: 'sk-live-1', pin: '0000' } })); + const line = chunks.join(''); + for (const value of ['hunter2', 'sk-live-1', '0000']) expect(line).not.toContain(value); + const record = JSON.parse(line.trim()) as ErrorRecord; + expect(JSON.parse(record.error?.causes?.[0].message ?? '')).toEqual({ + code: 'ECONNRESET', + password: '***REDACTED***', + apiKey: '***REDACTED***', + pin: '***REDACTED***', + }); + }); + + it('a link whose message read throws ends the chain in a marker, and the record is still written', () => { + const unreadable = new Error('unreadable'); + Object.defineProperty(unreadable, 'message', { get() { throw new Error('getter'); } }); + const record = recordOf((logger) => logger.error('unreadable', new Error('w', { cause: unreadable }))); + expect(record.error?.causes).toEqual([{ message: '[cause chain link unreadable: reading it threw]' }]); + }); +}); + +describe('parity — the logger and the fault log render one shape', () => { + const cycle = () => { + const a = new Error('a'); + (a as { cause?: unknown }).cause = new Error('b', { cause: a }); + return a; + }; + const deep = () => { + let error = new Error('link 0'); + for (let i = 1; i <= 9; i += 1) error = new Error(`link ${i}`, { cause: error }); + return error; + }; + const fixtures: Array<[string, () => Error]> = [ + ['a nested Error chain', wrapped], + ['a cycle', cycle], + ['a deep chain', deep], + ['a string cause', () => new Error('w', { cause: 'socket hang up' })], + ['an object cause', () => new Error('w', { cause: { code: 'ECONNRESET' } })], + ['a cause redacted like the error', () => new Error('w', { cause: { code: 'E1', password: 'p', apiKey: 'k' } })], + ['field names under the default redact words, whole-word matched', () => new Error('w', { + cause: { + keys: ['a'], tokens: 3, monkey: 'm', keyword: 'k', secretary: 's', tokenizer: 't', + apiKey: 'x', apikey: 'x', accesstoken: 'x', refresh_tokens: ['x'], clientSecret: 'x', password: 'x', API_KEY: 'x', + }, + })], + ['an array inside an object cause', () => new Error('w', { + cause: { code: 'E3', attempts: [{ host: 'db-1', password: 'x' }, { host: 'db-2', authToken: 'y' }] }, + })], + ['an object cause that cannot be serialized', () => { + const loop: Record = { code: 'E2' }; + loop.self = loop; + return new Error('w', { cause: loop }); + }], + ['a link whose message read throws', () => { + const unreadable = new Error('unreadable'); + Object.defineProperty(unreadable, 'message', { get() { throw new Error('getter'); } }); + return new Error('w', { cause: new Error('mid', { cause: unreadable }) }); + }], + ['a throwing cause getter', () => { + const hostile = new Error('w'); + Object.defineProperty(hostile, 'cause', { get() { throw new Error('getter'); } }); + return hostile; + }], + ]; + it.each(fixtures)('%s', (_name, make) => { + const error = make(); + const record = recordOf((logger) => logger.error('parity', error)); + // The record omits `causes` when the chain is empty; the fault log's helper answers `[]`. + expect(record.error?.causes ?? []).toEqual(faultCauseChain(error)); + }); +}); diff --git a/packages/core/src/logger.ts b/packages/core/src/logger.ts index bef1d3358bc..967949115c4 100644 --- a/packages/core/src/logger.ts +++ b/packages/core/src/logger.ts @@ -183,6 +183,86 @@ function colorEnabled(stream: { isTTY?: boolean } | undefined): boolean { return Boolean(stream?.isTTY); } +/** How many `cause` links an error record prints before it says it stopped. */ +const CAUSE_DEPTH_LIMIT = 5; + +/** + * An error as a log record carries it: message and stack, and the `cause` + * chain under it, outermost first. + * + * A wrapper thrown with the original on `cause` (`new Error(say, { cause })`) + * used to log as the wrapper alone, so the root cause of a wrapped fault was + * missing from the line. Each link is its message and stack. Bounded both + * ways: a cycle stops at the first repeat, a chain past + * {@link CAUSE_DEPTH_LIMIT} stops there, and either says so in a last link; + * a link whose read throws ends the chain in a marker link too. + * + * The same shape as `faultCauseChain` in `@objectstack/types`, which the 5xx + * fault log prints on its console fallback. A copy rather than an import: + * this entry is browser-safe and `@objectstack/client` bundles it without + * depending on `@objectstack/types`, whose root entry would come along with + * `@objectstack/spec` behind it. `logger-error-cause.test.ts` pins the two to one output, + * the field-name rule for object causes included (the types copy carries this + * file's whole-word matcher for its default list). + */ +function renderError( + error: Error, + isRedacted: (key: string) => boolean, +): { message: string; stack?: string; causes?: Array<{ message: string; stack?: string }> } { + const causes: Array<{ message: string; stack?: string }> = []; + const seen = new Set([error]); + let current = causeOf(error); + while (current !== undefined && current !== null) { + if (seen.has(current)) { + causes.push({ message: '[cause chain cycle: this link repeats an earlier one]' }); + break; + } + if (causes.length >= CAUSE_DEPTH_LIMIT) { + causes.push({ message: `[cause chain truncated after ${CAUSE_DEPTH_LIMIT} links]` }); + break; + } + seen.add(current); + try { + causes.push(causeLine(current, isRedacted)); + } catch { + // A link whose name, message or stack read throws (a hostile getter, a Proxy) + // ends the chain in a marker; it must not cost the whole line. + causes.push({ message: '[cause chain link unreadable: reading it threw]' }); + break; + } + current = causeOf(current); + } + return { message: error.message, stack: error.stack, ...(causes.length > 0 ? { causes } : {}) }; +} + +function causeOf(value: unknown): unknown { + if (typeof value !== 'object' || value === null) return undefined; + try { + return (value as { cause?: unknown }).cause; + } catch { + // A throwing `cause` getter ends the chain; it must not cost the record. + return undefined; + } +} + +/** + * One link as text. A non-Error object cause is serialized with the logger's + * own redaction applied key by key, the same rule the record's fields get. + * A read that throws is the caller's to catch (`renderError` ends the chain). + */ +function causeLine(cause: unknown, isRedacted: (key: string) => boolean): { message: string; stack?: string } { + if (cause instanceof Error) { + return { message: `${cause.name}: ${cause.message}`, ...(cause.stack ? { stack: cause.stack } : {}) }; + } + if (typeof cause === 'string') return { message: cause }; + try { + const text = JSON.stringify(cause, (key, value) => (key !== '' && isRedacted(key) ? '***REDACTED***' : value)); + return { message: text ?? String(cause) }; + } catch { + return { message: String(cause) }; + } +} + /** * Resolve a Node builtin without putting it in this module's import graph. * @@ -340,7 +420,7 @@ export class ObjectLogger implements Logger { const context = this.redactSensitive({ ...this.bindings, ...meta, - ...(error ? { error: { message: error.message, stack: error.stack } } : {}), + ...(error ? { error: renderError(error, (key) => this.isRedactedFieldName(key)) } : {}), }); const hasContext = Object.keys(context).length > 0; diff --git a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts index 601fa095f39..189794cc9a0 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -797,13 +797,19 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(faults).toHaveLength(4); for (const [, meta] of faults) { expect(meta).toMatchObject({ status: 500, code: 'INTERNAL_ERROR' }); - expect(String((meta as { stack?: unknown }).stack)).toContain(`Caused by: Error: ${OUTAGE}`); + // The original reaches the line through the fault log's own `cause` rendering, + // not through a suffix on the failure's stack. + const { causes, stack } = meta as { causes?: Array<{ message: string; stack?: string }>; stack?: unknown }; + expect(causes?.[0]?.message).toBe(`Error: ${OUTAGE}`); + expect(causes?.[0]?.stack).toContain(OUTAGE); + expect(String(stack)).not.toContain('Caused by:'); } // Reached through each door, so the answer is the outage's on both. expect(failing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(4); expect(answer.isError).toBe(true); expect(answer.payload.error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); - for (const word of ['rc_revision', 'disk I/O', 'version']) expect(answer.text).not.toContain(word); + // The wire carries no cause text: the fault line is the operator's alone. + for (const word of ['rc_revision', 'disk I/O', 'version', 'causes', 'Caused by']) expect(answer.text).not.toContain(word); } finally { failing.mockRestore(); errorLines.mockRestore(); diff --git a/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts b/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts index 78a53150f48..3bc1997b8a4 100644 --- a/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts +++ b/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts @@ -443,10 +443,10 @@ describe('get_record_context — a read of a related object that fails is a fail for (const word of ['policy_revision', 'secret_note', 'acme_private', 'store down']) { expect(failed.message).not.toContain(word); } - // The original is the host's, on `cause` (which no door puts on the wire), and at the foot of the - // stack, which the doors' fault line prints where it prints no `cause`. + // The original is the host's, on `cause` (which no door puts on the wire and the doors' fault line + // prints). The failure's own stack does not repeat it: the fault line renders the `cause` chain. expect(failed.cause).toBe(original); - expect(failed.stack).toContain(`Caused by: ${original instanceof Error ? original.stack : String(original)}`); + expect(failed.stack ?? '').not.toContain('Caused by:'); }; it.each([ diff --git a/packages/services/service-record-context/src/record-context-tools.ts b/packages/services/service-record-context/src/record-context-tools.ts index 756d30378a8..dc26a891b58 100644 --- a/packages/services/service-record-context/src/record-context-tools.ts +++ b/packages/services/service-record-context/src/record-context-tools.ts @@ -194,17 +194,6 @@ export function doorAnswersItself(thrown: unknown, object: string): boolean { return !Object.entries(body).every(([key, value]) => key === 'error' || (key === 'code' && value === 'INTERNAL_ERROR')); } -/** A thrown value as a log reads it: its stack, else its text. */ -function describeThrown(thrown: unknown): string { - if (thrown instanceof Error) return thrown.stack ?? `${thrown.name}: ${thrown.message}`; - if (typeof thrown === 'string') return thrown; - try { - return JSON.stringify(thrown) ?? String(thrown); - } catch { - return String(thrown); - } -} - /** The call's arguments, or a `VALIDATION_ERROR` carrying the spec's own words. */ function parseInput(input: unknown): GetRecordContextInput { const parsed = GetRecordContextInputSchema.safeParse(input); @@ -468,8 +457,8 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex // (500) in the executor's own sentence, which names the pack and the root // only. No door renders the original error, so nothing it says can name an // object, a field or a package the caller is not shown; it rides on - // `cause` and at the foot of the stack, neither of which a door puts on the - // wire, and the doors' fault line prints it. The doors withhold a 5xx's + // `cause`, which no door puts on the wire and the doors' fault line prints + // (`logServerFault` and `ObjectLogger` render the `cause` chain). The doors withhold a 5xx's // sentence too (`Internal server error`), so the sentence is read // in-process only (the citation verifier's host, through `onError`). // @@ -489,10 +478,6 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex status: 500, cause: err, }); - // The doors' fault line prints an error's message and stack, never its - // `cause` (`logServerFault`, and `ObjectLogger` behind it), so the stack - // carries the original too. A stack is never on the wire. - failure.stack = `${failure.stack ?? `Error: ${failure.message}`}\nCaused by: ${describeThrown(err)}`; throw failure; }; diff --git a/packages/types/src/server-fault-log-cause.test.ts b/packages/types/src/server-fault-log-cause.test.ts new file mode 100644 index 00000000000..d8a2b6a8d97 --- /dev/null +++ b/packages/types/src/server-fault-log-cause.test.ts @@ -0,0 +1,214 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The 5xx fault line prints the thrown value's `cause` chain. + * + * A producer that wraps an original on `cause` hands the door its own + * sentence; the original is the operator's. The line used to print the + * wrapper alone, so a wrapped fault logged without its root cause. These pin + * the console fallback (the sink `sendError` / `sendServerFault` and an + * un-wired door reach), the bounds (a cycle, a deep chain), the hand-off to an + * injected logger (which renders the chain itself, so the line never carries + * it twice), and the wire (which carries none of it). + */ + +import { describe, it, expect, vi } from 'vitest'; + +import { logServerFault, faultCauseChain, FAULT_CAUSE_DEPTH_LIMIT, SERVER_FAULT_LOG_PREFIX } from './server-fault-log.js'; +import { sendServerFault } from './response-envelope.js'; + +/** `new Error(message, { cause })` without the ES2022 lib this package does not compile against. */ +const withCause = (message: string, cause: unknown): Error => Object.assign(new Error(message), { cause }); + +const ROOT = 'SQLITE_IOERR: disk I/O error reading policy_revision.version'; +const MID = 'driver read failed for policy_revision'; +const OUTER = 'The related records of policy could not be read.'; + +/** wrapper → mid → root, the shape a door wraps a driver error in. */ +const wrapped = () => withCause(OUTER, withCause(MID, new Error(ROOT))); + +const faultLines = (spy: { mock: { calls: unknown[][] } }) => + spy.mock.calls.filter((c) => String(c[0]).startsWith(SERVER_FAULT_LOG_PREFIX)); + +describe('logServerFault — the console fallback prints the cause chain', () => { + it('logs each cause\'s message and stack, outermost first', () => { + const spy = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + logServerFault({ status: 500, code: 'INTERNAL_ERROR', error: wrapped() }); + const lines = faultLines(spy); + expect(lines).toHaveLength(1); + const meta = lines[0][1] as { stack?: string; causes?: Array<{ message: string; stack?: string }> }; + expect(meta.stack).toContain(OUTER); + expect(meta.causes).toHaveLength(2); + expect(meta.causes?.[0].message).toBe(`Error: ${MID}`); + expect(meta.causes?.[0].stack).toContain(MID); + expect(meta.causes?.[1].message).toBe(`Error: ${ROOT}`); + expect(meta.causes?.[1].stack).toContain(ROOT); + } finally { + spy.mockRestore(); + } + }); + + it('CONTROL — an error with no cause carries no causes field', () => { + const spy = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + logServerFault({ status: 500, error: new Error(OUTER) }); + const meta = faultLines(spy)[0][1] as Record; + expect(meta).not.toHaveProperty('causes'); + } finally { + spy.mockRestore(); + } + }); + + it('a declared capability absence (warn, no throw) carries none either', () => { + const spy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + logServerFault({ + status: 501, + code: 'NOT_IMPLEMENTED', + error: wrapped(), + request: { method: 'GET', path: '/api/v1/cause-chain-absence-probe' }, + }); + const meta = spy.mock.calls[0][1] as Record; + expect(meta).not.toHaveProperty('causes'); + } finally { + spy.mockRestore(); + } + }); +}); + +describe('faultCauseChain — bounded both ways', () => { + it('stops a cycle at its first repeat, and says so', () => { + const a = new Error('a'); + const b = withCause('b', a); + (a as { cause?: unknown }).cause = b; + const chain = faultCauseChain(a); + expect(chain.map((l) => l.message)).toEqual([ + 'Error: b', + '[cause chain cycle: this link repeats an earlier one]', + ]); + }); + + it('stops a self-cause at once', () => { + const self = new Error('self'); + (self as { cause?: unknown }).cause = self; + expect(faultCauseChain(self)).toEqual([{ message: '[cause chain cycle: this link repeats an earlier one]' }]); + }); + + it(`stops a deep chain after ${FAULT_CAUSE_DEPTH_LIMIT} links, and says so`, () => { + let error = new Error('link 0'); + for (let i = 1; i <= 20; i += 1) error = withCause(`link ${i}`, error); + const chain = faultCauseChain(error); + expect(chain).toHaveLength(FAULT_CAUSE_DEPTH_LIMIT + 1); + expect(chain.slice(0, FAULT_CAUSE_DEPTH_LIMIT).map((l) => l.message)).toEqual( + ['link 19', 'link 18', 'link 17', 'link 16', 'link 15'].map((m) => `Error: ${m}`), + ); + expect(chain[FAULT_CAUSE_DEPTH_LIMIT]).toEqual({ message: `[cause chain truncated after ${FAULT_CAUSE_DEPTH_LIMIT} links]` }); + }); + + it('prints a non-Error cause as its text, and ends the chain there', () => { + expect(faultCauseChain(withCause('w', 'socket hang up'))).toEqual([{ message: 'socket hang up' }]); + expect(faultCauseChain(withCause('w', { code: 'ECONNRESET' }))).toEqual([{ message: '{"code":"ECONNRESET"}' }]); + }); + + it('a throwing cause getter ends the chain rather than costing the line', () => { + const hostile = new Error('w'); + Object.defineProperty(hostile, 'cause', { get() { throw new Error('getter'); } }); + expect(faultCauseChain(hostile)).toEqual([]); + expect(faultCauseChain('a string throw')).toEqual([]); + expect(faultCauseChain(undefined)).toEqual([]); + }); + + it('a link whose message read throws ends the chain in a marker, and the line is still written', () => { + const unreadable = new Error('unreadable'); + Object.defineProperty(unreadable, 'message', { get() { throw new Error('getter'); } }); + const outer = withCause(OUTER, withCause(MID, unreadable)); + expect(faultCauseChain(outer)).toEqual([ + expect.objectContaining({ message: `Error: ${MID}` }), + { message: '[cause chain link unreadable: reading it threw]' }, + ]); + const spy = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + expect(logServerFault({ status: 500, error: outer })).toBe(true); + const meta = faultLines(spy)[0][1] as { causes?: Array<{ message: string }> }; + expect(meta.causes?.[1]).toEqual({ message: '[cause chain link unreadable: reading it threw]' }); + } finally { + spy.mockRestore(); + } + }); +}); + +describe('a cause is redacted like the error', () => { + it('an object cause', () => { + const chain = faultCauseChain(withCause('w', { code: 'ECONNRESET', password: 'hunter2', apiKey: 'sk-live-1', nested: { authToken: 't-1' } })); + expect(chain).toHaveLength(1); + expect(JSON.parse(chain[0].message)).toEqual({ + code: 'ECONNRESET', + password: '***REDACTED***', + apiKey: '***REDACTED***', + nested: { authToken: '***REDACTED***' }, + }); + for (const value of ['hunter2', 'sk-live-1', 't-1']) expect(chain[0].message).not.toContain(value); + }); + + it('by whole words, as the logger matches its redact list', () => { + const [line] = faultCauseChain(withCause('w', { + keys: ['a'], tokens: 3, monkey: 'm', keyword: 'k', secretary: 's', + apiKey: 'x', apikey: 'x', refresh_tokens: ['x'], password: 'x', + })); + expect(JSON.parse(line.message)).toEqual({ + keys: ['a'], tokens: 3, monkey: 'm', keyword: 'k', secretary: 's', + apiKey: '***REDACTED***', apikey: '***REDACTED***', refresh_tokens: '***REDACTED***', password: '***REDACTED***', + }); + }); + + it('inside an array in an object cause', () => { + const [line] = faultCauseChain(withCause('w', { attempts: [{ host: 'db-1', password: 'x' }, { host: 'db-2' }] })); + expect(JSON.parse(line.message)).toEqual({ attempts: [{ host: 'db-1', password: '***REDACTED***' }, { host: 'db-2' }] }); + }); + + it('on the console fallback line', () => { + const spy = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + logServerFault({ status: 500, error: withCause(OUTER, { password: 'hunter2' }) }); + const meta = faultLines(spy)[0][1] as { causes?: Array<{ message: string }> }; + expect(meta.causes).toEqual([{ message: '{"password":"***REDACTED***"}' }]); + } finally { + spy.mockRestore(); + } + }); +}); + +describe('logServerFault — an injected logger renders the chain itself', () => { + it('hands the logger the thrown error with its cause intact, and no second copy in meta', () => { + const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn(), child: vi.fn() }; + const thrown = wrapped(); + logServerFault({ status: 500, error: thrown }, logger as never); + expect(logger.error).toHaveBeenCalledTimes(1); + const [, err, meta] = logger.error.mock.calls[0]; + expect(err).toBe(thrown); + expect((err as { cause?: unknown }).cause).toBeInstanceOf(Error); + expect(meta).not.toHaveProperty('causes'); + }); +}); + +describe('the wire carries no cause text', () => { + it('sendServerFault answers the generic envelope while the line carries the root cause', () => { + const spy = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + const res: any = { + statusCode: undefined as number | undefined, + body: undefined as unknown, + status(c: number) { res.statusCode = c; return res; }, + json(b: unknown) { res.body = b; return res; }, + }; + sendServerFault(res, 500, 'INTERNAL_ERROR', 'Internal server error', wrapped()); + expect(res.body).toEqual({ success: false, error: { code: 'INTERNAL_ERROR', message: 'Internal server error' } }); + for (const word of [ROOT, MID, OUTER, 'causes', 'SQLITE']) expect(JSON.stringify(res.body)).not.toContain(word); + const meta = faultLines(spy)[0][1] as { causes?: Array<{ message: string }> }; + expect(meta.causes?.[1].message).toBe(`Error: ${ROOT}`); + } finally { + spy.mockRestore(); + } + }); +}); diff --git a/packages/types/src/server-fault-log.ts b/packages/types/src/server-fault-log.ts index ebe01d09572..bc383a4fd5a 100644 --- a/packages/types/src/server-fault-log.ts +++ b/packages/types/src/server-fault-log.ts @@ -275,6 +275,188 @@ function safeStringify(value: unknown): string { } } +/** One link of an error's `cause` chain, as an operator's fault line prints it. */ +export interface FaultCauseLine { + message: string; + /** Absent when the cause was not an `Error`, or carried none. */ + stack?: string; +} + +/** + * How many `cause` links a fault line prints before it says it stopped. A + * wrapper around a wrapper around a driver error is three; past five the + * chain is a loop in all but name, and the line must stay one line. + */ +export const FAULT_CAUSE_DEPTH_LIMIT = 5; + +/** + * The `cause` chain under a thrown value, outermost first, for the fault log. + * + * A producer that wraps an original on `cause` (`new Error(say, { cause })`) + * hands the door a sentence the caller may read; the original is the + * operator's. The line used to print the wrapper's message and stack only, so + * the root cause of every wrapped fault was missing from the one place an + * operator looks. Each link is its message and stack, so the line reads the + * way Node's own `Caused by:` rendering does, as data a JSON sink can index. + * + * Bounded both ways: a cycle (`a.cause = b; b.cause = a`) stops at the first + * repeat, and a chain deeper than {@link FAULT_CAUSE_DEPTH_LIMIT} stops there; + * either says so in a last link, so a cut chain never reads as a whole one. + * A link whose read throws ends the chain in a marker link too. + * + * A non-Error object cause is serialized with `isRedacted` applied key by + * key, at every depth. The default is `ObjectLogger`'s own rule over its + * default redact list (`LoggerConfig.redact`'s default words, whole-word + * matched). ⚠️ Only the default words: the console fallback has no logger + * config, so a host's own `redact` list is not applied to the line it writes; + * a door handed a configured logger gets that logger's list instead. + * + * ⛔ Operator-only. It feeds the log line; no door puts it on the wire, and a + * 5xx answer withholds even the wrapper's own sentence. + * + * `@objectstack/core`'s `ObjectLogger` renders the same shape for every + * `logger.error(message, err)`. It keeps its own copy because its `./logger` + * entry is browser-safe and bundled by `@objectstack/client`, which does not + * depend on this package; `logger-error-cause.test.ts` there pins the two to + * the same output. + */ +export function faultCauseChain( + thrown: unknown, + isRedacted: (key: string) => boolean = isDefaultRedactedFieldName, +): FaultCauseLine[] { + const limit = FAULT_CAUSE_DEPTH_LIMIT; + const lines: FaultCauseLine[] = []; + const seen = new Set([thrown]); + let current = causeOf(thrown); + while (current !== undefined && current !== null) { + if (seen.has(current)) { + lines.push({ message: '[cause chain cycle: this link repeats an earlier one]' }); + break; + } + if (lines.length >= limit) { + lines.push({ message: `[cause chain truncated after ${limit} links]` }); + break; + } + seen.add(current); + try { + lines.push(causeLine(current, isRedacted)); + } catch { + // A link whose name, message or stack read throws (a hostile getter, a Proxy) + // ends the chain in a marker; it must not cost the whole line. + lines.push({ message: '[cause chain link unreadable: reading it threw]' }); + break; + } + current = causeOf(current); + } + return lines; +} + +function causeOf(value: unknown): unknown { + if (typeof value !== 'object' || value === null) return undefined; + try { + return (value as { cause?: unknown }).cause; + } catch { + // A throwing `cause` getter ends the chain; it must not cost the line. + return undefined; + } +} + +/** + * `LoggerConfig.redact`'s default words (`@objectstack/spec` `logging.zod.ts`), + * which `ObjectLogger` also applies when it is given none. + */ +const DEFAULT_REDACTED_WORDS = ['password', 'token', 'secret', 'key'] as const; + +/** + * The default field-name rule, matched the way `ObjectLogger` matches its + * redact list: on word boundaries, the maintainer's ruling on #5573, so a bare + * `keys` / `tokens` or a `monkey` / `keyword` / `secretary` is not withheld, + * while `apiKey`, `refresh_tokens` and `accesstoken` are. + * + * A copy of `@objectstack/core`'s matcher (`tokenizeFieldName` and + * `fieldWordsMatchPattern` in `logger.ts`), for the same reason + * {@link faultCauseChain} is one; `logger-error-cause.test.ts` there runs a + * fixture of these spellings through both and fails on any drift. + */ +function isDefaultRedactedFieldName(key: string): boolean { + const nameWords = tokenizeFieldName(key); + return DEFAULT_REDACTED_WORDS.some((word) => fieldWordsMatchPattern(nameWords, [word])); +} + +function tokenizeFieldName(name: string): string[] { + return name + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') + .replace(/([a-zA-Z])([0-9])/g, '$1 $2') + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + .map((word) => word.toLowerCase()); +} + +function singularizeWord(word: string): string { + if (/(?:ss|us|is)$/.test(word)) return word; + if (/(?:ch|sh|s|x|z)es$/.test(word)) return word.slice(0, -2); + if (/[a-z0-9]s$/.test(word)) return word.slice(0, -1); + return word; +} + +/** Glued qualifiers that mark the secret sense: `apikey`, `accesstoken`, `clientsecret`. */ +const CONCATENATED_SECRET_QUALIFIERS = new Set([ + 'access', 'account', 'admin', 'api', 'app', 'auth', 'bearer', 'client', 'csrf', 'db', 'database', + 'encryption', 'id', 'jwt', 'master', 'oauth', 'private', 'public', 'refresh', 'root', 'secret', + 'service', 'session', 'shared', 'sign', 'signing', 'ssh', 'token', 'user', 'webhook', 'xsrf', +]); + +function isQualifiedConcatenation(word: string, redactWord: string): boolean { + for (const base of [word, singularizeWord(word)]) { + if (base.length <= redactWord.length || !base.endsWith(redactWord)) continue; + if (CONCATENATED_SECRET_QUALIFIERS.has(base.slice(0, base.length - redactWord.length))) return true; + } + return false; +} + +function containsWordRun(words: string[], run: string[]): boolean { + for (let i = 0; i + run.length <= words.length; i++) { + if (run.every((word, offset) => words[i + offset] === word)) return true; + } + return false; +} + +function fieldWordsMatchPattern(nameWords: string[], patternWords: string[]): boolean { + if (patternWords.length === 0 || nameWords.length === 0) return false; + if (patternWords.length > 1) { + const glued = patternWords.join(''); + return ( + containsWordRun(nameWords, patternWords) || + nameWords.some((word) => word === glued || singularizeWord(word) === glued) + ); + } + const redactWord = patternWords[0]; + const isCompound = nameWords.filter((word) => /[a-z]/.test(word)).length > 1; + return nameWords.some( + (word) => + word === redactWord || + (isCompound && singularizeWord(word) === redactWord) || + isQualifiedConcatenation(word, redactWord), + ); +} + +function causeLine(cause: unknown, isRedacted: (key: string) => boolean): FaultCauseLine { + if (cause instanceof Error) { + return { + message: `${cause.name}: ${cause.message}`, + ...(cause.stack ? { stack: cause.stack } : {}), + }; + } + if (typeof cause === 'string') return { message: cause }; + try { + const text = JSON.stringify(cause, (key, value) => (key !== '' && isRedacted(key) ? '***REDACTED***' : value)); + return { message: text ?? String(cause) }; + } catch { + return { message: String(cause) }; + } +} + /** * The human half of the line: `[5xx] 500 GET /api/v1/packages — `. * Split out so both the emitted record and a test can name the same string. @@ -321,6 +503,11 @@ export function serverFaultLogMeta(input: ServerFaultLogInput): Record 0 ? { causes } : {}), + }); + } return true; } catch { // Log emission must never throw — the original fault is still answered.