mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 15:05:51 +00:00
perf(browser): precompile redaction markers, eliminate quadratic secret scans, and scope HAR validation (#13267)
* perf(browser): precompile redaction markers, eliminate quadratic secret scans, and skip unescaped HAR JSON.parse * fix(browser): remove single-use markerById map in BrowserScenarioSecrets * fix(browser): detach CaptureJson literal strings from parent buffer
This commit is contained in:
1 parent
38bc4fe907
commit
2afc34ec6e
5 files changed
+203
-65
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
|
||||
import { readResponseValues } from "./BrowserScenarioResponseValues.js";
|
||||
@@ -71,3 +71,57 @@ it.each([
|
||||
expect(secrets.redact("unrelated value")).toBe("unrelated value");
|
||||
},
|
||||
);
|
||||
|
||||
describe("browser scenario cursor redaction", () => {
|
||||
it("redacts multiple occurrences, longest-match overlaps, percent case escapes, and reconstructed secrets", () => {
|
||||
const resolved = BrowserScenarioSecrets.resolve(
|
||||
browserScenarioSchema.parse({
|
||||
browser: { mode: "launch", executable_path: "/fixture/chrome" },
|
||||
start_url: { url: "https://example.test/" },
|
||||
secrets: [
|
||||
{ secret_id: "short", environment_variable: "SHORT_SECRET" },
|
||||
{ secret_id: "long", environment_variable: "LONG_SECRET" },
|
||||
{ secret_id: "pct", environment_variable: "PCT_SECRET" },
|
||||
{ secret_id: "outer", environment_variable: "OUTER_SECRET" },
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
step_id: "save",
|
||||
action: "request",
|
||||
method: "GET",
|
||||
path: "/value",
|
||||
save: [{ name: "token", json_pointer: "/token", secret: true }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
{
|
||||
SHORT_SECRET: "alpha-secret",
|
||||
LONG_SECRET: "alpha-secret-extended",
|
||||
PCT_SECRET: "tok/en",
|
||||
OUTER_SECRET: "pre[REDACTED:short]post",
|
||||
},
|
||||
);
|
||||
if (!resolved.ok) throw resolved.error;
|
||||
const secrets = resolved.value;
|
||||
|
||||
const clean = "nothing-sensitive-present&foo=bar";
|
||||
expect(secrets.redact(clean)).toBe(clean);
|
||||
|
||||
const multi =
|
||||
"first=alpha-secret&second=alpha-secret-extended&url=tok%2fen&upper=tok%2Fen";
|
||||
const redactedMulti = secrets.redact(multi);
|
||||
expect(redactedMulti).toBe(
|
||||
"first=[REDACTED:short]&second=[REDACTED:long]&url=[REDACTED:pct]&upper=[REDACTED:pct]",
|
||||
);
|
||||
|
||||
const sanitized = secrets.sanitizeUrl(
|
||||
"https://example.test/?q=tok%2Fen&long=alpha-secret-extended",
|
||||
);
|
||||
expect(sanitized.redacted).toBe(true);
|
||||
expect(sanitized.url).not.toContain("tok");
|
||||
expect(sanitized.url).not.toContain("alpha-secret");
|
||||
|
||||
// When marker substitution forms another declared secret, the post-replacement check wipes the output.
|
||||
expect(secrets.redact("prealpha-secretpost")).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -58,6 +58,7 @@ interface SecretPattern {
|
||||
}
|
||||
interface SecretReplacement extends SecretPattern {
|
||||
readonly id: string;
|
||||
readonly marker: string;
|
||||
}
|
||||
interface SecretNeedle {
|
||||
readonly id: string;
|
||||
@@ -161,11 +162,17 @@ const declaredPatterns = (
|
||||
const secretReplacements = (
|
||||
values: ReadonlyMap<string, string>,
|
||||
spellings: SecretSpellings,
|
||||
markerPatterns: readonly SecretPattern[],
|
||||
): readonly SecretReplacement[] =>
|
||||
[...values]
|
||||
.flatMap(([id, secret]) =>
|
||||
secretPatterns(secret, spellings).map((pattern) => ({ id, ...pattern })),
|
||||
)
|
||||
.flatMap(([id, secret]) => {
|
||||
const marker = redactionMarker(id, markerPatterns);
|
||||
return secretPatterns(secret, spellings).map((pattern) => ({
|
||||
id,
|
||||
marker,
|
||||
...pattern,
|
||||
}));
|
||||
})
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.text.length - left.text.length ||
|
||||
@@ -249,51 +256,54 @@ const redactionMarker = (
|
||||
const replaceSecretLiterals = (
|
||||
value: string,
|
||||
replacements: readonly SecretReplacement[],
|
||||
patterns: readonly SecretPattern[],
|
||||
markerPatterns: readonly SecretPattern[] = patterns,
|
||||
): string => {
|
||||
): { readonly output: string; readonly replaced: boolean } => {
|
||||
const normalizedValue = replacements.some(
|
||||
({ percentInsensitive }) => percentInsensitive,
|
||||
)
|
||||
? lowercasePercentEscapes(value)
|
||||
: value;
|
||||
const nextIndices = new Int32Array(replacements.length).fill(-2);
|
||||
const parts: string[] = [];
|
||||
let offset = 0;
|
||||
while (offset < value.length) {
|
||||
let next:
|
||||
| ((typeof replacements)[number] & { readonly index: number })
|
||||
| undefined;
|
||||
for (const replacement of replacements) {
|
||||
const search = replacement.searchText;
|
||||
const view = replacement.percentInsensitive ? normalizedValue : value;
|
||||
const index = view.indexOf(search, offset);
|
||||
let next: SecretReplacement | undefined;
|
||||
let nextIndex = -1;
|
||||
for (let i = 0; i < replacements.length; i += 1) {
|
||||
const replacement = replacements[i]!;
|
||||
let index = nextIndices[i]!;
|
||||
if (index === -1) continue;
|
||||
if (index === -2 || index < offset) {
|
||||
const view = replacement.percentInsensitive ? normalizedValue : value;
|
||||
index = view.indexOf(replacement.searchText, offset);
|
||||
nextIndices[i] = index;
|
||||
}
|
||||
if (
|
||||
index >= 0 &&
|
||||
(next === undefined ||
|
||||
index < next.index ||
|
||||
(index === next.index && replacement.text.length > next.text.length))
|
||||
)
|
||||
next = { ...replacement, index };
|
||||
index < nextIndex ||
|
||||
(index === nextIndex && replacement.text.length > next.text.length))
|
||||
) {
|
||||
next = replacement;
|
||||
nextIndex = index;
|
||||
}
|
||||
}
|
||||
if (next === undefined) break;
|
||||
const marker = redactionMarker(next.id, markerPatterns);
|
||||
parts.push(value.slice(offset, next.index), marker);
|
||||
offset = next.index + next.text.length;
|
||||
parts.push(value.slice(offset, nextIndex), next.marker);
|
||||
offset = nextIndex + next.text.length;
|
||||
}
|
||||
if (parts.length === 0) return value;
|
||||
if (parts.length === 0) return { output: value, replaced: false };
|
||||
parts.push(value.slice(offset));
|
||||
return parts.join("");
|
||||
return { output: parts.join(""), replaced: true };
|
||||
};
|
||||
|
||||
const secretNeedles = (
|
||||
replacements: readonly SecretReplacement[],
|
||||
patterns: readonly SecretPattern[],
|
||||
): SecretNeedle[] =>
|
||||
replacements.map((pattern) => ({
|
||||
id: pattern.id,
|
||||
needle: Buffer.from(pattern.searchText),
|
||||
percentInsensitive: pattern.percentInsensitive,
|
||||
marker: Buffer.from(redactionMarker(pattern.id, patterns)),
|
||||
marker: Buffer.from(pattern.marker),
|
||||
}));
|
||||
|
||||
/** Resolved secret values kept only for one in-memory scenario session. */
|
||||
@@ -332,9 +342,13 @@ export class BrowserScenarioSecrets {
|
||||
const values = this.values;
|
||||
this.urlPatterns = declaredPatterns(values, "url");
|
||||
this.textPatterns = declaredPatterns(values, "text");
|
||||
this.urlReplacements = secretReplacements(values, "url");
|
||||
this.textReplacements = secretReplacements(values, "text");
|
||||
this.textNeedles = secretNeedles(this.textReplacements, this.textPatterns);
|
||||
this.urlReplacements = secretReplacements(values, "url", this.urlPatterns);
|
||||
this.textReplacements = secretReplacements(
|
||||
values,
|
||||
"text",
|
||||
this.textPatterns,
|
||||
);
|
||||
this.textNeedles = secretNeedles(this.textReplacements);
|
||||
this.redactionCostPerCharacter = this.costOf(
|
||||
this.textReplacements,
|
||||
this.urlReplacements,
|
||||
@@ -347,16 +361,12 @@ export class BrowserScenarioSecrets {
|
||||
url: readonly SecretReplacement[],
|
||||
): number {
|
||||
let cost = 8;
|
||||
for (const [replacements, patterns] of [
|
||||
[text, this.textPatterns],
|
||||
[url, this.urlPatterns],
|
||||
] as const)
|
||||
for (const replacements of [text, url] as const)
|
||||
for (const replacement of replacements)
|
||||
cost = Math.max(
|
||||
cost,
|
||||
8 +
|
||||
(Buffer.byteLength(redactionMarker(replacement.id, patterns)) * 8 +
|
||||
128) /
|
||||
(Buffer.byteLength(replacement.marker) * 8 + 128) /
|
||||
replacement.text.length,
|
||||
);
|
||||
return cost;
|
||||
@@ -722,12 +732,8 @@ export class BrowserScenarioSecrets {
|
||||
: this.textReplacements;
|
||||
const patterns = scope === "response" ? replacements : this.textPatterns;
|
||||
if (patterns.length === 0) return value;
|
||||
const output = replaceSecretLiterals(
|
||||
value,
|
||||
replacements,
|
||||
patterns,
|
||||
this.textPatterns,
|
||||
);
|
||||
const { output, replaced } = replaceSecretLiterals(value, replacements);
|
||||
if (!replaced) return output;
|
||||
return containsSecretPattern(
|
||||
output,
|
||||
lowercasePercentEscapes(output),
|
||||
@@ -811,13 +817,9 @@ export class BrowserScenarioSecrets {
|
||||
: this.urlReplacements;
|
||||
const patterns = scope === "response" ? replacements : this.urlPatterns;
|
||||
if (patterns.length === 0) return sanitizeBrowserUrl(value);
|
||||
const output = replaceSecretLiterals(
|
||||
value,
|
||||
replacements,
|
||||
patterns,
|
||||
this.urlPatterns,
|
||||
);
|
||||
const { output, replaced } = replaceSecretLiterals(value, replacements);
|
||||
if (
|
||||
replaced &&
|
||||
containsSecretPattern(output, lowercasePercentEscapes(output), patterns)
|
||||
)
|
||||
return {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { describe, expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import { createTestProcessRegistry } from "../../../tests/support/process/processFixture.js";
|
||||
import { selectedWebNetworkCaptureBudgets } from "../../domain/webNetworkCapture.js";
|
||||
@@ -26,19 +26,14 @@ it("keeps trace nesting independent of the selected network capture depth", () =
|
||||
});
|
||||
});
|
||||
|
||||
it("retains escape-heavy strings within a heap near their decoded size", async () => {
|
||||
const captureJsonModuleUrl = JSON.stringify(
|
||||
new URL("./CaptureJson.ts", import.meta.url).href,
|
||||
);
|
||||
|
||||
const runBoundedHeapProgram = (program: string) => {
|
||||
const processes = createTestProcessRegistry();
|
||||
onTestFinished(() => processes.shutdown());
|
||||
// About 4.4 MB of JSON strings with an escape every few characters: this
|
||||
// needed about 86 MiB of old space as retained ropes and fits in 48 flat.
|
||||
const program = `
|
||||
const { parseCaptureJson } = await import(${JSON.stringify(new URL("./CaptureJson.ts", import.meta.url).href)});
|
||||
const body = JSON.stringify({ items: Array.from({ length: 200 }, (_, id) => ({ id, note: 'a "quoted" word' })) });
|
||||
const parsed = parseCaptureJson(JSON.stringify(Array.from({ length: 463 }, () => body)), "HAR");
|
||||
if (!Array.isArray(parsed) || parsed.length !== 463 || parsed.some((value) => value !== body)) process.exit(3);
|
||||
`;
|
||||
|
||||
const child = await processes.run(process.execPath, [
|
||||
return processes.run(process.execPath, [
|
||||
"--max-old-space-size=48",
|
||||
"--max-semi-space-size=8",
|
||||
"--import",
|
||||
@@ -47,6 +42,79 @@ it("retains escape-heavy strings within a heap near their decoded size", async (
|
||||
"--eval",
|
||||
program,
|
||||
]);
|
||||
};
|
||||
|
||||
it("retains escape-heavy strings within a heap near their decoded size", async () => {
|
||||
// About 4.4 MB of JSON strings with an escape every few characters: this
|
||||
// needed about 86 MiB of old space as retained ropes and fits in 48 flat.
|
||||
const child = await runBoundedHeapProgram(`
|
||||
const { parseCaptureJson } = await import(${captureJsonModuleUrl});
|
||||
const body = JSON.stringify({ items: Array.from({ length: 200 }, (_, id) => ({ id, note: 'a "quoted" word' })) });
|
||||
const parsed = parseCaptureJson(JSON.stringify(Array.from({ length: 463 }, () => body)), "HAR");
|
||||
if (!Array.isArray(parsed) || parsed.length !== 463 || parsed.some((value) => value !== body)) process.exit(3);
|
||||
`);
|
||||
|
||||
expect(child.exitCode, child.stderr).toBe(0);
|
||||
});
|
||||
|
||||
describe("capture JSON string materialization", () => {
|
||||
it("preserves empty strings, unescaped Unicode text, and escaped sequences", () => {
|
||||
const raw =
|
||||
'["","plain ascii","https://example.test/雪?a=1&b=2","escaped\\nline\\t\\u0041","pair😀\\ud83d\\ude80"]';
|
||||
expect(parseCaptureJson(raw, "HAR")).toEqual(JSON.parse(raw));
|
||||
});
|
||||
|
||||
it("detaches unescaped short strings so omitted sibling payloads can be GC'd", async () => {
|
||||
// 30 x 2 MiB JSON payloads (~60 MiB) exceeds the 48 MiB old-space ceiling if
|
||||
// the retained 26-char callId stays a V8 SlicedString pinning each parent.
|
||||
const child = await runBoundedHeapProgram(`
|
||||
const { parseCaptureJson } = await import(${captureJsonModuleUrl});
|
||||
const callIds = [];
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const expectedId = "call_" + String(i).padStart(21, "0");
|
||||
const json = JSON.stringify({
|
||||
callId: expectedId,
|
||||
expression: String.fromCharCode(65 + (i % 26)).repeat(2 * 1024 * 1024),
|
||||
});
|
||||
const parsed = parseCaptureJson(json, "Playwright trace");
|
||||
callIds.push(parsed.callId);
|
||||
}
|
||||
if (
|
||||
callIds.length !== 30 ||
|
||||
callIds.some((id, i) => id !== "call_" + String(i).padStart(21, "0"))
|
||||
) {
|
||||
process.exit(3);
|
||||
}
|
||||
`);
|
||||
|
||||
expect(child.exitCode, child.stderr).toBe(0);
|
||||
});
|
||||
|
||||
it("detaches long LosslessNumber spellings so omitted sibling payloads can be GC'd", async () => {
|
||||
// Numeric literals >= 13 chars also slice `text` in V8; keeping only the
|
||||
// LosslessNumber spelling must not retain 30 x 2 MiB (~60 MiB) parent JSON.
|
||||
const child = await runBoundedHeapProgram(`
|
||||
const { parseCaptureJson } = await import(${captureJsonModuleUrl});
|
||||
const numbers = [];
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const literal = "1732245678901." + String(i).padStart(6, "0");
|
||||
const json =
|
||||
'{"startTime":' +
|
||||
literal +
|
||||
',"expression":' +
|
||||
JSON.stringify(String.fromCharCode(65 + (i % 26)).repeat(2 * 1024 * 1024)) +
|
||||
"}";
|
||||
const parsed = parseCaptureJson(json, "Playwright trace");
|
||||
numbers.push(parsed.startTime);
|
||||
}
|
||||
if (
|
||||
numbers.length !== 30 ||
|
||||
numbers.some((n, i) => n.value !== "1732245678901." + String(i).padStart(6, "0"))
|
||||
) {
|
||||
process.exit(3);
|
||||
}
|
||||
`);
|
||||
|
||||
expect(child.exitCode, child.stderr).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -122,11 +122,23 @@ export const parseCaptureJson = (
|
||||
onArrayEnd: () => endContainer("array"),
|
||||
onLiteralValue: (value: unknown, offset, length) => {
|
||||
admitNode();
|
||||
if (typeof value === "number")
|
||||
append(new LosslessNumber(text.slice(offset, offset + length)));
|
||||
// jsonc-parser 3.3.1 builds an escaped string fragment by fragment,
|
||||
// which V8 keeps as a rope several times larger than its text.
|
||||
// JSON.parse of the same accepted token returns one flat string.
|
||||
if (typeof value === "number") {
|
||||
const literal = text.slice(offset, offset + length);
|
||||
// V8 turns >= 13-character slices into SlicedStrings pointing at `text`;
|
||||
// detach long numeric literals so retained LosslessNumber spellings
|
||||
// cannot pin discarded multi-megabyte JSON source buffers.
|
||||
append(
|
||||
new LosslessNumber(
|
||||
length > 12 ? String(JSON.parse(`"${literal}"`)) : literal,
|
||||
),
|
||||
);
|
||||
}
|
||||
// jsonc-parser 3.3.1 builds escaped strings as V8 ropes several times
|
||||
// larger than the decoded text and slices unescaped strings (>= 13 chars)
|
||||
// with substring(), producing V8 SlicedStrings pointing at `text`.
|
||||
// JSON.parse of the accepted token solves both: it avoids rope inflation
|
||||
// and allocates a detached flat string so retained short strings cannot
|
||||
// pin oversized omitted payloads via V8 SlicedString parent pointers.
|
||||
else if (typeof value === "string")
|
||||
append(JSON.parse(text.slice(offset, offset + length)));
|
||||
else if (value === null || typeof value === "boolean") append(value);
|
||||
|
||||
@@ -26,14 +26,16 @@ type Projection = Pick<
|
||||
"reported" | "numeric_literals" | "binary_fields" | "redactions"
|
||||
>;
|
||||
|
||||
const validateHarDocument = (raw: unknown) =>
|
||||
createHarValidator()(projectHar(raw, [], "validation").reported);
|
||||
|
||||
/** Decode a retained HAR, validating a disposable projection of source facts. */
|
||||
export const decodeHarCapture = (
|
||||
text: string,
|
||||
sensitiveValues: readonly string[],
|
||||
): DecodedCapture => {
|
||||
const raw = parseCaptureJson(text, "HAR");
|
||||
const validation = projectHar(raw, [], "validation");
|
||||
const adaptations = createHarValidator()(validation.reported);
|
||||
const adaptations = validateHarDocument(raw);
|
||||
const ipv6Adaptation = adaptations.bracketedIpv6;
|
||||
const timingAdaptation = adaptations.failedRequests;
|
||||
const failedRequests = new Set(timingAdaptation?.entries);
|
||||
|
||||
Reference in new issue
Block a user