Files
reverse-engineering-anything/src/domain/analysisView/webNetworkCaptureView.test.ts
T
morluto 1f24b3fa57 feat(evidence)!: name the Evidence subject by its target identity (format revision 2) (#11416)
* feat(evidence)!: name the Evidence subject by its target identity (format revision 2)

The Evidence subject carries subject.identity (kind, sha256, format,
architecture, selection) and the Evidence ID commits to it, so raw/DOL
entry points and ESP flash offsets of the same bytes are different
subjects. Every record declares evidence_format: 2; revision 1 bundles,
standalone records and snapshots are refused with the recreate guidance.
binaryTargetIdentity is the one projection of an open target, used by
Evidence and snapshot comparison.

BREAKING CHANGE: Evidence format revision 2. Evidence IDs commit to the
subject's target identity (subject.identity, including the raw/DOL entry
point or ESP flash offsets), and every record declares evidence_format: 2.
Evidence bundles, records and analysis snapshots from earlier releases are
refused; recreate the observations with this release.

* refactor(analysis-view): read parent subjects through the Evidence identity accessors (#11423)

Analysis views compare their parent's file identity (evidenceFileTarget)
and take path and digest from evidenceSubjectTarget instead of reading
the subject's digest, format and architecture members, which duplicate
subject.identity until they are removed. A counted guard
(evidence-subject-declaration-read) keeps new direct reads out and
records the 20 remaining files.

* fix(evidence): carry format refusals through Evidence readers and bind target selections

- safeParseEvidence/safeParseImmutableEvidence return the format refusal as
  an expected failure; every consumer maps it to the one integrity refusal
  with the recreate guidance. An unmarked object is an earlier record only
  when it has every member records have always carried.
- ArtifactProvider inventory roots and provider subjects that name the
  target's own bytes carry the target's selection (ESP flash offsets).
- Snapshot rows bind only Evidence whose identity, selection included,
  matches the snapshot target.
- Entry-point selections use the raw-binary entry point form.

* fix(evidence): refuse unauthenticated or earlier-format records instead of reading them as absent

- recognizeEvidence (evidenceValidation) replaces tryParseEvidence: input
  without an evidence_id is not Evidence (ok(undefined)); a record that names
  one but fails authentication or is from another format revision is an
  EvidenceIntegrityError carrying the recreate guidance, never undefined.
- Direct analysis retains that refusal as a secondary failure instead of
  silently skipping source capture; cleanup projection, source-closure
  annotation and the flutter, debugger and release-exposure recoveries use
  the same owner (the last three previously read the unauthenticated schema).
- A desktop capture.json from an earlier format is refused with the recreate
  guidance instead of "not desktop application capture Evidence".

* fix(evidence): advertise revision 2 ledger examples and rank delivery omissions by serialized size

- The obligation ledger and reconstruction coverage examples named
  evidence_format 1, which revision 2 refuses; they now use
  EVIDENCE_FORMAT_REVISION.
- MCP delivery chose which unretained recovery to omit by a parsed-storage
  lower bound clipped at the response budget. Once revision 2 subjects made
  the source record's estimate cross the budget, both candidates tied at the
  clip and the smaller source was omitted ahead of the larger completed
  observation. Candidates are now ranked by serialized size, which is what
  the budget counts.

* refactor(native): compare function snapshots by their Evidence target identity (#11450)

Function snapshots carry the subject's file target identity instead of the
duplicated subject declaration. Call paths and function comparisons compare
targets through sameTargetIdentity, so the same bytes opened at a different
raw entry point or ESP flash offset no longer count as one coordinate space:
build_call_path refuses the mix, and compare_functions no longer matches
entries by address across selections. Structural candidates and native
function matching read the architecture and digest through
evidenceFileTarget.

Refs #11417

* refactor(artifacts): compare artifact and WASM summaries by their Evidence target identity (#11461)

Artifact comparison authenticates a summary against its retained inventory
through sameTargetIdentity and rebinds the alias with the whole target,
selection included, so a flash-selected inventory summary taken under an
alias path is no longer refused. WASM comparison, the analysis view
artifact projection and the inventory root check read the digest, format
and display path through the Evidence identity accessors.

Refs #11417

* refactor(evidence): read record subjects through the identity accessors in JS, managed, ledger and bundle readers (#11470)

JavaScript application graphs, runtime reconciliation, managed inspection
and native verification sources, the record summary filter, the ledger's
residual-unknown target and bundle scope selection read the subject digest,
format and display path through evidenceFileTarget and
evidenceSubjectDisplay. No comparison changes: each reader matches one
record's facts against its own payload or a caller filter.

Refs #11417

* refactor(evidence)!: name the Evidence subject only by its target identity (#11497)

* refactor(evidence)!: name the Evidence subject only by its target identity

The subject keeps `identity` and the display facts `name` and `local_path`.
The duplicated `digest`, `format` and `architecture` members are removed; the
format-owned declaration now validates the identity itself. Readers the type
checker found move to the owner accessors; untyped reads in verify scripts,
the efficiency harness and test matchers move to `subject.identity`. The
`evidence-subject-declaration-read` text guard and its baseline are deleted.

Fixes #11473
Refs #11417

BREAKING CHANGE: the Evidence subject no longer has `digest`, `format` or
`architecture`; read `subject.identity.sha256`, `subject.identity.format` and
`subject.identity.architecture`. A record that still carries them is refused.

* test(evidence): give the Flutter verifier fixture the identity subject and check the DOL declaration without the ID

* test(evidence): drop the removed subject members from the declaration matrix and tamper fixtures

* feat(evidence)!: give every Evidence record an explicit subject identity (#11536)

* feat(evidence)!: give every Evidence record an explicit subject identity

A producer that cannot name a file passes an `unknown` target identity
with a closed reason (derived-from-linked-evidence, not-observed,
unsupported-subject) instead of no subject. The subject is non-null;
unknown subjects have no display facts. The generic missing-subject
limitation and `subjectUnavailableReason` are removed; producer-specific
explanations are ordinary limitations. Comparison identity requires the
derived unknown, and null-subject consumers ask the owner accessors.

Refs #11417

BREAKING CHANGE: every Evidence record has a subject. A record without a
file target names `subject.identity` `{ "kind": "unknown", "reason": … }`
with `name` and `local_path` null, instead of `subject: null` and the
limitation "Artifact identity is unavailable for this observation.".
Their Evidence IDs change.

* fix(evidence): name explicit unknown subjects in JavaScript callers and keep a managed graph's file subject

The verification scripts are not type-checked, so five createEvidence
callers still passed undefined (or a missing first target) after the subject
became required. They now pass unknownTarget("not-observed").

A managed application graph chose the first present input subject. Every
subject is now present, so an unknown artifact subject hid a file subject on
the member or boundary Evidence. The graph now takes the first input subject
that names a file.

* test(evidence): assert the subject kind instead of a presence the type now guarantees

Every Evidence record has a subject after this change, so test guards and
assertions that checked it for null always passed. Each now checks that the
fixture subject names a file, or is removed where a later fileIdentity,
fileSubjectTarget or fileSubjectDisplay call already requires that. Non-null
assertions on Evidence subjects are removed; analysis-view inputs, whose
subject is optional, keep an undefined check.

* test(evidence): expect the Evidence subject format under its identity

Two boundary tests still matched subject.format, which slice 2e moved into
subject.identity. toMatchObject is not type-checked against the Evidence
shape, so they failed only when run (the signature test on macOS).
2026-11-16 06:28:01 +08:00

1154 lines
33 KiB
TypeScript

import { expect, it, vi } from "vitest";
import {
changedEvidenceSubject,
UNKNOWN_EVIDENCE_SUBJECT,
} from "../../../tests/fixtures/evidenceSubject.js";
import { createHash } from "node:crypto";
import { createEvidence } from "../evidence.js";
import { freezeJsonSnapshot } from "../immutableJson.js";
import { webNetworkCaptureSchema } from "../webNetworkCapture.js";
import { projectAnalysisView } from "./analysisView.js";
import { analysisViewRequestSchema } from "./analysisViewRequest.js";
import { timedCaptureEvidence } from "../../../tests/fixtures/analysisView.js";
const capture = () => {
const body = Buffer.from("original body");
const artifact = {
path: "/recordings/input.saz",
sha256: "b".repeat(64),
bytes: 100,
};
const decoder = { id: "fixture", name: "Fixture", version: "1" };
const report = webNetworkCaptureSchema.parse({
artifact,
decoder,
format: "saz",
runtime_attribution: "unknown",
limitations: [],
container: {
reported: { members: [] },
numeric_literals: [],
redactions: [],
records_pointer: null,
},
total_records: 9,
records: [7, 2].map((ordinal) => ({
ordinal,
location: { kind: "archive-members", members: [`raw/${ordinal}_c.txt`] },
reported: {
session_id: String(ordinal),
time: null,
request: {
method: "POST",
url: "https://example.invalid/a",
body: body.toString(),
},
},
binary_fields: [
{
pointer: "/request/body",
representation: "producer-bytes",
state: "retained",
content_base64: body.toString("base64"),
bytes: body.length,
sha256: createHash("sha256").update(body).digest("hex"),
},
],
numeric_literals: [
{
pointer: "/time",
producer_type: "json-number",
literal: "9007199254740993",
},
],
redactions: [],
limitations: [],
})),
});
const evidence = createEvidence({ ...artifact, format: "file" }, decoder, {
operation: "inspect_web_network_capture",
parameters: { record_ordinals: [7, 2] },
result: report,
confidence: "observed",
authority: "historical-reference",
});
return {
report,
parent: {
predicateType: evidence.predicate_type,
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: report,
subject: evidence.subject,
limitations: evidence.limitations,
},
};
};
it("uses qlog event headlines without promoting HTTP-shaped extensions", () => {
const { report } = capture();
const first = report.records[0];
if (first === undefined) throw new Error("Expected a capture record");
const qlog = webNetworkCaptureSchema.parse({
...report,
format: "qlog",
qlog: {
profile: "aioquic-1.5.0-json-0.3",
scope: "all-recorded-events-before-selection",
body_bytes: "not-reported",
clock: {
unit: "milliseconds",
domain: "unix-epoch",
basis: "selected-aioquic-profile-not-producer-authentication",
},
traces: [],
},
total_records: 1,
records: [
{
...first,
ordinal: 0,
reported: {
name: "transport:packet_sent",
time: 1.25,
request: { url: { payload: "event-extension" } },
type: { payload: "event-extension" },
},
numeric_literals: [],
binary_fields: [],
},
],
});
if (qlog.artifact.sha256 === null) throw new Error("Expected fixture digest");
const evidence = createEvidence(
{ ...qlog.artifact, sha256: qlog.artifact.sha256, format: "file" },
qlog.decoder,
{
operation: "inspect_web_network_capture",
parameters: {},
result: qlog,
confidence: "observed",
authority: "historical-reference",
},
);
const preview = projectAnalysisView(
{
predicateType: evidence.predicate_type,
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: qlog,
subject: evidence.subject,
limitations: evidence.limitations,
},
{ kind: "capture", detail: "preview", offset: 0, limit: 1 },
);
expect(preview.ok && preview.value).toMatchObject({
items: [{ reported: { name: "transport:packet_sent", time: 1.25 } }],
});
expect(JSON.stringify(preview)).not.toContain("event-extension");
});
it("checks each parent's subject even after its immutable capture has been validated", () => {
const { parent } = capture();
const source = {
...parent,
normalizedResult: freezeJsonSnapshot(parent.normalizedResult),
};
expect(projectAnalysisView(source, { kind: "summary" }).ok).toBe(true);
expect(
projectAnalysisView(
{ ...source, subject: UNKNOWN_EVIDENCE_SUBJECT },
{ kind: "summary" },
).ok,
).toBe(false);
if (source.subject.identity.kind !== "file")
throw new Error("Expected fixture subject");
expect(
projectAnalysisView(
{
...source,
subject: changedEvidenceSubject(source.subject, {
sha256: "e".repeat(64),
}),
},
{ kind: "summary" },
).ok,
).toBe(false);
expect(projectAnalysisView(source, { kind: "summary" }).ok).toBe(true);
});
it("keeps selected-record page coverage distinct from capture coverage and unsafe number absence", () => {
const { parent, report } = capture();
const summary = projectAnalysisView(parent, { kind: "summary" });
expect(summary.ok && summary.value).toMatchObject({
summary: { total_records: 9, retained_records: 2 },
coverage: { examined: 2, total: 2 },
});
const preview = projectAnalysisView(parent, {
kind: "capture",
detail: "preview",
offset: 0,
limit: 1,
});
expect(preview.ok && preview.value).toMatchObject({
items: [
{
ordinal: 7,
reported: { time: null },
numeric_literals: [{ pointer: "/time", literal: "9007199254740993" }],
},
],
coverage: { total: 2, examined: 1, next_offset: 1, exhausted: false },
});
expect(JSON.stringify(preview)).not.toContain("original body");
expect(JSON.stringify(preview)).not.toContain("content_base64");
const complete = projectAnalysisView(parent, {
kind: "capture",
detail: "complete",
offset: 1,
limit: 1,
});
expect(complete.ok && complete.value).toMatchObject({
items: [report.records[1]],
coverage: { total: 2, examined: 1, next_offset: null, exhausted: true },
});
const empty = projectAnalysisView(parent, {
kind: "capture",
detail: "preview",
offset: 50,
limit: 1,
});
expect(empty.ok && empty.value).toMatchObject({
items: [],
coverage: {
status: "empty",
total: 2,
examined: 0,
next_offset: null,
exhausted: true,
},
});
});
it("retains explicitly unknown digests and rejects a different subject digest", () => {
const { parent, report } = capture();
const unknown = projectAnalysisView(
{
...parent,
subject: UNKNOWN_EVIDENCE_SUBJECT,
normalizedResult: {
...report,
artifact: { ...report.artifact, sha256: null },
},
},
{ kind: "summary" },
);
expect(unknown.ok && unknown.value).toMatchObject({
artifact: { sha256: null },
});
expect(unknown.ok && unknown.value.unknowns.join(" ")).toContain(
"excluded artifact digest",
);
if (parent.subject.identity.kind !== "file")
throw new Error("Expected fixture subject");
const mismatched = projectAnalysisView(
{
...parent,
subject: changedEvidenceSubject(parent.subject, {
sha256: "e".repeat(64),
}),
},
{ kind: "summary" },
);
expect(mismatched.ok).toBe(false);
});
it("rejects invalid ordinal coverage in a borrowed parent", () => {
const { parent, report } = capture();
const result = projectAnalysisView(
{
...parent,
normalizedResult: {
...report,
records: [report.records[0], report.records[0]],
},
},
{ kind: "summary" },
);
expect(result.ok).toBe(false);
});
const nativePreview = (
format: "mitmproxy" | "har",
request: Readonly<Record<string, unknown>>,
{
response = {
http_version: "HTTP/1.1",
status_code: 404,
reason: "Not Found",
content: "omitted body",
},
producerType = "integer",
sidecars,
flowType = "http",
redactions = [],
binaryFields = [],
}: {
readonly response?: Readonly<Record<string, unknown>>;
readonly producerType?: "integer" | "float";
readonly flowType?: string | null;
readonly binaryFields?: readonly Record<string, unknown>[];
readonly redactions?: readonly {
pointer: string;
reason: string;
scope?: string;
}[];
readonly sidecars?: readonly {
pointer: string;
producer_type: string;
literal: string;
}[];
} = {},
) => {
// The bridge records a numeric sidecar for every native number.
const literals =
sidecars ??
Object.entries({ request, response }).flatMap(([side, fields]) =>
Object.entries(fields)
.filter(([, value]) => typeof value === "number")
.map(([field, value]) => ({
pointer: `/${side}/${field}`,
producer_type: producerType,
literal: String(value),
})),
);
const artifact = {
path: "/recordings/flows.mitm",
sha256: "c".repeat(64),
bytes: 100,
};
const decoder = { id: "fixture", name: "Fixture", version: "1" };
const report = webNetworkCaptureSchema.parse({
artifact,
decoder,
format,
runtime_attribution: "unknown",
limitations: [],
container: {
reported: null,
numeric_literals: [],
redactions: [],
records_pointer: null,
},
total_records: 1,
records: [
{
ordinal: 0,
location: { kind: "byte-range", offset: 0, bytes: 10 },
reported: {
...(flowType === null ? {} : { type: flowType }),
request: { ...request, headers: [["Accept", "*/*"]] },
response,
},
binary_fields: binaryFields,
numeric_literals: literals,
redactions,
limitations: [],
},
],
});
const evidence = createEvidence({ ...artifact, format: "file" }, decoder, {
operation: "inspect_web_network_capture",
parameters: {},
result: report,
confidence: "observed",
authority: "historical-reference",
});
const preview = projectAnalysisView(
{
predicateType: evidence.predicate_type,
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: report,
subject: evidence.subject,
limitations: evidence.limitations,
},
{ kind: "capture", detail: "preview", offset: 0, limit: 1 },
);
if (!preview.ok || preview.value.kind !== "capture")
throw new Error("Expected a capture preview page.");
return preview.value;
};
it("previews the mitmproxy request target and status code as headline fields", () => {
const preview = nativePreview("mitmproxy", {
host: "example.test",
port: 443,
method: "GET",
scheme: "https",
authority: "",
path: "/users/42",
http_version: "HTTP/1.1",
});
expect(preview).toMatchObject({
items: [
{
reported: {
type: "http",
request: {
method: "GET",
scheme: "https",
host: "example.test",
port: 443,
authority: "",
path: "/users/42",
http_version: "HTTP/1.1",
},
response: {
http_version: "HTTP/1.1",
status_code: 404,
reason: "Not Found",
},
},
numeric_literals: [
{
pointer: "/request/port",
producer_type: "integer",
literal: "443",
},
{
pointer: "/response/status_code",
producer_type: "integer",
literal: "404",
},
],
},
],
});
expect(JSON.stringify(preview)).not.toContain("Accept");
expect(JSON.stringify(preview)).not.toContain("omitted body");
});
it("previews the asterisk-form OPTIONS target", () => {
expect(
nativePreview("mitmproxy", { method: "OPTIONS", path: "*" }).items[0]
?.reported,
).toMatchObject({ request: { method: "OPTIONS", path: "*" } });
});
it.each([
[
"an ambiguous absolute path",
"mitmproxy",
"https:user:password@example.test/a",
],
["a network-path reference", "mitmproxy", "//user:password@example.test/a"],
[
"a slash-backslash reference",
"mitmproxy",
"/\\user:password@example.test/a",
],
[
"a slash-backslash reference with an unparseable port",
"mitmproxy",
"/\\user:password@example.test:65536/a",
],
["a path with an at-sign", "mitmproxy", "/users/password@example"],
["a slash-tab reference", "mitmproxy", "/\t/user:password@example.test/a"],
["an oversized path", "mitmproxy", `/${"password".repeat(1024)}`],
["a nested path value", "mitmproxy", { content: "password ".repeat(64) }],
["a path in a non-mitmproxy record", "har", "/users/password"],
] as const)("keeps %s out of the preview", (_label, format, path) => {
const preview = nativePreview(format, { method: "GET", path });
const [item] = preview.items;
expect(item?.reported).toMatchObject({ request: { method: "GET" } });
expect(JSON.stringify(item?.reported)).not.toContain("password");
if (format === "har")
expect(JSON.stringify(item?.reported)).not.toContain("status_code");
});
it("bounds the serialized mitmproxy headline of each preview record", () => {
const control = "\u0001".repeat(8 * 1024);
const malformed = nativePreview("mitmproxy", {
method: "GET",
scheme: control,
host: control,
port: control,
authority: control,
path: `/${control}`,
});
expect(malformed.items[0]?.reported).toMatchObject({
request: { method: "GET" },
});
expect(
Buffer.byteLength(JSON.stringify(malformed.items[0]?.reported)),
).toBeLessThan(1024);
const escaped = nativePreview("mitmproxy", {
method: "GET",
path: `/${'"'.repeat(2 * 1024 - 1)}`,
});
expect(escaped.items[0]?.reported).toMatchObject({
request: { path: `/${'"'.repeat(2 * 1024 - 1)}` },
});
expect(
Buffer.byteLength(JSON.stringify(escaped.items[0]?.reported)),
).toBeLessThan(5 * 1024);
});
it("keeps producer floats out of integer mitmproxy headline slots", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", port: 443, path: "/a" },
{
response: {
http_version: "HTTP/1.1",
status_code: 404,
reason: "Not Found",
},
producerType: "float",
},
).items[0]?.reported;
expect(reported).toMatchObject({
request: { method: "GET", path: "/a" },
response: { reason: "Not Found" },
});
expect(reported).not.toMatchObject({ request: { port: 443 } });
expect(reported).not.toMatchObject({ response: { status_code: 404 } });
});
it.each([
[
"an oversized literal",
[
{
pointer: "/request/port",
producer_type: "integer",
literal: "4".repeat(100_000),
},
],
],
[
"a literal that does not represent the value",
[{ pointer: "/request/port", producer_type: "integer", literal: "444" }],
],
[
"duplicate sidecars",
[
{ pointer: "/request/port", producer_type: "integer", literal: "443" },
{ pointer: "/request/port", producer_type: "integer", literal: "443" },
],
],
])(
"keeps a port whose sidecar has %s out of the preview",
(_label, sidecars) => {
const [item] = nativePreview(
"mitmproxy",
{ method: "GET", port: 443, path: "/a" },
{ response: { http_version: "HTTP/1.1", reason: "OK" }, sidecars },
).items;
expect(item?.reported).toEqual({
type: "http",
request: { method: "GET", path: "/a" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
expect(item?.numeric_literals).toEqual([]);
},
);
it.each(["tcp", null])(
"adds no mitmproxy headline fields to a %s flow",
(flowType) => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a", port: 443 },
{ flowType },
).items[0]?.reported;
expect(reported).toEqual({
...(flowType === null ? {} : { type: flowType }),
request: { method: "GET" },
response: { http_version: "HTTP/1.1", reason: "Not Found" },
});
},
);
it("keeps a string target that carries a numeric sidecar out of the preview", () => {
const [item] = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
sidecars: [
{
pointer: "/request/path",
producer_type: "integer",
literal: "9".repeat(100_000),
},
],
},
).items;
expect(item?.reported).toEqual({
type: "http",
request: { method: "GET" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
expect(item?.numeric_literals).toEqual([]);
});
it("keeps a mitmproxy headline the record marks as redacted out of the preview", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", host: "secret", path: "/a" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
redactions: [
{ pointer: "/request/host", reason: "explicit-sensitive-value" },
],
},
).items[0]?.reported;
expect(reported).toEqual({
type: "http",
request: { method: "GET", path: "/a" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
});
it("rejects a non-number integer headline without throwing", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a", port: { toString: null } },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
sidecars: [
{ pointer: "/request/port", producer_type: "integer", literal: "443" },
],
},
).items[0]?.reported;
expect(reported).toEqual({
type: "http",
request: { method: "GET", path: "/a" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
});
it.each([
["the request", "/request", { method: "GET" }],
["the record root", "", {}],
] as const)(
"keeps mitmproxy headlines under a redacted %s out of the preview",
(_label, pointer, request) => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", host: "secret", path: "/secret" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
redactions: [{ pointer, reason: "explicit-sensitive-value" }],
},
).items[0]?.reported;
expect(JSON.stringify(reported)).not.toContain("secret");
expect(reported).toMatchObject({ request });
},
);
it("keeps a mitmproxy headline with a redacted byte descriptor out of the preview", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", host: "example.test", path: "/secret" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
binaryFields: [
{
pointer: "/request/path",
representation: "producer-bytes",
state: "redacted",
content_base64: null,
bytes: null,
sha256: null,
},
],
},
).items[0]?.reported;
expect(reported).toMatchObject({
request: { method: "GET", host: "example.test" },
});
expect(JSON.stringify(reported)).not.toContain("secret");
});
it("adds no mitmproxy headline fields when the flow type is redacted", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
redactions: [{ pointer: "/type", reason: "explicit-sensitive-value" }],
},
).items[0]?.reported;
expect(reported).toMatchObject({ request: { method: "GET" } });
expect(reported).not.toMatchObject({ request: { path: "/a" } });
});
it.each([
["the flow type", "/type"],
["the record root", ""],
])(
"adds no mitmproxy headline fields when %s carries a numeric sidecar",
(_label, pointer) => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
sidecars: [{ pointer, producer_type: "integer", literal: "1" }],
},
).items[0]?.reported;
expect(reported).toMatchObject({ request: { method: "GET" } });
expect(reported).not.toMatchObject({ request: { path: "/a" } });
},
);
const retainedBytes = (pointer: string, text: string) => {
const bytes = Buffer.from(text);
return {
pointer,
representation: "producer-bytes",
state: "retained",
content_base64: bytes.toString("base64"),
bytes: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
};
};
it("adds no mitmproxy headline fields when the flow type was producer bytes", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
binaryFields: [retainedBytes("/type", "http")],
},
).items[0]?.reported;
expect(reported).toMatchObject({ type: "http", request: { method: "GET" } });
expect(reported).not.toMatchObject({ request: { path: "/a" } });
});
it("keeps mitmproxy headlines under a byte-valued side out of the preview", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a", port: 443 },
{
response: { http_version: "HTTP/1.1", reason: "OK", status_code: 200 },
binaryFields: [
retainedBytes("/request", "GET /a"),
retainedBytes("/response", "200"),
],
},
).items[0]?.reported;
expect(reported).toEqual({
type: "http",
request: { method: "GET" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
});
it("previews a byte-backed path but not a byte-backed port", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a", port: 443 },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
binaryFields: [
retainedBytes("/request/path", "/a"),
retainedBytes("/request/port", "443"),
],
},
).items[0]?.reported;
expect(reported).toEqual({
type: "http",
request: { method: "GET", path: "/a" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
});
it("adds no mitmproxy headline fields when the flow type has a child facet", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
sidecars: [
{ pointer: "/type/child", producer_type: "integer", literal: "1" },
],
},
).items[0]?.reported;
expect(reported).toMatchObject({ request: { method: "GET" } });
expect(reported).not.toMatchObject({ request: { path: "/a" } });
});
it.each([
[
"a child sidecar",
{
sidecars: [
{ pointer: "/request/path/0", producer_type: "integer", literal: "1" },
],
},
],
[
"a child redaction",
{
redactions: [
{ pointer: "/request/path/0", reason: "explicit-sensitive-value" },
],
},
],
[
"HAR content bytes",
{
binaryFields: [
{
...retainedBytes("/request/path", "/a"),
representation: "har-base64-content",
},
],
},
],
[
"bytes that are not its text",
{ binaryFields: [retainedBytes("/request/path", "/b")] },
],
] as const)(
"keeps a mitmproxy path with %s out of the preview",
(_label, facets) => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", host: "example.test", path: "/a" },
{ response: { http_version: "HTTP/1.1", reason: "OK" }, ...facets },
).items[0]?.reported;
expect(reported).toEqual({
type: "http",
request: { method: "GET", host: "example.test" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
},
);
it.each([
["path", { method: "GET", path: "/\ud800" }, { method: "GET" }],
[
"host",
{ method: "GET", host: "a\udc00.test", path: "/a" },
{ method: "GET", path: "/a" },
],
])(
"keeps a mitmproxy %s with an unpaired surrogate out of the preview",
(_field, request, expected) => {
const reported = nativePreview("mitmproxy", request, {
response: { http_version: "HTTP/1.1", reason: "OK" },
}).items[0]?.reported;
expect(reported).toEqual({
type: "http",
request: expected,
response: { http_version: "HTTP/1.1", reason: "OK" },
});
},
);
it.each([
["an unrelated", "/".repeat(1_000_000), { method: "GET", path: "/a" }],
[
"a path-descendant",
`/request/path${"/0".repeat(500_000)}`,
{ method: "GET" },
],
])(
"indexes %s million-character facet pointer by its headline prefix only",
(_label, pointer, request) => {
// Count set additions, not elapsed time or heap, so every Node version
// catches a regression. Only the pointer and strings cut from it are this
// long here; indexing every ancestor added one per "/" it held.
let longAdditions = 0;
const add = Set.prototype.add;
const addSpy = vi.spyOn(Set.prototype, "add").mockImplementation(function (
this: Set<unknown>,
value: unknown,
) {
if (typeof value === "string" && value.length > 1_000) longAdditions++;
return add.call(this, value);
});
let reported: unknown;
try {
reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
sidecars: [{ pointer, producer_type: "integer", literal: "1" }],
},
).items[0]?.reported;
} finally {
addSpy.mockRestore();
}
expect(longAdditions).toBe(0);
expect(reported).toEqual({
type: "http",
request,
response: { http_version: "HTTP/1.1", reason: "OK" },
});
},
);
// Indexing only headline coordinates must not change what the preview
// withholds or keeps beside many facets the headline checks never consult.
it("keeps headline omissions and controls beside many unrelated facets", () => {
const unrelated = Array.from({ length: 20_000 }, (_, index) => ({
pointer: `/extension/values/${index}`,
producer_type: "integer",
literal: String(index),
}));
const [item] = nativePreview(
"mitmproxy",
{
method: "GET",
scheme: "https",
host: "secret.test",
port: 443,
path: "/a",
},
{
response: { http_version: "HTTP/1.1", reason: "OK", status_code: 200 },
sidecars: [
...unrelated,
{ pointer: "/request/port", producer_type: "integer", literal: "443" },
{
pointer: "/response/status_code",
producer_type: "integer",
literal: "200",
},
// A facet beneath the path says the producer held a container there.
{ pointer: "/request/path/0", producer_type: "integer", literal: "1" },
],
redactions: [
{ pointer: "/request/host", reason: "explicit-sensitive-value" },
],
},
).items;
expect(item?.reported).toEqual({
type: "http",
request: { method: "GET", scheme: "https", port: 443 },
response: { http_version: "HTTP/1.1", reason: "OK", status_code: 200 },
});
expect(item?.numeric_literals).toEqual([
{ pointer: "/request/port", producer_type: "integer", literal: "443" },
{
pointer: "/response/status_code",
producer_type: "integer",
literal: "200",
},
]);
});
it("keeps an unpaired-surrogate path out despite replacement-character bytes", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/\ud800" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
binaryFields: [retainedBytes("/request/path", "/�")],
},
).items[0]?.reported;
expect(reported).toEqual({
type: "http",
request: { method: "GET" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
});
it("keeps mitmproxy headlines under a numeric sidecar out of the preview", () => {
const [item] = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a", port: 443 },
{
response: { http_version: "HTTP/1.1", reason: "OK", status_code: 200 },
sidecars: [
{ pointer: "/request", producer_type: "integer", literal: "7" },
{ pointer: "/request/port", producer_type: "integer", literal: "443" },
{
pointer: "/response/status_code",
producer_type: "integer",
literal: "200",
},
],
},
).items;
expect(item?.reported).toEqual({
type: "http",
request: { method: "GET" },
response: { http_version: "HTTP/1.1", reason: "OK", status_code: 200 },
});
expect(item?.numeric_literals).toEqual([
{
pointer: "/response/status_code",
producer_type: "integer",
literal: "200",
},
]);
});
it("keeps sibling mitmproxy headlines next to an omitted property name", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", host: "example.test", path: "/a" },
{
response: { http_version: "HTTP/1.1", reason: "OK" },
redactions: [
{
pointer: "/request",
reason: "explicit-sensitive-value",
scope: "property-name",
},
],
},
).items[0]?.reported;
expect(reported).toMatchObject({
request: { method: "GET", host: "example.test", path: "/a" },
});
});
it("selects mitmproxy target fields from the request and the status from the response only", () => {
const reported = nativePreview(
"mitmproxy",
{ method: "GET", path: "/a", status_code: 200 },
{
response: { http_version: "HTTP/1.1", reason: "OK", path: "/extension" },
},
).items[0]?.reported;
expect(reported).toEqual({
type: "http",
request: { method: "GET", path: "/a" },
response: { http_version: "HTTP/1.1", reason: "OK" },
});
});
it.each(["scheme", "host", "port", "authority"])(
"keeps a userinfo-bearing mitmproxy %s out of the preview",
(field) => {
const preview = nativePreview("mitmproxy", {
method: "GET",
path: "/users/42",
[field]: "user:password@example.test",
});
const reported = preview.items[0]?.reported;
expect(reported).toMatchObject({
request: { method: "GET", path: "/users/42" },
});
expect(JSON.stringify(reported)).not.toContain("password");
},
);
it.each(["base64", "bytes", "sha256", "duplicate"] as const)(
"refuses inconsistent retained binary %s at parent admission",
(fault) => {
const { parent, report } = capture();
const record = report.records[0]!;
const binary = record.binary_fields[0]!;
if (binary.state !== "retained")
throw new Error("Expected retained source bytes");
const changed = {
...binary,
...(fault === "base64"
? { content_base64: "!!!!" }
: fault === "bytes"
? { bytes: binary.bytes + 1 }
: { sha256: "0".repeat(64) }),
};
const invalid = {
...report,
records: [
{
...record,
binary_fields: fault === "duplicate" ? [binary, binary] : [changed],
},
],
};
const projected = projectAnalysisView(
{ ...parent, normalizedResult: invalid },
{ kind: "capture", detail: "preview", offset: 0, limit: 1 },
);
expect(projected).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
},
);
it.each([
"/response/content/text",
"/response/content",
"/response",
"",
"binary-redaction",
"control",
])(
"respects retained response-body authority without altering raw facts: %s",
(marker) => {
const seed = timedCaptureEvidence([
["GET", "/api/items", [{ id: 1, name: "withheld-value" }]],
]);
const report = webNetworkCaptureSchema.parse(seed.normalized_result);
const record = report.records[0]!;
if (marker === "binary-redaction")
record.binary_fields.push({
pointer: "/response/content/text",
representation: "har-base64-content",
state: "redacted",
content_base64: null,
bytes: null,
sha256: null,
});
else if (marker !== "control")
record.redactions.push({
pointer: marker,
reason: "explicit-sensitive-value",
});
const evidence = createEvidence(
{
path: report.artifact.path,
sha256: report.artifact.sha256!,
format: "file",
},
report.decoder,
{
operation: seed.operation,
parameters: seed.parameters,
result: report,
},
);
const parent = {
predicateType: evidence.predicate_type,
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: evidence.normalized_result,
subject: evidence.subject,
parameters: evidence.parameters,
limitations: evidence.limitations,
};
const state = projectAnalysisView(
parent,
analysisViewRequestSchema.parse({ kind: "environment-state" }),
);
if (!state.ok || state.value.kind !== "environment-state")
throw new Error("Expected retained state projection");
expect(
JSON.stringify(state.value.entities).includes("withheld-value"),
).toBe(marker === "control");
const complete = projectAnalysisView(parent, {
kind: "capture",
detail: "complete",
offset: 0,
limit: 1,
});
expect(
complete.ok && JSON.stringify(complete.value).includes("withheld-value"),
).toBe(true);
},
);