@elisra-devops/docgen-skins 0.28.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/ci.yml +2 -0
- package/bin/index.js +8 -3
- package/bin/index.js.map +1 -1
- package/bin/models/json/table/JSONTableCell.js +4 -3
- package/bin/models/json/table/JSONTableCell.js.map +1 -1
- package/bin/services/logSink.d.ts +25 -0
- package/bin/services/logSink.js +16 -0
- package/bin/services/logSink.js.map +1 -0
- package/bin/services/logger.d.ts +6 -0
- package/bin/services/logger.js +212 -16
- package/bin/services/logger.js.map +1 -1
- package/bin/services/runContext.d.ts +7 -0
- package/bin/services/runContext.js +12 -0
- package/bin/services/runContext.js.map +1 -0
- package/bin/test/logger.test.d.ts +1 -0
- package/bin/test/logger.test.js +272 -0
- package/bin/test/logger.test.js.map +1 -0
- package/bin/test/runContext.test.d.ts +1 -0
- package/bin/test/runContext.test.js +96 -0
- package/bin/test/runContext.test.js.map +1 -0
- package/eslint.config.mjs +40 -0
- package/package.json +8 -3
- package/src/index.ts +8 -5
- package/src/models/json/table/JSONTableCell.ts +4 -3
- package/src/services/logSink.ts +44 -0
- package/src/services/logger.ts +220 -17
- package/src/services/runContext.ts +22 -0
- package/src/test/logger.test.ts +268 -0
- package/src/test/runContext.test.ts +48 -0
package/src/services/logger.ts
CHANGED
|
@@ -1,26 +1,229 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
import * as winston from "winston";
|
|
3
|
+
import * as fs from "fs";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
import Transport from "winston-transport";
|
|
6
|
+
import { runContextStore } from "./runContext";
|
|
7
|
+
import { getLogSink, DiagnosticEvent } from "./logSink";
|
|
3
8
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
9
|
+
// Merges the ambient runId (set by content-control's request middleware, once Phase 3 lands
|
|
10
|
+
// there) into every log record. A never-populated store is a harmless no-op — this package
|
|
11
|
+
// only reads it, never sets it.
|
|
12
|
+
export const withRunContext = winston.format((info) => {
|
|
13
|
+
const store = runContextStore.getStore();
|
|
14
|
+
if (store?.runId) (info as Record<string, unknown>).runId = store.runId;
|
|
15
|
+
// Phase 7b — same ambient, per-run treatment as runId.
|
|
16
|
+
if (store?.docType) (info as Record<string, unknown>).docType = store.docType;
|
|
17
|
+
return info;
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
// Defense-in-depth: scrubs known-sensitive keys out of any object attached to a log
|
|
21
|
+
// call (meta, splat, an Error's own enumerable props). Does not redact secrets
|
|
22
|
+
// interpolated into a message string — that's the corresponding call-site fixes' job;
|
|
23
|
+
// this is a backstop for structured fields.
|
|
24
|
+
// "accesskey" (not just "minioaccesskey") so this also catches an *AccessKeyId-style field —
|
|
25
|
+
// a real gap found in api-gate's copy during the Phase 5 manifest work: only the *SecretKey
|
|
26
|
+
// sibling was covered before, via "secret". Applied here too to keep the four copies in sync.
|
|
27
|
+
const SENSITIVE_KEY = /token|pat|password|secret|authorization|accesskey|minioaccesskey|miniosecretkey/i;
|
|
28
|
+
|
|
29
|
+
// A per-key try/catch on the *read*, not just around the whole loop: a getter that throws
|
|
30
|
+
// (e.g. `{ get boom() { throw ... } }`) would otherwise abort redaction for every remaining
|
|
31
|
+
// key in the same object, or — worse — survive redaction untouched and re-throw later, inside
|
|
32
|
+
// winston's json() formatter, which is not wrapped in anything. redactValue always returns a
|
|
33
|
+
// freshly built plain object/array, never the original reference, so once a value has passed
|
|
34
|
+
// through here nothing downstream can re-trigger a throwing accessor on it.
|
|
35
|
+
function safeRead(obj: Record<string, unknown>, key: string): { ok: true; value: unknown } | { ok: false } {
|
|
36
|
+
try {
|
|
37
|
+
return { ok: true, value: obj[key] };
|
|
38
|
+
} catch {
|
|
39
|
+
return { ok: false };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function redactValue(value: unknown, depth = 0, seen = new WeakSet<object>()): unknown {
|
|
43
|
+
if (depth > 6 || value === null || typeof value !== "object") return value;
|
|
44
|
+
if (seen.has(value as object)) return "[Circular]";
|
|
45
|
+
seen.add(value as object);
|
|
46
|
+
if (Array.isArray(value)) return value.map((v) => redactValue(v, depth + 1, seen));
|
|
47
|
+
const out: Record<string, unknown> = {};
|
|
48
|
+
for (const key of Object.keys(value as Record<string, unknown>)) {
|
|
49
|
+
const read = safeRead(value as Record<string, unknown>, key);
|
|
50
|
+
if (!read.ok) {
|
|
51
|
+
out[key] = "[Unreadable property]";
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
out[key] = SENSITIVE_KEY.test(key) ? "[REDACTED]" : redactValue(read.value, depth + 1, seen);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
export const redact = winston.format((info) => {
|
|
59
|
+
const target = info as Record<string, unknown>;
|
|
60
|
+
for (const key of Object.keys(target)) {
|
|
61
|
+
// level/timestamp are always plain strings winston sets itself — never touched. message is
|
|
62
|
+
// NOT exempt: when logger.error(x) is called with a single non-string/non-Error argument,
|
|
63
|
+
// winston nests the whole thing under info.message (this is exactly the shape hit by a raw
|
|
64
|
+
// object argument), so message can carry a throwing getter or a sensitive key just as much
|
|
65
|
+
// as any other field — redactValue already no-ops on a plain string, so including it here
|
|
66
|
+
// costs nothing for the common case and closes that gap for the uncommon one.
|
|
67
|
+
if (key === "level" || key === "timestamp") continue;
|
|
68
|
+
const read = safeRead(target, key);
|
|
69
|
+
const value = !read.ok
|
|
70
|
+
? "[Unreadable property]"
|
|
71
|
+
: // A top-level primitive (e.g. token: "abc") has no children for redactValue to walk into —
|
|
72
|
+
// the key itself has to be checked here too, not just inside the recursive object walk.
|
|
73
|
+
SENSITIVE_KEY.test(key)
|
|
74
|
+
? "[REDACTED]"
|
|
75
|
+
: redactValue(read.value);
|
|
76
|
+
try {
|
|
77
|
+
target[key] = value;
|
|
78
|
+
} catch {
|
|
79
|
+
// The original property could be a getter-only accessor with no setter, which throws on
|
|
80
|
+
// plain assignment in strict mode — redefine it outright rather than skip it.
|
|
81
|
+
Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return info;
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// Resolves the package's own version for defaultMeta.
|
|
88
|
+
function readOwnVersion(): string {
|
|
89
|
+
const candidates = [
|
|
90
|
+
path.resolve(__dirname, "../package.json"),
|
|
91
|
+
path.resolve(__dirname, "../../package.json"),
|
|
92
|
+
path.resolve(process.cwd(), "package.json"),
|
|
93
|
+
];
|
|
94
|
+
for (const candidate of candidates) {
|
|
95
|
+
try {
|
|
96
|
+
if (!fs.existsSync(candidate)) continue;
|
|
97
|
+
return JSON.parse(fs.readFileSync(candidate, "utf8")).version || "unknown";
|
|
98
|
+
} catch {
|
|
99
|
+
// try next candidate
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return "unknown";
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// A template literal's implicit ToString throws on a Symbol value (unlike String(), which
|
|
106
|
+
// calls Symbol.prototype.toString() explicitly) — logger.error(Symbol('x')) would otherwise
|
|
107
|
+
// crash inside this formatter itself, the one place in the pipeline with no try/catch around
|
|
108
|
+
// it. Symbol.toString() itself never throws, so this needs no further guarding.
|
|
109
|
+
const safeMessageString = (value: unknown): string =>
|
|
110
|
+
typeof value === "symbol" ? value.toString() : String(value);
|
|
111
|
+
|
|
112
|
+
const textFormat = winston.format.printf(
|
|
113
|
+
info => `${info.timestamp} - ${info.level}: ${safeMessageString(info.message)}`
|
|
7
114
|
);
|
|
8
115
|
|
|
116
|
+
// Bounded so one oversized message/stack can't produce an unbounded LogEvent document.
|
|
117
|
+
const MAX_MESSAGE_LEN = 2000;
|
|
118
|
+
const MAX_STACK_LEN = 4000;
|
|
119
|
+
function clamp(value: unknown, max: number): string | undefined {
|
|
120
|
+
if (typeof value !== "string") return undefined;
|
|
121
|
+
return value.length > max ? value.slice(0, max) : value;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Ships warn/error records to whatever LogSink the host process (docgen-content-control's
|
|
125
|
+
// index.ts) has installed — this package never installs one itself, only reads it. Reads
|
|
126
|
+
// info *after* the rest of the format chain has already run — redact() has already scrubbed
|
|
127
|
+
// it by the time this transport sees it. Never throws, never blocks the call path, and never
|
|
128
|
+
// logs through `logger` itself (that would recurse back into this same transport) — failures
|
|
129
|
+
// go to console.error only.
|
|
130
|
+
const DIAGNOSTICS_CAPTURE_ENABLED = (process.env.DIAGNOSTICS_CAPTURE_ENABLED || "true").toLowerCase() !== "false";
|
|
131
|
+
// Exported for tests, the same treatment as redact()/withRunContext() — so a test pipeline
|
|
132
|
+
// can exercise this transport without going through the real singleton logger's env-gated
|
|
133
|
+
// json()/textFormat branch.
|
|
134
|
+
export class DiagnosticsTransport extends Transport {
|
|
135
|
+
log(info: Record<string, unknown>, callback: () => void): void {
|
|
136
|
+
setImmediate(() => this.emit("logged", info));
|
|
137
|
+
try {
|
|
138
|
+
const level = info.level;
|
|
139
|
+
const isWarnOrError = level === "warn" || level === "error";
|
|
140
|
+
// Phase 6b — the logger's own level gate is now 'debug' (see createLogger below), so a
|
|
141
|
+
// debug/info call reaches this transport regardless of mode; this is the one place that
|
|
142
|
+
// decides whether it's actually persisted, keyed off the per-run capture mode rather
|
|
143
|
+
// than a process-wide setting — concurrent runs in 'normal' mode are unaffected by a
|
|
144
|
+
// sibling run's 'verbose'/'retain-on-failure' opt-in.
|
|
145
|
+
const captureMode = runContextStore.getStore()?.captureMode;
|
|
146
|
+
const isCapturedDebugOrInfo =
|
|
147
|
+
(level === "debug" || level === "info") && (captureMode === "verbose" || captureMode === "retain-on-failure");
|
|
148
|
+
if (DIAGNOSTICS_CAPTURE_ENABLED && (isWarnOrError || isCapturedDebugOrInfo)) {
|
|
149
|
+
// winston.errors({stack:true}) merges an Error's own enumerable properties (stack,
|
|
150
|
+
// and anything else the call site set, e.g. `err.code`) directly onto `info` — there
|
|
151
|
+
// is no separate nested info.err. `info.stack`'s presence is the only reliable signal
|
|
152
|
+
// that this record came from `logger.error('...', err)`/`logger.error(err)` rather
|
|
153
|
+
// than a plain string message. When present, info.message is already the
|
|
154
|
+
// stable-message-plus-error-message string winston produced, so err.message reuses it.
|
|
155
|
+
const hasErr = typeof info.stack === "string";
|
|
156
|
+
const message = clamp(info.message, MAX_MESSAGE_LEN) ?? "";
|
|
157
|
+
const event: DiagnosticEvent = {
|
|
158
|
+
ts: typeof info.timestamp === "string" ? info.timestamp : new Date().toISOString(),
|
|
159
|
+
level: String(info.level),
|
|
160
|
+
service: String(info.service ?? "@elisra-devops/docgen-skins"),
|
|
161
|
+
version: String(info.version ?? "unknown"),
|
|
162
|
+
runId: typeof info.runId === "string" ? info.runId : undefined,
|
|
163
|
+
docType: typeof info.docType === "string" ? info.docType : undefined,
|
|
164
|
+
step: typeof info.step === "string" ? info.step : undefined,
|
|
165
|
+
contentControlType: typeof info.contentControlType === "string" ? info.contentControlType : undefined,
|
|
166
|
+
contentControlTitle: typeof info.contentControlTitle === "string" ? info.contentControlTitle : undefined,
|
|
167
|
+
project: typeof info.project === "string" ? info.project : undefined,
|
|
168
|
+
userId: typeof info.userId === "string" ? info.userId : undefined,
|
|
169
|
+
message,
|
|
170
|
+
err: hasErr
|
|
171
|
+
? {
|
|
172
|
+
message,
|
|
173
|
+
code: typeof info.code === "string" ? info.code : undefined,
|
|
174
|
+
stack: clamp(info.stack, MAX_STACK_LEN),
|
|
175
|
+
}
|
|
176
|
+
: undefined,
|
|
177
|
+
retainPending: !isWarnOrError && captureMode === "retain-on-failure" ? true : undefined,
|
|
178
|
+
};
|
|
179
|
+
getLogSink()?.push(event);
|
|
180
|
+
}
|
|
181
|
+
} catch (e) {
|
|
182
|
+
// eslint-disable-next-line no-console
|
|
183
|
+
console.error("DiagnosticsTransport failed to push event", e);
|
|
184
|
+
}
|
|
185
|
+
callback();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// LOG_FORMAT=json is the eventual default (structured stdout a collector can parse), but
|
|
190
|
+
// stays opt-in for one release so switching is a config change, not an image rebuild, if
|
|
191
|
+
// anyone reading raw console output needs to roll back.
|
|
192
|
+
const useJson = (process.env.LOG_FORMAT || "text").toLowerCase() === "json";
|
|
193
|
+
|
|
194
|
+
// Phase 6b — the Logger's own level gate must be 'debug' (winston's most permissive) so a
|
|
195
|
+
// debug/info call always reaches every transport's log(); a static per-logger level can't
|
|
196
|
+
// depend on the ALS store's per-run capture mode, so DiagnosticsTransport has to be the one
|
|
197
|
+
// deciding what's actually persisted. The Console transport below gets its own explicit
|
|
198
|
+
// level so stdout's default behavior (info/warn/error unless LOG_LEVEL=debug) is unchanged —
|
|
199
|
+
// this only spends the format-chain cost on debug() calls that previously short-circuited
|
|
200
|
+
// for free; info/warn/error volume (Phase 4's focus) is unaffected either way.
|
|
201
|
+
const CONSOLE_LOG_LEVEL = process.env.LOG_LEVEL || "info";
|
|
202
|
+
|
|
9
203
|
const logger: winston.Logger = winston.createLogger({
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
204
|
+
level: "debug",
|
|
205
|
+
defaultMeta: { service: "@elisra-devops/docgen-skins", version: readOwnVersion() },
|
|
206
|
+
format: useJson
|
|
207
|
+
? winston.format.combine(
|
|
208
|
+
winston.format.errors({ stack: true }),
|
|
209
|
+
winston.format.timestamp(),
|
|
210
|
+
withRunContext(),
|
|
211
|
+
redact(),
|
|
212
|
+
winston.format.splat(),
|
|
213
|
+
winston.format.json()
|
|
214
|
+
)
|
|
215
|
+
: winston.format.combine(
|
|
216
|
+
winston.format.errors({ stack: true }),
|
|
217
|
+
winston.format.timestamp(),
|
|
218
|
+
withRunContext(),
|
|
219
|
+
redact(),
|
|
220
|
+
winston.format.splat(),
|
|
221
|
+
textFormat
|
|
222
|
+
),
|
|
223
|
+
// Stdout only — no File transports, consistent with the other DocGen services (no mounted
|
|
224
|
+
// log volume anywhere in this deployment, so a File transport is invisible to `kubectl logs`
|
|
225
|
+
// and can throw at import time under a read-only root filesystem).
|
|
226
|
+
transports: [new winston.transports.Console({ level: CONSOLE_LOG_LEVEL }), new DiagnosticsTransport()]
|
|
24
227
|
});
|
|
25
228
|
|
|
26
229
|
export default logger;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
3
|
+
|
|
4
|
+
export interface RunContext {
|
|
5
|
+
runId: string;
|
|
6
|
+
// Phase 6b — this package never sets it, only reads it: content-control (the host process
|
|
7
|
+
// this package runs in-process inside) populates it via its own attachRunContext, and this
|
|
8
|
+
// package's DiagnosticsTransport reads the same in-process ALS store.
|
|
9
|
+
captureMode?: 'verbose' | 'retain-on-failure';
|
|
10
|
+
// Phase 7b — same read-only treatment as captureMode above.
|
|
11
|
+
docType?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Symbol.for uses the global symbol registry, so every duplicated copy of this file across
|
|
15
|
+
// the DocGen packages — hoisted or nested at any depth by npm — converges on the same
|
|
16
|
+
// AsyncLocalStorage instance. Keying by module identity instead would silently split into
|
|
17
|
+
// two stores and runId would go missing with no visible error.
|
|
18
|
+
const KEY = Symbol.for("elisradevops.docgen.runContext");
|
|
19
|
+
|
|
20
|
+
export const runContextStore: AsyncLocalStorage<RunContext> =
|
|
21
|
+
((globalThis as Record<symbol, unknown>)[KEY] as AsyncLocalStorage<RunContext> | undefined) ??
|
|
22
|
+
((globalThis as Record<symbol, unknown>)[KEY] = new AsyncLocalStorage<RunContext>());
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import * as winston from 'winston';
|
|
2
|
+
import Transport from 'winston-transport';
|
|
3
|
+
import { redact, DiagnosticsTransport } from '../services/logger';
|
|
4
|
+
import { installLogSink, LogSink, DiagnosticEvent } from '../services/logSink';
|
|
5
|
+
import { runContextStore } from '../services/runContext';
|
|
6
|
+
|
|
7
|
+
const applyRedact = (info: Record<string, unknown>) => (redact() as any).transform({ ...info });
|
|
8
|
+
|
|
9
|
+
describe('logger redact format', () => {
|
|
10
|
+
test('scrubs a top-level token/password/secret regardless of key casing', () => {
|
|
11
|
+
const out = applyRedact({ level: 'info', message: 'x', token: 'abc', Password: 'p', SECRET: 's' });
|
|
12
|
+
expect(out.token).toBe('[REDACTED]');
|
|
13
|
+
expect(out.Password).toBe('[REDACTED]');
|
|
14
|
+
expect(out.SECRET).toBe('[REDACTED]');
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('scrubs nested config.auth.password and config.headers.Authorization — the AxiosError.toJSON() leak', () => {
|
|
18
|
+
const axiosLikeError = {
|
|
19
|
+
message: 'Request failed',
|
|
20
|
+
config: {
|
|
21
|
+
auth: { username: '', password: 'super-secret-pat' },
|
|
22
|
+
headers: { Authorization: 'Bearer abc.def.ghi' },
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
const out: any = applyRedact({ level: 'error', message: 'upstream failed', err: axiosLikeError });
|
|
26
|
+
expect(out.err.config.auth.password).toBe('[REDACTED]');
|
|
27
|
+
expect(out.err.config.headers.Authorization).toBe('[REDACTED]');
|
|
28
|
+
expect(out.err.message).toBe('Request failed');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('leaves non-sensitive fields untouched', () => {
|
|
32
|
+
const out = applyRedact({ level: 'info', message: 'ok', project: 'Cube-ADCS', docType: 'SVD' });
|
|
33
|
+
expect(out.project).toBe('Cube-ADCS');
|
|
34
|
+
expect(out.docType).toBe('SVD');
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('never throws on a circular object', () => {
|
|
38
|
+
const circular: any = { name: 'x' };
|
|
39
|
+
circular.self = circular;
|
|
40
|
+
expect(() => applyRedact({ level: 'info', message: 'x', circular })).not.toThrow();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('never throws and passes info through on null/undefined meta', () => {
|
|
44
|
+
expect(() => applyRedact({ level: 'info', message: 'x', meta: null })).not.toThrow();
|
|
45
|
+
expect(() => applyRedact({ level: 'info', message: 'x', meta: undefined })).not.toThrow();
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// A capturing transport + the exact JSON format chain logger.ts uses (errors -> timestamp ->
|
|
50
|
+
// redact -> splat -> json), so these tests exercise the real pipeline, not just redact() alone.
|
|
51
|
+
class CaptureTransport extends Transport {
|
|
52
|
+
lines: Record<string, unknown>[] = [];
|
|
53
|
+
log(info: Record<string, unknown>, callback: () => void) {
|
|
54
|
+
this.lines.push(JSON.parse((info as any)[Symbol.for('message')] ?? JSON.stringify(info)));
|
|
55
|
+
callback();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function makeTestLogger() {
|
|
59
|
+
const capture = new CaptureTransport();
|
|
60
|
+
const logger = winston.createLogger({
|
|
61
|
+
level: 'silly',
|
|
62
|
+
format: winston.format.combine(
|
|
63
|
+
winston.format.errors({ stack: true }),
|
|
64
|
+
winston.format.timestamp(),
|
|
65
|
+
redact(),
|
|
66
|
+
winston.format.splat(),
|
|
67
|
+
winston.format.json()
|
|
68
|
+
),
|
|
69
|
+
transports: [capture],
|
|
70
|
+
});
|
|
71
|
+
return { logger, capture };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
describe('logger pipeline — errors({stack:true})', () => {
|
|
75
|
+
test('logger.error(err) (single-arg Error) still produces a non-empty message and a stack', () => {
|
|
76
|
+
// This is the regression errors({stack:true}) exists to prevent: without it, winston's
|
|
77
|
+
// single-arg path makes `info` *be* the Error, and message/stack are non-enumerable, so
|
|
78
|
+
// json() would emit {"level":"error","timestamp":"…"} — content-free.
|
|
79
|
+
const { logger, capture } = makeTestLogger();
|
|
80
|
+
logger.error(new Error('boom'));
|
|
81
|
+
expect(capture.lines).toHaveLength(1);
|
|
82
|
+
expect(capture.lines[0].message).toBe('boom');
|
|
83
|
+
expect(typeof capture.lines[0].stack).toBe('string');
|
|
84
|
+
expect((capture.lines[0].stack as string).length).toBeGreaterThan(0);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe('logger pipeline — hostile inputs never throw', () => {
|
|
89
|
+
test.each([
|
|
90
|
+
['null', null],
|
|
91
|
+
['undefined', undefined],
|
|
92
|
+
['NaN', NaN],
|
|
93
|
+
['a circular object', (() => { const c: any = { a: 1 }; c.self = c; return c; })()],
|
|
94
|
+
['an object with a throwing getter', { get boom() { throw new Error('nope'); } }],
|
|
95
|
+
['a BigInt', BigInt(9007199254740993)],
|
|
96
|
+
['a Symbol', Symbol('x')],
|
|
97
|
+
['an Error with no message', new Error()],
|
|
98
|
+
['a 10MB string', 'x'.repeat(10 * 1024 * 1024)],
|
|
99
|
+
])('logger.error(%s) does not throw', (_label, value) => {
|
|
100
|
+
const { logger } = makeTestLogger();
|
|
101
|
+
expect(() => logger.error(value as any)).not.toThrow();
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
describe('DiagnosticsTransport (Phase 6a)', () => {
|
|
106
|
+
function makeDiagnosticsLogger() {
|
|
107
|
+
const capture = new CaptureTransport();
|
|
108
|
+
const logger = winston.createLogger({
|
|
109
|
+
level: 'silly',
|
|
110
|
+
format: winston.format.combine(
|
|
111
|
+
winston.format.errors({ stack: true }),
|
|
112
|
+
winston.format.timestamp(),
|
|
113
|
+
redact(),
|
|
114
|
+
winston.format.splat(),
|
|
115
|
+
winston.format.json()
|
|
116
|
+
),
|
|
117
|
+
transports: [capture, new DiagnosticsTransport()],
|
|
118
|
+
});
|
|
119
|
+
return { logger, capture };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
test('pushes warn/error records to whatever sink is installed', () => {
|
|
123
|
+
const events: DiagnosticEvent[] = [];
|
|
124
|
+
const sink: LogSink = { push: (e) => events.push(e) };
|
|
125
|
+
installLogSink(sink);
|
|
126
|
+
const { logger } = makeDiagnosticsLogger();
|
|
127
|
+
logger.warn('a stable warning');
|
|
128
|
+
logger.error('a stable error', Object.assign(new Error('boom'), { code: 'ECONN' }));
|
|
129
|
+
expect(events).toHaveLength(2);
|
|
130
|
+
expect(events[0].level).toBe('warn');
|
|
131
|
+
expect(events[1].err?.code).toBe('ECONN');
|
|
132
|
+
expect(events[1].err?.stack).toEqual(expect.any(String));
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('does not push info/debug records', () => {
|
|
136
|
+
const events: DiagnosticEvent[] = [];
|
|
137
|
+
installLogSink({ push: (e) => events.push(e) });
|
|
138
|
+
const { logger } = makeDiagnosticsLogger();
|
|
139
|
+
logger.info('not interesting to the dashboard');
|
|
140
|
+
expect(events).toHaveLength(0);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test('a throwing sink cannot break the log call', () => {
|
|
144
|
+
installLogSink({
|
|
145
|
+
push: () => {
|
|
146
|
+
throw new Error('sink is down');
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
const { logger } = makeDiagnosticsLogger();
|
|
150
|
+
expect(() => logger.error('still must not throw')).not.toThrow();
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test.each([
|
|
154
|
+
['null', null],
|
|
155
|
+
['undefined', undefined],
|
|
156
|
+
['NaN', NaN],
|
|
157
|
+
['a circular object', (() => { const c: any = { a: 1 }; c.self = c; return c; })()],
|
|
158
|
+
['an object with a throwing getter', { get boom() { throw new Error('nope'); } }],
|
|
159
|
+
['a BigInt', BigInt(9007199254740993)],
|
|
160
|
+
['a Symbol', Symbol('x')],
|
|
161
|
+
['an Error with no message', new Error()],
|
|
162
|
+
['a 10MB string', 'x'.repeat(10 * 1024 * 1024)],
|
|
163
|
+
])('logger.error(%s) with a sink installed does not throw', (_label, value) => {
|
|
164
|
+
installLogSink({ push: () => undefined });
|
|
165
|
+
const { logger } = makeDiagnosticsLogger();
|
|
166
|
+
expect(() => logger.error(value as any)).not.toThrow();
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
describe('textFormat safety (regression)', () => {
|
|
171
|
+
// The hostile-input matrix above exercises makeTestLogger()'s json() pipeline — it never
|
|
172
|
+
// touched the real singleton logger's text-format branch (LOG_FORMAT's default), which is
|
|
173
|
+
// where a Symbol message crashed: a template literal's implicit ToString throws on a Symbol,
|
|
174
|
+
// and this formatter sits with no try/catch around it.
|
|
175
|
+
test('logger.error(Symbol) does not throw through the real default-exported logger', () => {
|
|
176
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
177
|
+
const logger = require('../services/logger').default;
|
|
178
|
+
expect(() => logger.error(Symbol('x'))).not.toThrow();
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
describe('DiagnosticsTransport capture policy (Phase 6b)', () => {
|
|
183
|
+
function makeDiagnosticsLogger() {
|
|
184
|
+
const capture = new CaptureTransport();
|
|
185
|
+
const logger = winston.createLogger({
|
|
186
|
+
level: 'silly',
|
|
187
|
+
format: winston.format.combine(
|
|
188
|
+
winston.format.errors({ stack: true }),
|
|
189
|
+
winston.format.timestamp(),
|
|
190
|
+
redact(),
|
|
191
|
+
winston.format.splat(),
|
|
192
|
+
winston.format.json()
|
|
193
|
+
),
|
|
194
|
+
transports: [capture, new DiagnosticsTransport()],
|
|
195
|
+
});
|
|
196
|
+
return { logger, capture };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
test('normal mode (no captureMode) does not persist debug/info', () => {
|
|
200
|
+
const events: DiagnosticEvent[] = [];
|
|
201
|
+
installLogSink({ push: (e) => events.push(e) });
|
|
202
|
+
const { logger } = makeDiagnosticsLogger();
|
|
203
|
+
runContextStore.run({ runId: 'run-1' }, () => {
|
|
204
|
+
logger.debug('a debug line');
|
|
205
|
+
logger.info('an info line');
|
|
206
|
+
});
|
|
207
|
+
expect(events).toHaveLength(0);
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
test('verbose mode persists debug and info', () => {
|
|
211
|
+
const events: DiagnosticEvent[] = [];
|
|
212
|
+
installLogSink({ push: (e) => events.push(e) });
|
|
213
|
+
const { logger } = makeDiagnosticsLogger();
|
|
214
|
+
runContextStore.run({ runId: 'run-2', captureMode: 'verbose' }, () => {
|
|
215
|
+
logger.debug('a debug line');
|
|
216
|
+
logger.info('an info line');
|
|
217
|
+
});
|
|
218
|
+
expect(events).toHaveLength(2);
|
|
219
|
+
expect(events[0].retainPending).toBeUndefined();
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test('warn/error persist regardless of capture mode', () => {
|
|
223
|
+
const events: DiagnosticEvent[] = [];
|
|
224
|
+
installLogSink({ push: (e) => events.push(e) });
|
|
225
|
+
const { logger } = makeDiagnosticsLogger();
|
|
226
|
+
runContextStore.run({ runId: 'run-3' }, () => {
|
|
227
|
+
logger.warn('a warning');
|
|
228
|
+
logger.error('an error');
|
|
229
|
+
});
|
|
230
|
+
expect(events).toHaveLength(2);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
test('retain-on-failure persists debug/info tagged retainPending: true', () => {
|
|
234
|
+
const events: DiagnosticEvent[] = [];
|
|
235
|
+
installLogSink({ push: (e) => events.push(e) });
|
|
236
|
+
const { logger } = makeDiagnosticsLogger();
|
|
237
|
+
runContextStore.run({ runId: 'run-4', captureMode: 'retain-on-failure' }, () => {
|
|
238
|
+
logger.debug('a debug line');
|
|
239
|
+
});
|
|
240
|
+
expect(events).toHaveLength(1);
|
|
241
|
+
expect(events[0].retainPending).toBe(true);
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test('retain-on-failure does not tag warn/error as retainPending', () => {
|
|
245
|
+
const events: DiagnosticEvent[] = [];
|
|
246
|
+
installLogSink({ push: (e) => events.push(e) });
|
|
247
|
+
const { logger } = makeDiagnosticsLogger();
|
|
248
|
+
runContextStore.run({ runId: 'run-5', captureMode: 'retain-on-failure' }, () => {
|
|
249
|
+
logger.error('an error');
|
|
250
|
+
});
|
|
251
|
+
expect(events).toHaveLength(1);
|
|
252
|
+
expect(events[0].retainPending).toBeUndefined();
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
test('a concurrent normal-mode run is unaffected by a sibling verbose run', () => {
|
|
256
|
+
const events: DiagnosticEvent[] = [];
|
|
257
|
+
installLogSink({ push: (e) => events.push(e) });
|
|
258
|
+
const { logger } = makeDiagnosticsLogger();
|
|
259
|
+
runContextStore.run({ runId: 'verbose-run', captureMode: 'verbose' }, () => {
|
|
260
|
+
logger.debug('verbose debug');
|
|
261
|
+
});
|
|
262
|
+
runContextStore.run({ runId: 'normal-run' }, () => {
|
|
263
|
+
logger.debug('normal debug');
|
|
264
|
+
});
|
|
265
|
+
expect(events).toHaveLength(1);
|
|
266
|
+
expect(events[0].message).toBe('verbose debug');
|
|
267
|
+
});
|
|
268
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import * as winston from 'winston';
|
|
2
|
+
import Transport from 'winston-transport';
|
|
3
|
+
import { withRunContext } from '../services/logger';
|
|
4
|
+
import { runContextStore } from '../services/runContext';
|
|
5
|
+
|
|
6
|
+
class CaptureTransport extends Transport {
|
|
7
|
+
lines: Record<string, unknown>[] = [];
|
|
8
|
+
log(info: Record<string, unknown>, callback: () => void) {
|
|
9
|
+
this.lines.push(JSON.parse((info as any)[Symbol.for('message')] ?? JSON.stringify(info)));
|
|
10
|
+
callback();
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function makeTestLogger() {
|
|
14
|
+
const capture = new CaptureTransport();
|
|
15
|
+
const logger = winston.createLogger({
|
|
16
|
+
level: 'silly',
|
|
17
|
+
format: winston.format.combine(withRunContext(), winston.format.json()),
|
|
18
|
+
transports: [capture],
|
|
19
|
+
});
|
|
20
|
+
return { logger, capture };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe('withRunContext', () => {
|
|
24
|
+
test('is a no-op when the store was never populated', () => {
|
|
25
|
+
const { logger, capture } = makeTestLogger();
|
|
26
|
+
logger.info('outside any run');
|
|
27
|
+
expect(capture.lines[0].runId).toBeUndefined();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('stamps runId onto every log emitted inside store.run(...)', () => {
|
|
31
|
+
const { logger, capture } = makeTestLogger();
|
|
32
|
+
runContextStore.run({ runId: 'run-123' }, () => {
|
|
33
|
+
logger.info('inside the run');
|
|
34
|
+
});
|
|
35
|
+
logger.info('outside again');
|
|
36
|
+
expect(capture.lines[0].runId).toBe('run-123');
|
|
37
|
+
expect(capture.lines[1].runId).toBeUndefined();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('async work started inside the run keeps the runId across the await boundary', async () => {
|
|
41
|
+
const { logger, capture } = makeTestLogger();
|
|
42
|
+
await runContextStore.run({ runId: 'run-async' }, async () => {
|
|
43
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
44
|
+
logger.info('after await');
|
|
45
|
+
});
|
|
46
|
+
expect(capture.lines[0].runId).toBe('run-async');
|
|
47
|
+
});
|
|
48
|
+
});
|