268 lines
8.6 KiB
TypeScript
268 lines
8.6 KiB
TypeScript
import { Writable } from "node:stream";
|
|
import { describe, expect, it } from "vitest";
|
|
|
|
import { createChildLogger, createLogger, resolveLogLevel } from "./index.js";
|
|
|
|
function createLogSink() {
|
|
let buffer = "";
|
|
const records: Array<Record<string, unknown>> = [];
|
|
|
|
const stream = new Writable({
|
|
write(chunk, _encoding, callback) {
|
|
buffer += chunk.toString();
|
|
const lines = buffer.split("\n");
|
|
buffer = lines.pop() ?? "";
|
|
|
|
for (const line of lines) {
|
|
if (line.length > 0) {
|
|
records.push(JSON.parse(line) as Record<string, unknown>);
|
|
}
|
|
}
|
|
|
|
callback();
|
|
},
|
|
});
|
|
|
|
return { records, stream };
|
|
}
|
|
|
|
describe("@hivegrid/logger", () => {
|
|
it("uses HIVEGRID_LOG_LEVEL before LOG_LEVEL and falls back to info", () => {
|
|
expect(resolveLogLevel({ HIVEGRID_LOG_LEVEL: "debug", LOG_LEVEL: "warn" })).toBe("debug");
|
|
expect(resolveLogLevel({ LOG_LEVEL: "warn" })).toBe("warn");
|
|
expect(resolveLogLevel({})).toBe("info");
|
|
});
|
|
|
|
it("creates structured logs without base pid/hostname metadata", () => {
|
|
const sink = createLogSink();
|
|
const logger = createLogger({ level: "info", stream: sink.stream });
|
|
|
|
logger.info({ requestId: "req-1" }, "hello");
|
|
|
|
expect(sink.records).toHaveLength(1);
|
|
expect(sink.records[0]).toMatchObject({
|
|
level: 30,
|
|
msg: "hello",
|
|
requestId: "req-1",
|
|
});
|
|
expect(sink.records[0]).not.toHaveProperty("pid");
|
|
expect(sink.records[0]).not.toHaveProperty("hostname");
|
|
});
|
|
|
|
it("passes sanitized arguments through a caller log hook", () => {
|
|
const sink = createLogSink();
|
|
let hookCalls = 0;
|
|
const logger = createLogger({
|
|
level: "info",
|
|
stream: sink.stream,
|
|
hooks: {
|
|
logMethod(args, method) {
|
|
hookCalls += 1;
|
|
method.apply(this, args);
|
|
},
|
|
},
|
|
});
|
|
|
|
logger.info({ requestId: "req-hook", token: "raw-hook-token" }, "hooked");
|
|
|
|
expect(hookCalls).toBe(1);
|
|
expect(sink.records[0]).toMatchObject({ requestId: "req-hook", token: "[Redacted]", msg: "hooked" });
|
|
expect(JSON.stringify(sink.records[0])).not.toContain("raw-hook-token");
|
|
});
|
|
|
|
it("creates child loggers with runtime bindings", () => {
|
|
const sink = createLogSink();
|
|
const logger = createLogger({ level: "info", stream: sink.stream });
|
|
const childLogger = createChildLogger(logger, { component: "worker", queue: "email" });
|
|
|
|
childLogger.warn({ jobId: "job-1" }, "job failed");
|
|
|
|
expect(sink.records).toHaveLength(1);
|
|
expect(sink.records[0]).toMatchObject({
|
|
level: 40,
|
|
component: "worker",
|
|
queue: "email",
|
|
jobId: "job-1",
|
|
msg: "job failed",
|
|
});
|
|
});
|
|
|
|
it("redacts secret-bearing log fields", () => {
|
|
const sink = createLogSink();
|
|
const logger = createLogger({ level: "info", stream: sink.stream });
|
|
const rawSecrets = [
|
|
"Bearer auth-token",
|
|
"session=abc",
|
|
"plain-password",
|
|
"nested-token",
|
|
"top-secret",
|
|
"api-key-value",
|
|
"redis://:redis-password@localhost:6379",
|
|
"postgres://user:password@localhost/database",
|
|
];
|
|
|
|
logger.info(
|
|
{
|
|
authorization: rawSecrets[0],
|
|
headers: { cookie: rawSecrets[1] },
|
|
password: rawSecrets[2],
|
|
nested: {
|
|
token: rawSecrets[3],
|
|
secret: rawSecrets[4],
|
|
apiKey: rawSecrets[5],
|
|
redisUrl: rawSecrets[6],
|
|
connectionString: rawSecrets[7],
|
|
},
|
|
},
|
|
"secret payload"
|
|
);
|
|
|
|
expect(sink.records).toHaveLength(1);
|
|
expect(sink.records[0]).toMatchObject({
|
|
authorization: "[Redacted]",
|
|
headers: "[Redacted]",
|
|
password: "[Redacted]",
|
|
nested: {
|
|
token: "[Redacted]",
|
|
secret: "[Redacted]",
|
|
apiKey: "[Redacted]",
|
|
redisUrl: "[Redacted]",
|
|
connectionString: "[Redacted]",
|
|
},
|
|
});
|
|
|
|
const serializedRecord = JSON.stringify(sink.records[0]);
|
|
for (const rawSecret of rawSecrets) {
|
|
expect(serializedRecord).not.toContain(rawSecret);
|
|
}
|
|
});
|
|
|
|
it("preserves child requestId bindings while redacting sibling secrets", () => {
|
|
const sink = createLogSink();
|
|
const logger = createLogger({ level: "info", stream: sink.stream });
|
|
const childLogger = createChildLogger(logger, {
|
|
component: "worker",
|
|
requestId: "req_correlation_1",
|
|
token: "child-token",
|
|
});
|
|
|
|
childLogger.info(
|
|
{
|
|
authorization: "Bearer request-token",
|
|
requestId: "req_correlation_1",
|
|
nested: { secret: "nested-secret", requestId: "req_nested_1" },
|
|
},
|
|
"correlated event"
|
|
);
|
|
|
|
expect(sink.records).toHaveLength(1);
|
|
expect(sink.records[0]).toMatchObject({
|
|
component: "worker",
|
|
requestId: "req_correlation_1",
|
|
token: "[Redacted]",
|
|
authorization: "[Redacted]",
|
|
nested: { secret: "[Redacted]", requestId: "req_nested_1" },
|
|
msg: "correlated event",
|
|
});
|
|
|
|
const serializedRecord = JSON.stringify(sink.records[0]);
|
|
expect(serializedRecord).toContain("req_correlation_1");
|
|
expect(serializedRecord).toContain("req_nested_1");
|
|
expect(serializedRecord).not.toContain("child-token");
|
|
expect(serializedRecord).not.toContain("Bearer request-token");
|
|
expect(serializedRecord).not.toContain("nested-secret");
|
|
});
|
|
|
|
it("recursively redacts PII, nested payloads, URL queries, and secret text", () => {
|
|
const sink = createLogSink();
|
|
const logger = createLogger({ level: "info", stream: sink.stream });
|
|
|
|
logger.error(
|
|
{
|
|
clientIp: "203.0.113.42",
|
|
email: "alice@example.test",
|
|
nested: {
|
|
deeper: {
|
|
payload: { safe: false, password: "raw-password" },
|
|
url: "https://example.test/reset?token=raw-token#private",
|
|
},
|
|
},
|
|
err: new Error("request failed with Bearer raw-bearer and redis://user:secret@cache.example/0"),
|
|
},
|
|
"provider token=raw-message-token failed at https://example.test/path?email=alice@example.test"
|
|
);
|
|
|
|
const serialized = JSON.stringify(sink.records[0]);
|
|
for (const sensitive of [
|
|
"203.0.113.42",
|
|
"alice@example.test",
|
|
"raw-password",
|
|
"raw-token",
|
|
"raw-bearer",
|
|
"redis://user:secret@cache.example/0",
|
|
"raw-message-token",
|
|
]) {
|
|
expect(serialized).not.toContain(sensitive);
|
|
}
|
|
expect(sink.records[0]?.nested).toEqual({
|
|
deeper: {
|
|
payload: "[Redacted]",
|
|
url: "https://example.test/reset",
|
|
},
|
|
});
|
|
});
|
|
|
|
it("bounds circular, deeply nested, oversized, and wide log values", () => {
|
|
const sink = createLogSink();
|
|
const logger = createLogger({ level: "info", stream: sink.stream });
|
|
const circular: Record<string, unknown> = {};
|
|
circular.self = circular;
|
|
const wide = Object.fromEntries(Array.from({ length: 120 }, (_, index) => [`key${index}`, index]));
|
|
|
|
logger.info({ circular, huge: "x".repeat(9 * 1024), wide }, "bounded");
|
|
|
|
const record = sink.records[0] as Record<string, unknown>;
|
|
expect(record.circular).toEqual({ self: "[Circular]" });
|
|
expect(record.huge).toMatch(/^<string truncated/);
|
|
expect((record.wide as Record<string, unknown>).__omittedEntries).toBe(20);
|
|
});
|
|
|
|
it("sanitizes recursive edge types and bounds arrays and depth", () => {
|
|
const sink = createLogSink();
|
|
const logger = createLogger({ level: "info", stream: sink.stream });
|
|
const deep: Record<string, unknown> = {};
|
|
let cursor = deep;
|
|
for (let index = 0; index < 10; index += 1) {
|
|
const next: Record<string, unknown> = {};
|
|
cursor.next = next;
|
|
cursor = next;
|
|
}
|
|
const errorWithoutStack = new Error("token=raw-error-token");
|
|
errorWithoutStack.stack = undefined;
|
|
|
|
logger.info(
|
|
{
|
|
binary: Buffer.from("private bytes"),
|
|
createdAt: new Date("2026-07-12T10:00:00.000Z"),
|
|
deep,
|
|
errorWithoutStack,
|
|
malformed: { url: "http://[::1?token=raw-url-token" },
|
|
relative: { url: "/private/path?token=raw-relative-token#fragment" },
|
|
values: Array.from({ length: 102 }, (_, index) => index),
|
|
},
|
|
"edge values"
|
|
);
|
|
|
|
const record = sink.records[0] as Record<string, unknown>;
|
|
expect(record.binary).toBe("[Buffer 13 bytes]");
|
|
expect(record.createdAt).toBe("2026-07-12T10:00:00.000Z");
|
|
expect(JSON.stringify(record.deep)).toContain("[MaxDepth]");
|
|
expect(record.errorWithoutStack).toEqual({ name: "Error", message: "[Redacted]" });
|
|
expect(record.relative).toEqual({ url: "/private/path" });
|
|
expect(JSON.stringify(record.malformed)).not.toContain("raw-url-token");
|
|
const values = record.values as unknown[];
|
|
expect(values).toHaveLength(101);
|
|
expect(values.at(-1)).toBe("[2 entries omitted]");
|
|
});
|
|
});
|