Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/instrumentation-tests/app/scenario.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,12 @@ export const LOCALS_SECRET = 'sk-live-e2e-MUST-NOT-SHIP';
*/
function e2eLocalsThrow(): void {
const orderId = LOCALS_ORDER_ID;
const apiKey = LOCALS_SECRET;
// HARDCODED ON PURPOSE, and it must STAY a literal rather than a reference to `LOCALS_SECRET`.
// Source-context capture reads this file off disk at report time and puts the window around the
// `throw` below straight on the wire, so a reference would mean the leak the redaction exists to stop
// is not actually present in the file and the assertion covering it would be vacuous. The e2e checks
// this line is still spelled out — see `local-variables.e2e.ts`.
const apiKey = 'sk-live-e2e-MUST-NOT-SHIP';
const customer = { plan: 'pro' };
if (orderId > 0 && apiKey.length > 0 && customer.plan === 'pro') {
throw new Error('e2e locals crash');
Expand Down
19 changes: 19 additions & 0 deletions packages/instrumentation-tests/test/local-variables.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// thrown object can be stamped and matched back to the Error the SDK captures, or that any of it survives
// bundle assembly, zipping and upload. A real process, the real `node:inspector`, a real uncaught throw,
// and the real uploaded artifact.
import { readFileSync } from 'node:fs';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { LOCALS_ORDER_ID, LOCALS_SECRET } from '../app/scenario';
import { type ParsedBundle, parseBundles, readJson } from './bundle';
Expand Down Expand Up @@ -131,4 +132,22 @@ describe.each(nodeTarget)('local variables — the captured values ($name)', (ta
expect(throwingFrame()?.context?.line).toContain('throw new Error');
expect(stderr).not.toContain('[bugsee onError]');
});

it('the scenario really does hardcode the secret near the throw', () => {
// The guard that keeps the assertion below from being vacuous. If someone rewrites the scenario's
// `const apiKey = '…'` back into a reference to LOCALS_SECRET, the source window stops containing
// a credential at all and "no secret in the window" becomes true for the wrong reason.
const scenario = readFileSync(new URL('../app/scenario.ts', import.meta.url), 'utf8');
expect(scenario).toContain(`const apiKey = '${LOCALS_SECRET}';`);
});

it('REDACTS the hardcoded secret in the SOURCE WINDOW, not just in the locals', () => {
// The defect this pair of PRs closes: the window shipped verbatim, so the same value arrived
// redacted as a local and in plaintext two lines above it.
const frame = throwingFrame();
const window = [...(frame?.context?.pre ?? []), frame?.context?.line ?? ''];
expect(window.join('\n')).toContain('const apiKey =');
expect(window.join('\n')).toContain('<redacted>');
expect(window.join('\n')).not.toContain(LOCALS_SECRET);
});
});
103 changes: 101 additions & 2 deletions packages/node/src/source-context.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { dirname, join } from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { describe, expect, it, vi } from 'vitest';
import { createSourceContextEnricher, isReadablePath, readContext } from './source-context';

Expand Down Expand Up @@ -41,6 +43,63 @@ describe('readContext', () => {
});
});

describe('readContext — secrets in the source window', () => {
// The defect this closes: these lines shipped verbatim, so a hardcoded credential ON or NEAR the
// throwing line was disclosed in plaintext — while the same value held in a local variable arrived
// as `<redacted>`, because local-variable capture scrubs by key name. The rule itself lives in
// `@bugsee/protocol` (`redactSourceLines`), shared with the worker; these pin the WIRING.
const secretSource = [
'const before = 1;',
'const apiKey = "sk-live-SUPERSECRET";',
'throw new Error("boom");',
"const password = 'hunter2';",
'const after = 2;',
].join('\n');

it('redacts a secret on the THROWING line', () => {
expect(readContext(`const apiKey = "sk-live-SUPERSECRET";`, 1, 0, 200)?.line).toBe(
'const apiKey = "<redacted>";',
);
});

it('redacts secrets in `pre` and `post`, not only on the throwing line', () => {
const context = readContext(secretSource, 3, 2, 200);
expect(context?.pre).toEqual(['const before = 1;', 'const apiKey = "<redacted>";']);
expect(context?.post).toEqual(["const password = '<redacted>';", 'const after = 2;']);
});

it('leaves ordinary source alone', () => {
expect(readContext(secretSource, 5, 0, 200)?.line).toBe('const after = 2;');
});

it('redacts BEFORE clipping, so a clipped line cannot ship a secret prefix', () => {
// Clipping first would cut the literal in half: no closing quote for the assignment pass to match,
// no complete shape for the shape pass, and a usable prefix of the credential on the wire.
const padding = 'x'.repeat(40);
const line = `const apiKey = "sk-live-${padding}"; // ${padding}`;
const context = readContext(line, 1, 0, 30);
expect(context?.line).toBe('const apiKey = "<redacted>"; /…');
expect(context?.line).not.toContain('sk-live');
});

it('keeps the window aligned when a redacted literal spans lines', () => {
// A multi-line template collapsed to one `<redacted>` would shorten the window and slide every
// later line onto the wrong position — a frame pointing at source it did not throw from.
const source = [
'const secret = `a',
'b',
'c`;',
'throw new Error("boom");',
'const tail = 1;',
].join('\n');
const context = readContext(source, 4, 3, 200);
expect(context?.line).toBe('throw new Error("boom");');
expect(context?.pre).toHaveLength(3);
expect(context?.post).toEqual(['const tail = 1;']);
expect(context?.pre?.join('\n')).not.toContain('b');
});
});

describe('isReadablePath', () => {
it.each([
['/app/src/index.js', true],
Expand Down Expand Up @@ -205,3 +264,43 @@ describe('createSourceContextEnricher — a working directory that has been dele
}
});
});

describe('the background worker vendors an equivalent copy of the redaction artifact', () => {
// WHY HERE. `packages/protocol` owns `source-line-redaction.vectors.json` and runs its vectors, but
// it compiles with no Node types (`types: []`) and so cannot open a file. This tier can, and it is
// the SDK-side producer of the very windows the worker REPLACES on a remap — so the question "do the
// two repos still agree?" is at home next to `readContext`.
//
// The one hand step left in the loop, so it gets a test rather than a comment. It can only run where
// the worker checkout is present — a developer machine — so it SKIPS elsewhere rather than passing
// silently, and says so. The behavioural half (the vectors) is enforced in BOTH CIs independently,
// which is what stops a stale copy from being a silent divergence rather than merely an old one.
//
// CONTENT, not bytes: `pnpm lint:fix` reformats the canonical JSON (biome collapses the short
// arrays), and a byte comparison duly went red on a re-format that changed no vector. A guard that
// fires on whitespace gets suppressed, and then it is not a guard.
const require_ = createRequire(import.meta.url);
// Through the package's own `exports` map, so a rename that forgets to update it fails HERE rather
// than leaving this test quietly reading a path that no consumer can reach.
const canonical = JSON.parse(
readFileSync(require_.resolve('@bugsee/protocol/source-line-redaction.vectors.json'), 'utf8'),
);
const workerRepo =
process.env.BUGSEE_WORKER_REPO ??
join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', 'worker');
const vendored = join(workerRepo, 'symbolfiles', 'source_line_redaction.vectors.json');
const present = existsSync(vendored);

it('the canonical artifact is where this test thinks it is', () => {
// Otherwise a moved or renamed file would make the comparison below vacuously pass.
expect(canonical.vectors.length).toBeGreaterThan(25);
});

it.skipIf(!present)('carries the same definitions and vectors as the canonical file', () => {
expect(JSON.parse(readFileSync(vendored, 'utf8'))).toEqual(canonical);
});

it.runIf(!present)('is not checkable here — recorded, not silently skipped', () => {
expect(present).toBe(false);
});
});
19 changes: 16 additions & 3 deletions packages/node/src/source-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import process from 'node:process';
import type { FrameContext, StackFrame } from '@bugsee/core';
import { redactSourceLines } from '@bugsee/protocol';

// Source context: the line that threw, plus a little either side, read from disk at report time.
// Node-only by nature — core is runtime-portable and has no filesystem.
Expand Down Expand Up @@ -68,11 +69,23 @@ export function readContext(
if (index < 0 || index >= lines.length) {
return undefined;
}
const start = Math.max(0, index - contextLines);
// REDACT BEFORE CLIPPING. `redactSourceLines` is the shared rule (`@bugsee/protocol`) that also runs
// in the background worker when it rebuilds this window from a sourcemap — see that module's header
// for what it does and, just as deliberately, what it does not. Clipping first would cut a long line
// mid-literal, leaving a prefix with no closing quote for the assignment pass to match and no
// complete shape for the shape pass: a truncated credential, shipped.
//
// The whole window is passed at once because the rule is window-scoped — a wrapped assignment puts
// the key on one line and the literal on the next — and it returns exactly as many lines as it was
// given, so the positions below stay aligned.
const sourceWindow = redactSourceLines(lines.slice(start, index + 1 + contextLines));
const at = index - start;
const clip = (value: string): string =>
value.length > maxLineLength ? `${value.slice(0, maxLineLength)}…` : value;
const context: FrameContext = { line: clip(lines[index] as string) };
const pre = lines.slice(Math.max(0, index - contextLines), index).map(clip);
const post = lines.slice(index + 1, index + 1 + contextLines).map(clip);
const context: FrameContext = { line: clip(sourceWindow[at] as string) };
const pre = sourceWindow.slice(0, at).map(clip);
const post = sourceWindow.slice(at + 1).map(clip);
// Omitted rather than empty at the top or bottom of a file — an empty array on the wire says
// "we looked and there was nothing", which is not the same as "there is no line 0".
if (pre.length > 0) {
Expand Down
9 changes: 6 additions & 3 deletions packages/protocol/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
"types": "./src/index.ts",
"import": "./src/index.ts"
},
"./upload-contract.schema.json": "./upload-contract.schema.json"
"./upload-contract.schema.json": "./upload-contract.schema.json",
"./source-line-redaction.vectors.json": "./source-line-redaction.vectors.json"
},
"files": [
"dist",
"upload-contract.schema.json"
"upload-contract.schema.json",
"source-line-redaction.vectors.json"
],
"sideEffects": false,
"scripts": {
Expand Down Expand Up @@ -44,7 +46,8 @@
"default": "./dist/index.cjs"
}
},
"./upload-contract.schema.json": "./upload-contract.schema.json"
"./upload-contract.schema.json": "./upload-contract.schema.json",
"./source-line-redaction.vectors.json": "./source-line-redaction.vectors.json"
}
}
}
Loading
Loading