refactor(test): keep coverage at behavioral boundaries (#474)
* refactor(test): keep coverage at behavioral boundaries * fix(ci): restore package workflow temp-root classification
This commit is contained in:
@@ -0,0 +1,219 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
ArtifactOperationError,
|
||||
BinaryTargetError,
|
||||
HopperProcessError,
|
||||
PermissionRequiredError,
|
||||
ProviderAdapterError,
|
||||
ReplayPlanStaleError,
|
||||
UnknownRegistryError,
|
||||
projectAnalysisError,
|
||||
} from "./errors.js";
|
||||
|
||||
describe("analysis error projection: provider failures", () => {
|
||||
it("preserves detached, actionable provider diagnostics", () => {
|
||||
const diagnostics = {
|
||||
runtime_root: "/tmp/rea-ghidra-fixture",
|
||||
profile_digest: "a".repeat(64),
|
||||
exit_code: 1,
|
||||
};
|
||||
const error = new ProviderAdapterError("ghidra", "health", {
|
||||
diagnostics,
|
||||
});
|
||||
|
||||
expect(error.diagnostics).not.toBe(diagnostics);
|
||||
expect(projectAnalysisError(error)).toMatchObject({
|
||||
details: {
|
||||
provider_id: "ghidra",
|
||||
operation: "health",
|
||||
diagnostics,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("maps the Linux startup compatibility exit codes without host internals", () => {
|
||||
const expected = [
|
||||
[70, "private_display_unavailable"],
|
||||
[71, "x11_authorization_failed"],
|
||||
[72, "unsupported_hopper_build"],
|
||||
[73, "invalid_launch_command"],
|
||||
[74, "process_ownership_mismatch"],
|
||||
[75, "hopper_exited_during_startup"],
|
||||
[76, "unsupported_demo_dialog"],
|
||||
[77, "unexpected_display_geometry"],
|
||||
[78, "x11_input_failed"],
|
||||
[79, "runtime_dependency_unavailable"],
|
||||
[80, "x11_socket_directory_unusable"],
|
||||
] as const;
|
||||
|
||||
for (const [exitCode, code] of expected) {
|
||||
const projected = projectAnalysisError(new HopperProcessError(exitCode));
|
||||
expect(projected).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: { failure_code: code, exit_code: exitCode },
|
||||
});
|
||||
expect(projected.message.length).toBeGreaterThan(20);
|
||||
expect(JSON.stringify(projected)).not.toContain("/proc/");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis error projection: caller contract", () => {
|
||||
it("maps representative failures without exposing causes", () => {
|
||||
const secretCause = new Error("secret-token");
|
||||
const projected = [
|
||||
projectAnalysisError(
|
||||
new AnalysisInputError("overview", { cause: secretCause }),
|
||||
),
|
||||
projectAnalysisError(
|
||||
new AnalysisCapabilityUnavailableError("fixture", "overview", "absent"),
|
||||
),
|
||||
projectAnalysisError(
|
||||
new BinaryTargetError("/local/targets/app", "invalid", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
),
|
||||
projectAnalysisError(
|
||||
new ReplayPlanStaleError("a".repeat(64), "b".repeat(64)),
|
||||
),
|
||||
];
|
||||
|
||||
expect(projected.map(({ code }) => code)).toEqual([
|
||||
"invalid_request",
|
||||
"capability_unavailable",
|
||||
"target_unavailable",
|
||||
"plan_stale",
|
||||
]);
|
||||
expect(projected[1]).toMatchObject({ category: "unsupported_provider" });
|
||||
expect(projected[2]).toMatchObject({
|
||||
details: { path: "/local/targets/app" },
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("secret-token");
|
||||
});
|
||||
|
||||
it("preserves exact artifact-integrity coordinates", () => {
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new ArtifactOperationError("inventory_artifact", "integrity", {
|
||||
logicalPath: "main.js",
|
||||
declaredSha256: "a".repeat(64),
|
||||
calculatedSha256: "b".repeat(64),
|
||||
unpacked: true,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
category: "integrity_mismatch",
|
||||
details: {
|
||||
logical_path: "main.js",
|
||||
declared_sha256: "a".repeat(64),
|
||||
calculated_sha256: "b".repeat(64),
|
||||
unpacked: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"configure",
|
||||
false,
|
||||
false,
|
||||
"Add the exact missing scope beneath the administrator ceiling, then retry.",
|
||||
],
|
||||
[
|
||||
"elicit",
|
||||
false,
|
||||
true,
|
||||
"Approve the exact missing scope, then retry the operation.",
|
||||
],
|
||||
[
|
||||
"restart",
|
||||
true,
|
||||
false,
|
||||
"Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client.",
|
||||
],
|
||||
] as const)(
|
||||
"projects %s permission remediation into stable protocol fields",
|
||||
(remediation, restartRequired, elicitationSupported, action) => {
|
||||
const projected = projectAnalysisError(
|
||||
new PermissionRequiredError({
|
||||
requested: {
|
||||
capability: "evidence_read",
|
||||
roots: ["/workspace/evidence.json"],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:evidence",
|
||||
},
|
||||
missing: { roots: ["/workspace/evidence.json"] },
|
||||
ceiling: null,
|
||||
remediation,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(projected.remediation).toEqual({
|
||||
action,
|
||||
restart_required: restartRequired,
|
||||
elicitation_supported: elicitationSupported,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("gives missing residual unknowns lookup-specific remediation", () => {
|
||||
expect(
|
||||
projectAnalysisError(new UnknownRegistryError("not-found")),
|
||||
).toMatchObject({
|
||||
code: "execution_failure",
|
||||
message:
|
||||
"The requested residual unknown does not exist in this session. Check the unknown_id and try again.",
|
||||
remediation: {
|
||||
action:
|
||||
"Check that the unknown_id belongs to this session, then retry.",
|
||||
},
|
||||
details: { reason: "not-found" },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains schema-authored input guidance", () => {
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new AnalysisInputError("find_changed_behavior", undefined, [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Supply either existing comparisons or one investigation_run",
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Supply either existing comparisons or one investigation_run",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("distinguishes disabled integrity continuation from format support", () => {
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new ArtifactOperationError("inventory_artifact", "policy"),
|
||||
),
|
||||
).toMatchObject({
|
||||
code: "artifact_operation_failed",
|
||||
category: "unavailable",
|
||||
message: expect.stringContaining(
|
||||
"REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED=true",
|
||||
),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
analyzeBytecodeArtifacts,
|
||||
bytecodeAnalysisSchema,
|
||||
classifyProvenance,
|
||||
detectArtifactFormat,
|
||||
detectBytecodeFamily,
|
||||
type BytecodeArtifact,
|
||||
} from "./bytecodeProvider.js";
|
||||
|
||||
describe("bytecode provider", () => {
|
||||
it("detects JVM family from extensions", () => {
|
||||
expect(detectBytecodeFamily("App.class")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("app.jar")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("webapp.war")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("app.ear")).toBe("jvm");
|
||||
});
|
||||
|
||||
it("detects Python family from extensions", () => {
|
||||
expect(detectBytecodeFamily("module.pyc")).toBe("python");
|
||||
expect(detectBytecodeFamily("module.pyo")).toBe("python");
|
||||
expect(detectBytecodeFamily("package.whl")).toBe("python");
|
||||
expect(detectBytecodeFamily("app.pyz")).toBe("python");
|
||||
expect(detectBytecodeFamily("app.zipapp")).toBe("python");
|
||||
});
|
||||
|
||||
it("returns null for unknown extensions", () => {
|
||||
expect(detectBytecodeFamily("readme.txt")).toBeNull();
|
||||
expect(detectBytecodeFamily("script.js")).toBeNull();
|
||||
});
|
||||
|
||||
it("detects artifact format from path", () => {
|
||||
expect(detectArtifactFormat("App.class")).toBe("class");
|
||||
expect(detectArtifactFormat("lib.jar")).toBe("jar");
|
||||
expect(detectArtifactFormat("web.war")).toBe("war");
|
||||
expect(detectArtifactFormat("mod.pyc")).toBe("pyc");
|
||||
expect(detectArtifactFormat("pkg.whl")).toBe("whl");
|
||||
expect(detectArtifactFormat("unknown.xyz")).toBeNull();
|
||||
});
|
||||
|
||||
it("classifies standard library provenance", () => {
|
||||
expect(classifyProvenance("/usr/lib/stdlib", "java.lang.String")).toBe(
|
||||
"standard_library",
|
||||
);
|
||||
expect(
|
||||
classifyProvenance("/lib/python3.10/site-packages/numpy", "__init__"),
|
||||
).toBe("standard_library");
|
||||
});
|
||||
|
||||
it("classifies generated provenance", () => {
|
||||
expect(classifyProvenance("/build/generated/src", "GeneratedClass")).toBe(
|
||||
"generated",
|
||||
);
|
||||
expect(
|
||||
classifyProvenance("/__pycache__/module.cpython-310.pyc", "module"),
|
||||
).toBe("generated");
|
||||
});
|
||||
|
||||
it("classifies vendored provenance", () => {
|
||||
expect(classifyProvenance("/vendor/libs/lib.jar", "VendorLib")).toBe(
|
||||
"vendored",
|
||||
);
|
||||
expect(classifyProvenance("/third_party/pkg/module.pyc", "module")).toBe(
|
||||
"vendored",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies application provenance", () => {
|
||||
expect(classifyProvenance("/src/main/App.java", "com.example.App")).toBe(
|
||||
"application",
|
||||
);
|
||||
expect(classifyProvenance("/src/app.py", "main")).toBe("application");
|
||||
});
|
||||
|
||||
it("analyzes bytecode artifacts and computes summary", () => {
|
||||
const artifacts: BytecodeArtifact[] = [
|
||||
{
|
||||
path: "src/App.class",
|
||||
family: "jvm",
|
||||
format: "class",
|
||||
size: 1000,
|
||||
digest: "a".repeat(64),
|
||||
symbols: [
|
||||
{
|
||||
name: "com.example.App",
|
||||
raw_location: "0x1000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "application",
|
||||
is_public: true,
|
||||
},
|
||||
{
|
||||
name: "java.lang.String",
|
||||
raw_location: "0x2000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "standard_library",
|
||||
is_public: true,
|
||||
},
|
||||
],
|
||||
is_standard_library: false,
|
||||
is_generated: false,
|
||||
is_vendored: false,
|
||||
},
|
||||
{
|
||||
path: "lib/generated/Generated.class",
|
||||
family: "jvm",
|
||||
format: "class",
|
||||
size: 500,
|
||||
digest: "b".repeat(64),
|
||||
symbols: [
|
||||
{
|
||||
name: "GeneratedClass",
|
||||
raw_location: "0x3000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "generated",
|
||||
is_public: false,
|
||||
},
|
||||
],
|
||||
is_standard_library: false,
|
||||
is_generated: true,
|
||||
is_vendored: false,
|
||||
},
|
||||
];
|
||||
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
|
||||
expect(result.family).toBe("jvm");
|
||||
expect(result.total_symbols).toBe(3);
|
||||
expect(result.application_symbols).toBe(1);
|
||||
expect(result.standard_library_symbols).toBe(1);
|
||||
expect(result.generated_symbols).toBe(1);
|
||||
expect(result.vendored_symbols).toBe(0);
|
||||
|
||||
// Validate schema
|
||||
const parsed = bytecodeAnalysisSchema.safeParse(result);
|
||||
expect(parsed.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -37,7 +37,6 @@ export const bytecodeSymbolSchema = z.strictObject({
|
||||
/** Whether the symbol is accessible (public). */
|
||||
is_public: z.boolean().default(false),
|
||||
});
|
||||
export type BytecodeSymbol = z.infer<typeof bytecodeSymbolSchema>;
|
||||
|
||||
/** A discovered bytecode artifact (class file, wheel, etc). */
|
||||
export const bytecodeArtifactSchema = z.strictObject({
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
authEventsByProtocol,
|
||||
authFlowDuration,
|
||||
customProtocolCaptureSchema,
|
||||
correlateProcessIdentity,
|
||||
failedAuthEvents,
|
||||
framesByTransport,
|
||||
looksLikeCredentialFrame,
|
||||
successfulAuthEvents,
|
||||
type AuthFlowEvent,
|
||||
type ProtocolFrame,
|
||||
} from "./customProtocolCapture.js";
|
||||
|
||||
const sampleFrames: ProtocolFrame[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 100,
|
||||
transport: "tcp",
|
||||
direction: "sent",
|
||||
source_pid: 100,
|
||||
dest_pid: 200,
|
||||
source_endpoint: "127.0.0.1:8080",
|
||||
dest_endpoint: "127.0.0.1:9090",
|
||||
raw_data: "hello",
|
||||
decoded_content: "hello",
|
||||
size: 5,
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 200,
|
||||
transport: "udp",
|
||||
direction: "received",
|
||||
source_pid: 200,
|
||||
dest_pid: 100,
|
||||
source_endpoint: "127.0.0.1:9090",
|
||||
dest_endpoint: "127.0.0.1:8080",
|
||||
raw_data: "world",
|
||||
decoded_content: "world",
|
||||
size: 5,
|
||||
truncated: false,
|
||||
},
|
||||
];
|
||||
|
||||
const sampleAuthEvents: AuthFlowEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 100,
|
||||
stage: "init",
|
||||
protocol: "OAuth2",
|
||||
token_type: "Bearer",
|
||||
token_lifecycle: "issued",
|
||||
correlation_id: "abc-123",
|
||||
credentials_redacted: true,
|
||||
succeeded: false,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 500,
|
||||
stage: "success",
|
||||
protocol: "OAuth2",
|
||||
token_type: "Bearer",
|
||||
token_lifecycle: "issued",
|
||||
correlation_id: "abc-123",
|
||||
credentials_redacted: true,
|
||||
succeeded: true,
|
||||
error: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("custom protocol capture", () => {
|
||||
it("validates a well-formed capture", () => {
|
||||
const capture = {
|
||||
transport: "tcp" as const,
|
||||
frames: sampleFrames,
|
||||
auth_events: sampleAuthEvents,
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
const result = customProtocolCaptureSchema.safeParse(capture);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("correlates process identity", () => {
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 100)).toBe(true);
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 200)).toBe(true);
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 999)).toBe(false);
|
||||
});
|
||||
|
||||
it("filters frames by transport", () => {
|
||||
const tcpFrames = framesByTransport(sampleFrames, "tcp");
|
||||
expect(tcpFrames).toHaveLength(1);
|
||||
const udpFrames = framesByTransport(sampleFrames, "udp");
|
||||
expect(udpFrames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("detects credential-like frames", () => {
|
||||
const credFrame: ProtocolFrame = {
|
||||
...sampleFrames[0]!,
|
||||
decoded_content: { password: "secret" },
|
||||
};
|
||||
expect(looksLikeCredentialFrame(credFrame)).toBe(true);
|
||||
expect(looksLikeCredentialFrame(sampleFrames[0]!)).toBe(false);
|
||||
});
|
||||
|
||||
it("filters auth events by protocol", () => {
|
||||
const oauthEvents = authEventsByProtocol(sampleAuthEvents, "OAuth2");
|
||||
expect(oauthEvents).toHaveLength(2);
|
||||
const otherEvents = authEventsByProtocol(sampleAuthEvents, "SAML");
|
||||
expect(otherEvents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("gets successful auth events", () => {
|
||||
const success = successfulAuthEvents(sampleAuthEvents);
|
||||
expect(success).toHaveLength(1);
|
||||
expect(success[0]!.succeeded).toBe(true);
|
||||
});
|
||||
|
||||
it("gets failed auth events", () => {
|
||||
const failed = failedAuthEvents(sampleAuthEvents);
|
||||
expect(failed).toHaveLength(1);
|
||||
expect(failed[0]!.succeeded).toBe(false);
|
||||
});
|
||||
|
||||
it("computes auth flow duration", () => {
|
||||
const duration = authFlowDuration(sampleAuthEvents);
|
||||
expect(duration).toBe(400);
|
||||
});
|
||||
|
||||
it("returns null for empty auth events", () => {
|
||||
expect(authFlowDuration([])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,6 @@ export type TransportType = z.infer<typeof transportTypeSchema>;
|
||||
|
||||
/** Direction of a protocol frame. */
|
||||
export const frameDirectionSchema = z.enum(["sent", "received", "intercepted"]);
|
||||
export type FrameDirection = z.infer<typeof frameDirectionSchema>;
|
||||
|
||||
/** A captured protocol frame. */
|
||||
export const protocolFrameSchema = z.strictObject({
|
||||
@@ -57,7 +56,6 @@ export const authStageSchema = z.enum([
|
||||
"failure",
|
||||
"success",
|
||||
]);
|
||||
export type AuthStage = z.infer<typeof authStageSchema>;
|
||||
|
||||
/** Token lifecycle event. */
|
||||
export const tokenLifecycleEventSchema = z.enum([
|
||||
@@ -67,7 +65,6 @@ export const tokenLifecycleEventSchema = z.enum([
|
||||
"revoked",
|
||||
"renewed",
|
||||
]);
|
||||
export type TokenLifecycleEvent = z.infer<typeof tokenLifecycleEventSchema>;
|
||||
|
||||
/** A captured authentication flow event. */
|
||||
export const authFlowEventSchema = z.strictObject({
|
||||
@@ -107,7 +104,6 @@ export const customProtocolCaptureSchema = z.strictObject({
|
||||
/** Whether credentials were detected. */
|
||||
credentials_detected: z.boolean().default(false),
|
||||
});
|
||||
export type CustomProtocolCapture = z.infer<typeof customProtocolCaptureSchema>;
|
||||
|
||||
/** Correlate a frame with process identity. */
|
||||
export function correlateProcessIdentity(
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { electronActiveObservationResultSchema } from "./electronActiveObservation.js";
|
||||
|
||||
/** Create a bounded active-capture result for MCP contract tests. */
|
||||
export const createElectronActiveObservationFixtureResult = (
|
||||
applicationPath: string,
|
||||
) =>
|
||||
electronActiveObservationResultSchema.parse({
|
||||
schema_version: 1,
|
||||
application: {
|
||||
executable_path: process.execPath,
|
||||
application_path: applicationPath,
|
||||
electron_version: "test-electron",
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "submit",
|
||||
kind: "click",
|
||||
window_index: 0,
|
||||
target: "window:1",
|
||||
status: "completed",
|
||||
elapsed_ms: 3,
|
||||
error: null,
|
||||
},
|
||||
],
|
||||
windows: [
|
||||
{
|
||||
window_id: "window:1",
|
||||
web_contents_id: "webContents:1",
|
||||
url: "file:///tmp/app.html",
|
||||
title: "Fixture",
|
||||
visible: true,
|
||||
destroyed: false,
|
||||
},
|
||||
],
|
||||
windows_truncated: false,
|
||||
processes: {
|
||||
items: [{ pid: 1234, type: "Browser", name: null, service_name: null }],
|
||||
truncated: false,
|
||||
},
|
||||
ipc: {
|
||||
events: [
|
||||
{
|
||||
sequence: 1,
|
||||
kind: "main-handler-invocation",
|
||||
channel: "readiness:echo",
|
||||
argument_shapes: ["string"],
|
||||
result_shape: "object",
|
||||
process_type: "main",
|
||||
error: false,
|
||||
},
|
||||
],
|
||||
observed: 1,
|
||||
retained: 1,
|
||||
truncated: false,
|
||||
},
|
||||
limitations: [
|
||||
"IPC payloads are represented only by bounded value shapes; values are never retained.",
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,388 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
containsProcess,
|
||||
getDescendants,
|
||||
maxTreeDepth,
|
||||
reconstructProcessTree,
|
||||
type ProcessTreeEvent,
|
||||
} from "./eventProcessTree.js";
|
||||
|
||||
describe("event-backed process tree reconstruction", () => {
|
||||
it("reconstructs a simple process tree", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 3,
|
||||
at_ms: 30,
|
||||
type: "exit",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.processes).toHaveLength(2);
|
||||
expect(result.events_consumed).toBe(4);
|
||||
expect(result.events_unmatched).toBe(0);
|
||||
expect(result.short_lived_descendants).toBe(2);
|
||||
});
|
||||
|
||||
it("detects short-lived descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: "/short",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 11,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.short_lived_descendants).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree transitions", () => {
|
||||
it("detects re-exec", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "re_exec",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/newroot",
|
||||
arguments: ["--new"],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_re_exec).toBe(true);
|
||||
const root = result.processes.find((p) => p.pid === 1)!;
|
||||
expect(root.is_re_exec).toBe(true);
|
||||
expect(root.executable).toBe("/newroot");
|
||||
});
|
||||
|
||||
it("detects reparenting", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "reparent",
|
||||
pid: 2,
|
||||
ppid: 0,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: 1,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_reparenting).toBe(true);
|
||||
const child = result.processes.find((p) => p.pid === 2)!;
|
||||
expect(child.is_reparented).toBe(true);
|
||||
expect(child.previous_ppid).toBe(1);
|
||||
expect(child.ppid).toBe(0);
|
||||
});
|
||||
|
||||
it("reports unmatched events for unknown exits", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "exit",
|
||||
pid: 999,
|
||||
ppid: null,
|
||||
process_name: null,
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 1,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.events_unmatched).toBe(1);
|
||||
expect(result.processes).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree queries", () => {
|
||||
it("gets descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child1",
|
||||
executable: "/c1",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "grandchild",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
const descendants = getDescendants(result.processes, 1);
|
||||
expect(descendants).toHaveLength(2);
|
||||
expect(descendants).toContain(2);
|
||||
expect(descendants).toContain(3);
|
||||
});
|
||||
|
||||
it("checks process containment", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(containsProcess(result.processes, 1)).toBe(true);
|
||||
expect(containsProcess(result.processes, 999)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree depth and types", () => {
|
||||
it("computes max tree depth", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/c",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "gc",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(maxTreeDepth(result.processes, 1)).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,6 @@ export const processEventTypeSchema = z.enum([
|
||||
"thread_create",
|
||||
"thread_exit",
|
||||
]);
|
||||
export type ProcessEventType = z.infer<typeof processEventTypeSchema>;
|
||||
|
||||
/** A single event-backed process-tree event. */
|
||||
export const processTreeEventSchema = z.strictObject({
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
export const ghidraFunctionClassification = () => ({
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
provenance: "ghidra-function-manager" as const,
|
||||
});
|
||||
|
||||
export const ghidraFunctionIdentity = () => ({
|
||||
address: "0x401000",
|
||||
name: "fixture_main",
|
||||
classification: ghidraFunctionClassification(),
|
||||
});
|
||||
|
||||
const ghidraReferenceKind = () => ({
|
||||
available: true as const,
|
||||
provenance: "ghidra-reference-manager" as const,
|
||||
type: "DATA",
|
||||
flow: false,
|
||||
call: false,
|
||||
jump: false,
|
||||
data: true,
|
||||
read: true,
|
||||
write: false,
|
||||
indirect: false,
|
||||
computed: false,
|
||||
conditional: false,
|
||||
terminal: false,
|
||||
primary: true,
|
||||
operand_index: 0,
|
||||
external: false,
|
||||
});
|
||||
|
||||
export const ghidraReferenceEdge = () => ({
|
||||
source_address: "0x401001",
|
||||
target_address: "0x402000",
|
||||
source_procedure: ghidraFunctionIdentity(),
|
||||
target_procedure: null,
|
||||
kind: ghidraReferenceKind(),
|
||||
});
|
||||
|
||||
export const ghidraBounded = (items: readonly JsonValue[]) => ({
|
||||
items: [...items],
|
||||
total: items.length,
|
||||
returned: items.length,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
export const ghidraNativeApiBoundary = (mappingsTruncated = false) => ({
|
||||
available: true as const,
|
||||
provenance: "ghidra-high-function",
|
||||
signature_source: "analysis",
|
||||
calling_convention: "__cdecl",
|
||||
return_type: {
|
||||
role: "return" as const,
|
||||
ordinal: null,
|
||||
name: null,
|
||||
data_type: "int",
|
||||
size_bytes: 4,
|
||||
storage: "EAX:4",
|
||||
confidence: "medium" as const,
|
||||
evidence: [
|
||||
{
|
||||
kind: "signature-source" as const,
|
||||
source: "ghidra-function-manager",
|
||||
detail: "Function signature source is analysis.",
|
||||
},
|
||||
{
|
||||
kind: "decompiler-type" as const,
|
||||
source: "ghidra-high-function",
|
||||
detail: "HighFunction recovered data type int.",
|
||||
},
|
||||
],
|
||||
decompiler_artifacts: [
|
||||
"recovered-signature" as const,
|
||||
"register-or-stack-storage" as const,
|
||||
],
|
||||
},
|
||||
parameters: [],
|
||||
parameters_truncated: false,
|
||||
jump_tables: [
|
||||
{
|
||||
dispatch_address: "0x401010",
|
||||
data_sources: [
|
||||
{
|
||||
address: "0x403000",
|
||||
provenance: "ghidra-decompiler-load-table" as const,
|
||||
entry_size_bytes: 4,
|
||||
entry_count: 2,
|
||||
confidence: "high" as const,
|
||||
evidence: [
|
||||
{
|
||||
kind: "jump-table" as const,
|
||||
source: "ghidra-high-function",
|
||||
detail: "Decompiler load table starts at 0x403000.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
data_sources_truncated: false,
|
||||
mappings: [
|
||||
{
|
||||
case_value: 0,
|
||||
target_address: "0x401020",
|
||||
data_addresses: ["0x403000"],
|
||||
confidence: "medium" as const,
|
||||
evidence: [
|
||||
{
|
||||
kind: "jump-table" as const,
|
||||
source: "ghidra-high-function",
|
||||
detail: "Recovered target 0x401020 from dispatch 0x401010.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
mappings_truncated: mappingsTruncated,
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
jump_tables_truncated: false,
|
||||
pseudocode: {
|
||||
classification: "decompiler-generated-non-source" as const,
|
||||
compilable: false as const,
|
||||
},
|
||||
decompiler_artifacts: [
|
||||
"recovered-signature" as const,
|
||||
"register-and-stack-variables" as const,
|
||||
"compiler-generated-control-flow" as const,
|
||||
"pointer-arithmetic" as const,
|
||||
"pseudocode" as const,
|
||||
],
|
||||
limitations: [
|
||||
"Pseudocode is neither original source nor guaranteed to compile.",
|
||||
],
|
||||
});
|
||||
|
||||
export const ghidraFunctionDossier = (
|
||||
includeAssembly = true,
|
||||
mappingsTruncated = false,
|
||||
): JsonValue => {
|
||||
const pseudocode = "int fixture_main(void) { return 42; }";
|
||||
return {
|
||||
procedure: {
|
||||
...ghidraFunctionIdentity(),
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: pseudocode,
|
||||
total_chars: [...pseudocode].length,
|
||||
returned_chars: [...pseudocode].length,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: ghidraBounded(
|
||||
includeAssembly ? ["0x401000: CALL 0x401020", "0x401005: RET"] : [],
|
||||
),
|
||||
comments: ghidraBounded([]),
|
||||
callers: ghidraBounded([]),
|
||||
callees: ghidraBounded([]),
|
||||
incoming_references: ghidraBounded([]),
|
||||
outgoing_references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
referenced_strings: ghidraBounded([
|
||||
{
|
||||
address: "0x402000",
|
||||
value: "inventory fixture",
|
||||
source_address: "0x401001",
|
||||
},
|
||||
]),
|
||||
referenced_names: ghidraBounded([]),
|
||||
basic_blocks: ghidraBounded([
|
||||
{ start: "0x401000", end: "0x401006", successors: [] },
|
||||
]),
|
||||
instruction_scan: { scanned: 2, truncated: false },
|
||||
native_api: ghidraNativeApiBoundary(mappingsTruncated),
|
||||
limitations: [
|
||||
"Unresolved computed or indirect flows without target addresses are not represented as reference edges.",
|
||||
"Thunk and external classifications are Ghidra FunctionManager observations; they do not resolve targetless calls.",
|
||||
"Pseudocode and assembly are Ghidra-specific representations, not original source or Hopper-equivalent text.",
|
||||
],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
parseDocuments,
|
||||
parseAddressedPage,
|
||||
parseListCount,
|
||||
parseNames,
|
||||
parseProcedures,
|
||||
parseRelatedAddresses,
|
||||
parseSegments,
|
||||
} from "./hopperValues.js";
|
||||
|
||||
describe("Hopper boundary values", () => {
|
||||
it("parses Hopper's address-keyed name and string maps", () => {
|
||||
expect(parseNames({ "0x1000": "_main" })).toEqual({
|
||||
ok: true,
|
||||
value: [{ address: "0x1000", name: "_main" }],
|
||||
});
|
||||
expect(
|
||||
parseListCount({ "0x1000": "hello", "0x2000": "world" }, "strings"),
|
||||
).toEqual({ ok: true, value: 2 });
|
||||
});
|
||||
|
||||
it("parses direct and wrapped protocol shapes", () => {
|
||||
expect(parseProcedures({ procedures: { "0x1": "main" } })).toEqual({
|
||||
ok: true,
|
||||
value: [{ address: "0x1", name: "main" }],
|
||||
});
|
||||
expect(parseNames({ names: [{ address: "0x2", name: "label" }] }).ok).toBe(
|
||||
true,
|
||||
);
|
||||
expect(parseRelatedAddresses({ callers: ["0x3"] }, "callers")).toEqual({
|
||||
ok: true,
|
||||
value: ["0x3"],
|
||||
});
|
||||
expect(
|
||||
parseSegments([
|
||||
{
|
||||
name: "__TEXT",
|
||||
start: "0x1",
|
||||
end: "0x2",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: null,
|
||||
},
|
||||
]),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: [
|
||||
{
|
||||
name: "__TEXT",
|
||||
start: "0x1",
|
||||
end: "0x2",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(parseDocuments(["fixture"])).toEqual({
|
||||
ok: true,
|
||||
value: ["fixture"],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: true,
|
||||
},
|
||||
{
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 0,
|
||||
next_offset: 100,
|
||||
has_more: false,
|
||||
},
|
||||
])("rejects contradictory page continuation metadata", (page) => {
|
||||
const result = parseAddressedPage(page);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["procedures", () => parseProcedures(["not-a-map"])],
|
||||
["names", () => parseNames([{ address: 1, name: "bad" }])],
|
||||
["relations", () => parseRelatedAddresses([1], "callees")],
|
||||
["segments", () => parseSegments([{ name: 1 }])],
|
||||
["documents", () => parseDocuments([1])],
|
||||
])(
|
||||
"rejects malformed %s instead of manufacturing empty output",
|
||||
(_label, parse) => {
|
||||
const result = parse();
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareManagedMembers,
|
||||
managedMemberComparisonResultSchema,
|
||||
} from "./managedMemberComparison.js";
|
||||
import { inspectManagedMembersBytes } from "../dotnet/ManagedMemberInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
} from "../dotnet/ManagedPe.fixture.js";
|
||||
|
||||
const comparisonLimits = {
|
||||
max_method_matches: 100,
|
||||
max_field_matches: 100,
|
||||
max_candidates: 10,
|
||||
};
|
||||
|
||||
describe("managed member comparison", () => {
|
||||
it("remaps renamed methods by exact CIL/signature without using names", () => {
|
||||
const leftBytes = buildManagedPeFixture();
|
||||
const rightBytes = buildManagedPeFixture({
|
||||
mvid: Buffer.from("00112233445566778899aabbccddeefe", "hex"),
|
||||
typeName: "A",
|
||||
typeNamespace: "X",
|
||||
methodName: "b",
|
||||
fieldName: "c",
|
||||
});
|
||||
const left = inspect(leftBytes, "/tmp/left.dll");
|
||||
const right = inspect(rightBytes, "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: left.result },
|
||||
{ evidenceId: right.evidenceId, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.algorithm.name_matching).toBe("not-used");
|
||||
expect(result.left.mvid).toBe("00112233-4455-6677-8899-aabbccddeeff");
|
||||
expect(result.right.mvid).toBe("33221100-5544-7766-8899-aabbccddeefe");
|
||||
expect(result.matching.exact_il_signature).toBe(1);
|
||||
expect(result.methods).toEqual([
|
||||
expect.objectContaining({
|
||||
status: "unchanged",
|
||||
left: expect.objectContaining({ token: "0x06000001", name: "Main" }),
|
||||
right: expect.objectContaining({ token: "0x06000001", name: "b" }),
|
||||
match: expect.objectContaining({
|
||||
status: "matched",
|
||||
basis: "exact-il-signature",
|
||||
confidence: "exact",
|
||||
}),
|
||||
dimensions: [],
|
||||
}),
|
||||
]);
|
||||
expect(result.limitations).toContain(
|
||||
"Names are reported as observations but are not used as a matching basis.",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses structural method shape when build-local token operands drift", () => {
|
||||
const leftBytes = buildManagedPeFixture();
|
||||
const rightBytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.from([
|
||||
0x32, 0x02, 0x7b, 0x02, 0x00, 0x00, 0x04, 0x28, 0x02, 0x00, 0x00, 0x0a,
|
||||
0x2a,
|
||||
]),
|
||||
});
|
||||
const left = inspect(leftBytes, "/tmp/left.dll");
|
||||
const right = inspect(rightBytes, "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: left.result },
|
||||
{ evidenceId: right.evidenceId, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.exact_il_signature).toBe(0);
|
||||
expect(result.matching.structural_method_shape).toBe(1);
|
||||
expect(result.methods[0]).toMatchObject({
|
||||
status: "changed",
|
||||
match: { status: "matched", basis: "structural-method-shape" },
|
||||
dimensions: ["cil"],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects member states that disagree with their observed sides or match", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: left.result },
|
||||
{ evidenceId: right.evidenceId, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
const method = result.methods[0];
|
||||
expect(method).toBeDefined();
|
||||
if (method === undefined) return;
|
||||
|
||||
expect(
|
||||
managedMemberComparisonResultSchema.safeParse({
|
||||
...result,
|
||||
methods: [{ ...method, status: "unchanged", right: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
managedMemberComparisonResultSchema.safeParse({
|
||||
...result,
|
||||
methods: [
|
||||
{
|
||||
...method,
|
||||
match: {
|
||||
...method.match,
|
||||
basis: "none",
|
||||
confidence: "unknown",
|
||||
},
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not match identical instruction-limited method prefixes", () => {
|
||||
const limited = {
|
||||
...MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
maxMethodInstructions: 1,
|
||||
};
|
||||
const left = inspect(
|
||||
buildManagedPeFixture(),
|
||||
"/tmp/left-partial.dll",
|
||||
limited,
|
||||
);
|
||||
const right = inspect(
|
||||
buildManagedPeFixture(),
|
||||
"/tmp/right-partial.dll",
|
||||
limited,
|
||||
);
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: left.result },
|
||||
{ evidenceId: right.evidenceId, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.exact_il_signature).toBe(0);
|
||||
expect(result.matching.structural_method_shape).toBe(0);
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
left_status: "partial",
|
||||
right_status: "partial",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed member comparison uncertainty", () => {
|
||||
it("keeps unmatched members unknown when the opposite page is incomplete", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left-paged.dll");
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right-paged.dll");
|
||||
const leftPartial = {
|
||||
...left.result,
|
||||
fields: {
|
||||
...left.result.fields,
|
||||
items: [],
|
||||
returned: 0,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const rightPartial = {
|
||||
...right.result,
|
||||
methods: {
|
||||
...right.result.methods,
|
||||
items: [],
|
||||
returned: 0,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: leftPartial },
|
||||
{ evidenceId: right.evidenceId, result: rightPartial },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.summary).toMatchObject({
|
||||
added: 0,
|
||||
removed: 0,
|
||||
unknown: 2,
|
||||
});
|
||||
expect(result.methods[0]).toMatchObject({
|
||||
status: "unknown",
|
||||
left: { token: "0x06000001" },
|
||||
right: null,
|
||||
limitations: [expect.stringContaining("unknown-within-unobserved-page")],
|
||||
});
|
||||
expect(result.fields[0]).toMatchObject({
|
||||
status: "unknown",
|
||||
left: null,
|
||||
right: { token: "0x04000001" },
|
||||
limitations: [expect.stringContaining("unknown-within-unobserved-page")],
|
||||
});
|
||||
expect(result.coverage).toEqual({
|
||||
status: "truncated",
|
||||
left_status: "partial",
|
||||
right_status: "partial",
|
||||
omitted_methods: 1,
|
||||
omitted_fields: 1,
|
||||
omitted_candidates: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not guess ambiguous field signature matches", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
|
||||
const leftField = left.result.fields.items[0];
|
||||
expect(leftField).toBeDefined();
|
||||
if (leftField === undefined) return;
|
||||
const duplicatedLeft = {
|
||||
...left.result,
|
||||
fields: {
|
||||
...left.result.fields,
|
||||
items: [
|
||||
leftField,
|
||||
{
|
||||
...leftField,
|
||||
token: "0x04000002",
|
||||
name: "other",
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
returned: 2,
|
||||
},
|
||||
};
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
|
||||
const rightField = right.result.fields.items[0];
|
||||
expect(rightField).toBeDefined();
|
||||
if (rightField === undefined) return;
|
||||
const duplicatedRight = {
|
||||
...right.result,
|
||||
fields: {
|
||||
...right.result.fields,
|
||||
items: [
|
||||
rightField,
|
||||
{
|
||||
...rightField,
|
||||
token: "0x04000002",
|
||||
name: "renamed",
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
returned: 2,
|
||||
},
|
||||
};
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidenceId, result: duplicatedLeft },
|
||||
{ evidenceId: right.evidenceId, result: duplicatedRight },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.ambiguous).toBe(1);
|
||||
expect(result.fields).toEqual([
|
||||
expect.objectContaining({
|
||||
status: "unknown",
|
||||
match: expect.objectContaining({
|
||||
status: "ambiguous",
|
||||
basis: "field-signature",
|
||||
candidate_left_tokens: ["0x04000001", "0x04000002"],
|
||||
candidate_right_tokens: ["0x04000001", "0x04000002"],
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const inspect = (
|
||||
bytes: Buffer,
|
||||
path: string,
|
||||
limits: typeof MANAGED_MEMBER_FIXTURE_LIMITS = MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
) => {
|
||||
const target = managedPeFixtureTarget(bytes, path);
|
||||
const result = inspectManagedMembersBytes(bytes, target, limits);
|
||||
return {
|
||||
result,
|
||||
evidenceId: `ev_${hash(Buffer.from(path))}`,
|
||||
};
|
||||
};
|
||||
|
||||
const hash = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyMobileResource,
|
||||
detectMobileFormat,
|
||||
detectPlatform,
|
||||
getAllArchitectures,
|
||||
hasInternetPermission,
|
||||
mobileArtifactManifestSchema,
|
||||
nativeLibsByArchitecture,
|
||||
type MobileArtifactManifest,
|
||||
type AndroidManifest,
|
||||
type SigningInfo,
|
||||
type NativeLibrary,
|
||||
type MobileResource,
|
||||
} from "./mobileApplicationInvestigation.js";
|
||||
|
||||
describe("mobile application investigation", () => {
|
||||
it("detects mobile format from extension", () => {
|
||||
expect(detectMobileFormat("app.apk")).toBe("apk");
|
||||
expect(detectMobileFormat("app.aab")).toBe("aab");
|
||||
expect(detectMobileFormat("app.ipa")).toBe("ipa");
|
||||
expect(detectMobileFormat("classes.dex")).toBe("dex");
|
||||
expect(detectMobileFormat("lib.so")).toBe("native_lib");
|
||||
expect(detectMobileFormat("readme.txt")).toBeNull();
|
||||
});
|
||||
|
||||
it("detects platform from format", () => {
|
||||
expect(detectPlatform("apk")).toBe("android");
|
||||
expect(detectPlatform("aab")).toBe("android");
|
||||
expect(detectPlatform("dex")).toBe("android");
|
||||
expect(detectPlatform("ipa")).toBe("ios");
|
||||
expect(detectPlatform("native_lib")).toBe("cross_platform");
|
||||
});
|
||||
|
||||
it("classifies resources by path", () => {
|
||||
expect(classifyMobileResource("res/layout/main.xml")).toBe("layout");
|
||||
expect(classifyMobileResource("res/drawable/icon.png")).toBe("drawable");
|
||||
expect(classifyMobileResource("assets/data.json")).toBe("asset");
|
||||
expect(classifyMobileResource("AndroidManifest.xml")).toBe("manifest");
|
||||
expect(classifyMobileResource("app.entitlements")).toBe("entitlements");
|
||||
expect(classifyMobileResource("lib/arm64-v8a/libnative.so")).toBe(
|
||||
"native_lib",
|
||||
);
|
||||
expect(classifyMobileResource("unknown.xyz")).toBe("other");
|
||||
});
|
||||
|
||||
const androidManifest: AndroidManifest = {
|
||||
package_name: "com.example.app",
|
||||
version_name: "1.0.0",
|
||||
version_code: 1,
|
||||
min_sdk: 21,
|
||||
target_sdk: 34,
|
||||
permissions: ["android.permission.INTERNET", "android.permission.CAMERA"],
|
||||
activities: ["MainActivity"],
|
||||
services: ["BackgroundService"],
|
||||
receivers: [],
|
||||
providers: [],
|
||||
};
|
||||
|
||||
const signing: SigningInfo = {
|
||||
is_signed: true,
|
||||
signer_identity: "CN=TestSigner",
|
||||
certificate_fingerprint: "abc123",
|
||||
signature_scheme: "v2",
|
||||
is_debuggable: false,
|
||||
};
|
||||
|
||||
const nativeLibs: NativeLibrary[] = [
|
||||
{
|
||||
path: "lib/arm64-v8a/libnative.so",
|
||||
architecture: "arm64-v8a",
|
||||
size: 100000,
|
||||
digest: "a".repeat(64),
|
||||
},
|
||||
{
|
||||
path: "lib/armeabi-v7a/libnative.so",
|
||||
architecture: "armeabi-v7a",
|
||||
size: 90000,
|
||||
digest: "b".repeat(64),
|
||||
},
|
||||
];
|
||||
|
||||
const resources: MobileResource[] = [
|
||||
{ path: "res/layout/main.xml", type: "layout", size: 1000 },
|
||||
{ path: "res/drawable/icon.png", type: "drawable", size: 5000 },
|
||||
];
|
||||
|
||||
const validManifest: MobileArtifactManifest = {
|
||||
format: "apk",
|
||||
platform: "android",
|
||||
app_name: "TestApp",
|
||||
android_manifest: androidManifest,
|
||||
ios_manifest: null,
|
||||
signing,
|
||||
resources,
|
||||
native_libraries: nativeLibs,
|
||||
total_size: 5000000,
|
||||
architectures: ["arm64-v8a", "armeabi-v7a"],
|
||||
};
|
||||
|
||||
it("validates a well-formed manifest", () => {
|
||||
const result = mobileArtifactManifestSchema.safeParse(validManifest);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("filters native libs by architecture", () => {
|
||||
const arm64 = nativeLibsByArchitecture(validManifest, "arm64-v8a");
|
||||
expect(arm64).toHaveLength(1);
|
||||
expect(arm64[0]!.architecture).toBe("arm64-v8a");
|
||||
});
|
||||
|
||||
it("checks internet permission", () => {
|
||||
expect(hasInternetPermission(validManifest)).toBe(true);
|
||||
const noInternet: MobileArtifactManifest = {
|
||||
...validManifest,
|
||||
android_manifest: { ...androidManifest, permissions: [] },
|
||||
};
|
||||
expect(hasInternetPermission(noInternet)).toBe(false);
|
||||
});
|
||||
|
||||
it("gets all architectures", () => {
|
||||
const archs = getAllArchitectures(validManifest);
|
||||
expect(archs).toHaveLength(2);
|
||||
expect(archs).toContain("arm64-v8a");
|
||||
expect(archs).toContain("armeabi-v7a");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
countMethodsByType,
|
||||
isDbSaveComplete,
|
||||
isGetterSelector,
|
||||
isSetterSelector,
|
||||
objcSwiftMetadataSchema,
|
||||
propertyNameFromSelector,
|
||||
swiftDeclsByKind,
|
||||
type ObjcClass,
|
||||
type ObjcMethod,
|
||||
type ObjcProtocol,
|
||||
type SwiftDecl,
|
||||
type DbSaveResult,
|
||||
} from "./objcSwiftMetadata.js";
|
||||
|
||||
describe("ObjC/Swift metadata", () => {
|
||||
it("identifies getter selectors", () => {
|
||||
expect(isGetterSelector("name")).toBe(true);
|
||||
expect(isGetterSelector("setName:")).toBe(false);
|
||||
expect(isGetterSelector("set")).toBe(true);
|
||||
});
|
||||
|
||||
it("identifies setter selectors", () => {
|
||||
expect(isSetterSelector("setName:")).toBe(true);
|
||||
expect(isSetterSelector("name")).toBe(false);
|
||||
});
|
||||
|
||||
it("extracts property name from selector", () => {
|
||||
expect(propertyNameFromSelector("name")).toBe("name");
|
||||
expect(propertyNameFromSelector("setName:")).toBe("name");
|
||||
expect(propertyNameFromSelector("set")).toBe("set");
|
||||
});
|
||||
|
||||
it("counts methods by type", () => {
|
||||
const methods: ObjcMethod[] = [
|
||||
{
|
||||
selector: "init",
|
||||
method_type: "instance",
|
||||
address: 0x1000,
|
||||
is_required: false,
|
||||
is_optional: false,
|
||||
},
|
||||
{
|
||||
selector: "alloc",
|
||||
method_type: "class",
|
||||
address: 0x2000,
|
||||
is_required: false,
|
||||
is_optional: false,
|
||||
},
|
||||
];
|
||||
const counts = countMethodsByType(methods);
|
||||
expect(counts.instance).toBe(1);
|
||||
expect(counts.class).toBe(1);
|
||||
expect(counts.ivar_getter).toBe(0);
|
||||
expect(counts.ivar_setter).toBe(0);
|
||||
});
|
||||
|
||||
it("filters Swift declarations by kind", () => {
|
||||
const decls: SwiftDecl[] = [
|
||||
{
|
||||
kind: "class",
|
||||
name: "Foo",
|
||||
module: null,
|
||||
access_level: "public",
|
||||
super_class: null,
|
||||
protocols: [],
|
||||
is_final: false,
|
||||
is_required: false,
|
||||
is_convenience_init: false,
|
||||
is_override: false,
|
||||
},
|
||||
];
|
||||
const classes = swiftDeclsByKind(decls, "class");
|
||||
expect(classes).toHaveLength(1);
|
||||
expect(classes[0]!.name).toBe("Foo");
|
||||
});
|
||||
|
||||
it("checks database save completeness", () => {
|
||||
const result: DbSaveResult = {
|
||||
operation: "save",
|
||||
succeeded: true,
|
||||
preserved_names: 10,
|
||||
preserved_comments: 5,
|
||||
preserved_bookmarks: 3,
|
||||
database_path: "/tmp/db.hop",
|
||||
error: null,
|
||||
};
|
||||
expect(isDbSaveComplete(result, 10, 5, 3)).toBe(true);
|
||||
expect(isDbSaveComplete(result, 11, 5, 3)).toBe(false);
|
||||
});
|
||||
|
||||
it("validates a well-formed metadata result", () => {
|
||||
const meta = {
|
||||
objc_classes: [] as ObjcClass[],
|
||||
objc_protocols: [] as ObjcProtocol[],
|
||||
swift_decls: [] as SwiftDecl[],
|
||||
db_save_result: null,
|
||||
};
|
||||
const result = objcSwiftMetadataSchema.safeParse(meta);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyResource,
|
||||
detectPackageFormat,
|
||||
hasValidSignature,
|
||||
isConfigurationResource,
|
||||
isManifestResource,
|
||||
packageManifestSchema,
|
||||
resourcesByType,
|
||||
totalResourceSize,
|
||||
type PackageManifest,
|
||||
} from "./packageAnalysis.js";
|
||||
|
||||
describe("package analysis", () => {
|
||||
it("detects package format from extension", () => {
|
||||
expect(detectPackageFormat("app.msix")).toBe("msix");
|
||||
expect(detectPackageFormat("installer.msi")).toBe("msi");
|
||||
expect(detectPackageFormat("app.appx")).toBe("appx");
|
||||
expect(detectPackageFormat("app.zip")).toBeNull();
|
||||
});
|
||||
|
||||
it("identifies manifest resources", () => {
|
||||
expect(isManifestResource("AppXManifest.xml")).toBe(true);
|
||||
expect(isManifestResource("resources.pri")).toBe(false);
|
||||
});
|
||||
|
||||
it("identifies configuration resources", () => {
|
||||
expect(isConfigurationResource("settings.xml")).toBe(true);
|
||||
expect(isConfigurationResource("config.json")).toBe(true);
|
||||
expect(isConfigurationResource("app.exe")).toBe(false);
|
||||
});
|
||||
|
||||
it("classifies resources by path", () => {
|
||||
expect(classifyResource("AppXManifest.xml")).toBe("manifest");
|
||||
expect(classifyResource("icon.png")).toBe("icon");
|
||||
expect(classifyResource("settings.xml")).toBe("configuration");
|
||||
expect(classifyResource("cert.cer")).toBe("certificate");
|
||||
expect(classifyResource("app.exe")).toBe("executable");
|
||||
expect(classifyResource("lib.dll")).toBe("library");
|
||||
expect(classifyResource("data.bin")).toBe("other");
|
||||
});
|
||||
|
||||
const validManifest: PackageManifest = {
|
||||
format: "msix",
|
||||
name: "TestApp",
|
||||
publisher: "CN=TestPublisher",
|
||||
version: "1.0.0.0",
|
||||
architecture: "x64",
|
||||
resources: [
|
||||
{
|
||||
path: "AppXManifest.xml",
|
||||
type: "manifest",
|
||||
size: 1000,
|
||||
digest: "a".repeat(64),
|
||||
},
|
||||
{ path: "icon.png", type: "icon", size: 5000, digest: "b".repeat(64) },
|
||||
{
|
||||
path: "app.exe",
|
||||
type: "executable",
|
||||
size: 50000,
|
||||
digest: "c".repeat(64),
|
||||
},
|
||||
],
|
||||
signature: {
|
||||
is_signed: true,
|
||||
signer_subject: "CN=TestPublisher",
|
||||
certificate_thumbprint: "abc123",
|
||||
is_valid: true,
|
||||
is_timestamped: true,
|
||||
timestamp_signer: "CN=Timestamp",
|
||||
},
|
||||
is_framework: false,
|
||||
dependencies: ["Microsoft.VCLibs.14.00"],
|
||||
capabilities: ["internetClient", "localNetwork"],
|
||||
};
|
||||
|
||||
it("validates a well-formed manifest", () => {
|
||||
const result = packageManifestSchema.safeParse(validManifest);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("filters resources by type", () => {
|
||||
const icons = resourcesByType(validManifest, "icon");
|
||||
expect(icons).toHaveLength(1);
|
||||
expect(icons[0]!.path).toBe("icon.png");
|
||||
});
|
||||
|
||||
it("computes total resource size", () => {
|
||||
expect(totalResourceSize(validManifest)).toBe(56000);
|
||||
});
|
||||
|
||||
it("checks valid signature", () => {
|
||||
expect(hasValidSignature(validManifest)).toBe(true);
|
||||
const unsigned: PackageManifest = {
|
||||
...validManifest,
|
||||
signature: { ...validManifest.signature, is_valid: false },
|
||||
};
|
||||
expect(hasValidSignature(unsigned)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -44,7 +44,6 @@ export const digitalSignatureSchema = z.strictObject({
|
||||
/** Timestamp signer if present. */
|
||||
timestamp_signer: z.string().nullable(),
|
||||
});
|
||||
export type DigitalSignature = z.infer<typeof digitalSignatureSchema>;
|
||||
|
||||
/** A Windows package manifest for static analysis. */
|
||||
export const packageManifestSchema = z.strictObject({
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
countExecutableSections,
|
||||
getExportedFunctions,
|
||||
getImportedDlls,
|
||||
hasPdbInfo,
|
||||
parseDebugType,
|
||||
parseImageCharacteristics,
|
||||
parseMachineType,
|
||||
parseSectionCharacteristics,
|
||||
peManifestSchema,
|
||||
type PeManifest,
|
||||
} from "./peInspection.js";
|
||||
|
||||
const validManifest: PeManifest = {
|
||||
dos_magic: 0x5a4d,
|
||||
pe_signature: 0x00004550,
|
||||
machine: "x64",
|
||||
number_of_sections: 3,
|
||||
timestamp: 0x12345678,
|
||||
is_dll: false,
|
||||
is_executable: true,
|
||||
is_console: true,
|
||||
entry_point: 0x1000,
|
||||
image_base: 0x400000,
|
||||
section_alignment: 0x1000,
|
||||
subsystem_version: "10.0",
|
||||
sections: [
|
||||
{
|
||||
name: ".text",
|
||||
virtual_size: 0x1000,
|
||||
virtual_address: 0x1000,
|
||||
raw_size: 0x1000,
|
||||
raw_offset: 0x400,
|
||||
characteristics: {
|
||||
has_code: true,
|
||||
has_initialized_data: false,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: ".data",
|
||||
virtual_size: 0x500,
|
||||
virtual_address: 0x2000,
|
||||
raw_size: 0x500,
|
||||
raw_offset: 0x1400,
|
||||
characteristics: {
|
||||
has_code: false,
|
||||
has_initialized_data: true,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: true,
|
||||
executable: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: ".rdata",
|
||||
virtual_size: 0x200,
|
||||
virtual_address: 0x3000,
|
||||
raw_size: 0x200,
|
||||
raw_offset: 0x1900,
|
||||
characteristics: {
|
||||
has_code: false,
|
||||
has_initialized_data: true,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
imports: [
|
||||
{
|
||||
dll: "KERNEL32.DLL",
|
||||
function_name: "CreateFileW",
|
||||
ordinal: null,
|
||||
is_delay_import: false,
|
||||
},
|
||||
{
|
||||
dll: "KERNEL32.DLL",
|
||||
function_name: "WriteFile",
|
||||
ordinal: null,
|
||||
is_delay_import: false,
|
||||
},
|
||||
{
|
||||
dll: "USER32.DLL",
|
||||
function_name: "MessageBoxW",
|
||||
ordinal: 100,
|
||||
is_delay_import: false,
|
||||
},
|
||||
],
|
||||
exports: [
|
||||
{ name: "DllMain", ordinal: 1, rva: 0x1000, forwarder: null },
|
||||
{ name: "MyFunction", ordinal: 2, rva: 0x1050, forwarder: null },
|
||||
],
|
||||
resources: [
|
||||
{ type: "RT_VERSION", name: "1", language: 0x0409, rva: 0x4000, size: 100 },
|
||||
],
|
||||
debug_entries: [
|
||||
{
|
||||
type: "CODEVIEW",
|
||||
rva: 0x5000,
|
||||
size: 100,
|
||||
pdb_guid: "AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP",
|
||||
pdb_age: 1,
|
||||
pdb_path: "C:\\src\\app.pdb",
|
||||
},
|
||||
],
|
||||
tls_callbacks: [{ callback_rva: 0x6000, index: 0 }],
|
||||
relocations_count: 50,
|
||||
image_characteristics: ["Executable", "Console"],
|
||||
};
|
||||
|
||||
describe("PE/COFF static inspection", () => {
|
||||
it("parses machine types", () => {
|
||||
expect(parseMachineType(0x014c)).toBe("x86");
|
||||
expect(parseMachineType(0x8664)).toBe("x64");
|
||||
expect(parseMachineType(0x01c0)).toBe("arm");
|
||||
expect(parseMachineType(0xaa64)).toBe("arm64");
|
||||
expect(parseMachineType(0x0200)).toBe("ia64");
|
||||
expect(parseMachineType(0xffff)).toBe("unknown");
|
||||
});
|
||||
|
||||
it("parses section characteristics", () => {
|
||||
const CODE = 0x00000020;
|
||||
const READ = 0x40000000;
|
||||
const EXECUTE = 0x20000000;
|
||||
const result = parseSectionCharacteristics(CODE | READ | EXECUTE);
|
||||
expect(result.has_code).toBe(true);
|
||||
expect(result.readable).toBe(true);
|
||||
expect(result.executable).toBe(true);
|
||||
expect(result.writable).toBe(false);
|
||||
});
|
||||
|
||||
it("parses image characteristics", () => {
|
||||
const DLL = 0x2000;
|
||||
const EXEC = 0x0002;
|
||||
const flags = parseImageCharacteristics(DLL | EXEC);
|
||||
expect(flags).toContain("DLL");
|
||||
expect(flags).toContain("Executable");
|
||||
});
|
||||
|
||||
it("parses debug types", () => {
|
||||
expect(parseDebugType(2)).toBe("CODEVIEW");
|
||||
expect(parseDebugType(1)).toBe("COFF");
|
||||
expect(parseDebugType(99)).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("validates a well-formed manifest", () => {
|
||||
const result = peManifestSchema.safeParse(validManifest);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("detects PDB info", () => {
|
||||
expect(hasPdbInfo(validManifest)).toBe(true);
|
||||
const withoutPdb: PeManifest = {
|
||||
...validManifest,
|
||||
debug_entries: [
|
||||
{
|
||||
type: "COFF",
|
||||
rva: 0x5000,
|
||||
size: 100,
|
||||
pdb_guid: null,
|
||||
pdb_age: null,
|
||||
pdb_path: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(hasPdbInfo(withoutPdb)).toBe(false);
|
||||
});
|
||||
|
||||
it("gets imported DLLs", () => {
|
||||
const dlls = getImportedDlls(validManifest);
|
||||
expect(dlls).toHaveLength(2);
|
||||
expect(dlls).toContain("KERNEL32.DLL");
|
||||
expect(dlls).toContain("USER32.DLL");
|
||||
});
|
||||
|
||||
it("gets exported functions", () => {
|
||||
const exports = getExportedFunctions(validManifest);
|
||||
expect(exports).toHaveLength(2);
|
||||
expect(exports).toContain("DllMain");
|
||||
expect(exports).toContain("MyFunction");
|
||||
});
|
||||
|
||||
it("counts executable sections", () => {
|
||||
expect(countExecutableSections(validManifest)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,6 @@ export const peSectionSchema = z.strictObject({
|
||||
raw_offset: z.number().int().nonnegative(),
|
||||
characteristics: sectionCharacteristicsSchema,
|
||||
});
|
||||
export type PeSection = z.infer<typeof peSectionSchema>;
|
||||
|
||||
/** PE import entry. */
|
||||
export const peImportSchema = z.strictObject({
|
||||
@@ -34,7 +33,6 @@ export const peImportSchema = z.strictObject({
|
||||
ordinal: z.number().int().nullable(),
|
||||
is_delay_import: z.boolean().default(false),
|
||||
});
|
||||
export type PeImport = z.infer<typeof peImportSchema>;
|
||||
|
||||
/** PE export entry. */
|
||||
export const peExportSchema = z.strictObject({
|
||||
@@ -43,7 +41,6 @@ export const peExportSchema = z.strictObject({
|
||||
rva: z.number().int().nonnegative(),
|
||||
forwarder: z.string().nullable(),
|
||||
});
|
||||
export type PeExport = z.infer<typeof peExportSchema>;
|
||||
|
||||
/** PE/COFF resource entry. */
|
||||
export const peResourceSchema = z.strictObject({
|
||||
@@ -53,7 +50,6 @@ export const peResourceSchema = z.strictObject({
|
||||
rva: z.number().int().nonnegative(),
|
||||
size: z.number().int().nonnegative(),
|
||||
});
|
||||
export type PeResource = z.infer<typeof peResourceSchema>;
|
||||
|
||||
/** PE debug directory entry. */
|
||||
export const peDebugEntrySchema = z.strictObject({
|
||||
@@ -67,14 +63,12 @@ export const peDebugEntrySchema = z.strictObject({
|
||||
/** PDB path if this is a CodeView entry. */
|
||||
pdb_path: z.string().nullable(),
|
||||
});
|
||||
export type PeDebugEntry = z.infer<typeof peDebugEntrySchema>;
|
||||
|
||||
/** TLS callback entry. */
|
||||
export const peTlsCallbackSchema = z.strictObject({
|
||||
callback_rva: z.number().int().nonnegative(),
|
||||
index: z.number().int().nonnegative(),
|
||||
});
|
||||
export type PeTlsCallback = z.infer<typeof peTlsCallbackSchema>;
|
||||
|
||||
/** Architecture/machine type. */
|
||||
export const peMachineTypeSchema = z.enum([
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyProcessCapture as emptyCapture,
|
||||
} from "./processCapture.fixture.js";
|
||||
|
||||
it("classifies missing observations as unknown and one-sided evidence as added", () => {
|
||||
const base = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const added = compareProcessCaptures(base, {
|
||||
...base,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
columns: 3,
|
||||
rows: 1,
|
||||
cursor_x: 3,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["new"],
|
||||
serialized_state: "new",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(added.terminal).toBe("added");
|
||||
expect(added.status).toBe("changed");
|
||||
const unknown = compareProcessCaptures(
|
||||
{ ...base, residual_unknowns: [{ scope: "process", reason: "sampled" }] },
|
||||
base,
|
||||
);
|
||||
expect(unknown.process).toBe("unknown");
|
||||
expect(unknown.shim).toBe("unchanged");
|
||||
expect(unknown.status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("treats equivalent normalization records as equal regardless of member order", () => {
|
||||
const capture = emptyCapture();
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
normalization: {
|
||||
patterns: [],
|
||||
time_bucket_ms: 10,
|
||||
ports: true,
|
||||
pids: true,
|
||||
paths: true,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unchanged",
|
||||
first_divergence: { status: "none" },
|
||||
});
|
||||
});
|
||||
|
||||
it("compares raw terminal chunks even when rendered states agree", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "bar" }],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }],
|
||||
});
|
||||
expect(comparison.terminal).toBe("changed");
|
||||
expect(comparison.first_divergence).toMatchObject({
|
||||
status: "found",
|
||||
dimension: "terminal",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps filesystem evidence unknown when stable snapshots match", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [
|
||||
{ scope: "filesystem" as const, reason: "watcher unavailable" },
|
||||
],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, capture);
|
||||
expect(comparison.filesystem).toBe("unknown");
|
||||
expect(comparison.status).toBe("unknown");
|
||||
|
||||
const complete = { ...capture, residual_unknowns: [] };
|
||||
const transient = compareProcessCaptures(complete, {
|
||||
...complete,
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "during_run",
|
||||
at_ms: 10,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(transient.filesystem).toBe("changed");
|
||||
expect(transient.status).toBe("changed");
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
processCaptureSchema,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "./processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
|
||||
|
||||
export { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
|
||||
|
||||
/** Parse a detached valid empty capture for tests that need trusted evidence. */
|
||||
export const emptyProcessCapture = () =>
|
||||
parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
|
||||
/** Parse a mutable unverified capture for boundary-validation tests. */
|
||||
export const emptyUnverifiedProcessCapture = (): UnverifiedProcessCapture =>
|
||||
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
|
||||
/** Project validation failures without coupling tests to Zod internals. */
|
||||
export const processCaptureIssues = (
|
||||
capture: UnverifiedProcessCapture,
|
||||
): readonly { readonly path: string; readonly message: string }[] => {
|
||||
const parsed = processCaptureSchema.safeParse(capture);
|
||||
return parsed.success
|
||||
? []
|
||||
: parsed.error.issues.map((issue) => ({
|
||||
path: issue.path.join("."),
|
||||
message: issue.message,
|
||||
}));
|
||||
};
|
||||
|
||||
/** Compare unverified fixture values through the production parser. */
|
||||
export const compareUnverifiedProcessCaptures = (
|
||||
left: UnverifiedProcessCapture,
|
||||
right: UnverifiedProcessCapture,
|
||||
options?: Parameters<typeof compareProcessCaptures>[2],
|
||||
): ReturnType<typeof compareProcessCaptures> =>
|
||||
compareProcessCaptures(
|
||||
parseProcessCapture(left),
|
||||
parseProcessCapture(right),
|
||||
options,
|
||||
);
|
||||
@@ -0,0 +1,125 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { digestProcessCommitment } from "./processCapture.js";
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyProcessCapture as emptyCapture,
|
||||
} from "./processCapture.fixture.js";
|
||||
|
||||
it("detects changes in normalized process sample metadata", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 1,
|
||||
parent_pid: 0,
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
command: "worker",
|
||||
},
|
||||
],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const changed = {
|
||||
...capture,
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 20,
|
||||
pid: 1,
|
||||
parent_pid: 2,
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
command: "worker",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, changed);
|
||||
expect(comparison.process).toBe("changed");
|
||||
expect(comparison.status).toBe("changed");
|
||||
});
|
||||
|
||||
it("compares replay state transitions as protocol evidence", () => {
|
||||
const replayPlan = {
|
||||
machine: {
|
||||
initial_state: "anonymous",
|
||||
states: [
|
||||
{ name: "anonymous" },
|
||||
{ name: "authenticated", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "login",
|
||||
from: "anonymous",
|
||||
to: "authenticated",
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_json", path: ["token"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
};
|
||||
const empty = emptyCapture();
|
||||
const baseline = {
|
||||
...empty,
|
||||
manifest: {
|
||||
...empty.manifest,
|
||||
replay_plan: replayPlan,
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
};
|
||||
const transitioned = {
|
||||
...baseline,
|
||||
replay_transitions: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
transition_id: "login",
|
||||
state_before: "anonymous",
|
||||
state_after: "authenticated",
|
||||
sensitive_aliases: ["token"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(compareProcessCaptures(baseline, transitioned)).toMatchObject({
|
||||
status: "changed",
|
||||
protocol: "added",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
parseProcessCapture,
|
||||
processCaptureSchema,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "./processCapture.js";
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyUnverifiedProcessCapture as emptyCapture,
|
||||
processCaptureIssues,
|
||||
} from "./processCapture.fixture.js";
|
||||
|
||||
it("never considers truncated captures equivalent", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: true,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
expect(compareProcessCaptures(capture, capture).status).toBe("truncated");
|
||||
});
|
||||
|
||||
it("rejects altered v4 commitments and accepts canonical key reordering", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(parseProcessCapture(capture)).toEqual(capture);
|
||||
expect(digestProcessCommitment({ second: 2, first: 1 })).toBe(
|
||||
digestProcessCommitment({ first: 1, second: 2 }),
|
||||
);
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
normalization_sha256: "f".repeat(64),
|
||||
},
|
||||
}),
|
||||
).toThrow("normalization_sha256");
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
executable_sha256: "f".repeat(64),
|
||||
},
|
||||
}),
|
||||
).toThrow("executable_sha256");
|
||||
});
|
||||
|
||||
it("rejects settlement and cleanup combinations that cannot occur", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 0,
|
||||
cleanup_outcome: "cleaned",
|
||||
},
|
||||
}),
|
||||
).toThrow("cleanup_outcome");
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
settlement: {
|
||||
state: "alive_at_deadline",
|
||||
elapsed_ms: 1,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
}),
|
||||
).toThrow("cleanup_outcome");
|
||||
});
|
||||
|
||||
it("accepts old captures without a journal and validates complete journals", () => {
|
||||
const capture = emptyCapture();
|
||||
const { event_journal: _eventJournal, ...oldCapture } = capture;
|
||||
expect(parseProcessCapture(oldCapture).event_journal).toEqual([]);
|
||||
|
||||
const eventJournal = [
|
||||
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 2, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
|
||||
] as const;
|
||||
expect(
|
||||
processCaptureIssues({ ...capture, event_journal: eventJournal }),
|
||||
).toEqual([]);
|
||||
|
||||
for (const [candidate, message] of [
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 1 ? { ...entry, capture_order: 2 } : entry,
|
||||
),
|
||||
"contiguous",
|
||||
],
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 3
|
||||
? { ...entry, collection: "lifecycle" as const, index: 1 }
|
||||
: entry,
|
||||
),
|
||||
"unique",
|
||||
],
|
||||
[eventJournal.slice(0, 3), "every captured observation"],
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 3 ? { ...entry, index: 2 } : entry,
|
||||
),
|
||||
"outside",
|
||||
],
|
||||
] as const) {
|
||||
expect(
|
||||
processCaptureIssues({ ...capture, event_journal: candidate }),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining(message),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["machine limit", 1, 5, 10],
|
||||
["transition use limit", 5, 1, 10],
|
||||
["state visit limit", 5, 5, 1],
|
||||
])(
|
||||
"rejects replay journals that exceed the declared %s",
|
||||
(_name, maxTransitions, maxUses, maxVisits) => {
|
||||
const replayPlan = {
|
||||
machine: {
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: maxVisits },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "again",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/ws",
|
||||
body: "again",
|
||||
},
|
||||
actions: [{ type: "websocket_send", data: "again" }],
|
||||
max_uses: maxUses,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "complete",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/ws",
|
||||
body: "finish",
|
||||
},
|
||||
actions: [{ type: "websocket_send", data: "done" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: maxTransitions,
|
||||
},
|
||||
};
|
||||
const capture = emptyCapture();
|
||||
const candidate: UnverifiedProcessCapture = {
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
replay_plan: replayPlan,
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
replay_transitions: [0, 1].map((sequence) => ({
|
||||
sequence,
|
||||
at_ms: sequence,
|
||||
transition_id: "again",
|
||||
state_before: "active",
|
||||
state_after: "active",
|
||||
sensitive_aliases: [],
|
||||
})),
|
||||
};
|
||||
|
||||
expect(processCaptureIssues(candidate)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining("limit"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("tells agents and users to recapture unsupported v3 evidence", () => {
|
||||
const legacy = { ...emptyCapture(), schema_version: 3 };
|
||||
expect(() => parseProcessCapture(legacy)).toThrow(
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
);
|
||||
const parsed = processCaptureSchema.safeParse(legacy);
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) throw new Error("expected legacy capture rejection");
|
||||
expect(parsed.error.issues[0]?.message).toBe(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
});
|
||||
|
||||
it("requires compatible contracts and enforces capture age through a clock seam", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(() =>
|
||||
compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
comparison_contract: { changed: true },
|
||||
comparison_contract_sha256: digestProcessCommitment({
|
||||
changed: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
).toThrow("incompatible comparison contracts");
|
||||
expect(() =>
|
||||
compareProcessCaptures(capture, capture, {
|
||||
maxCaptureAgeMs: 1,
|
||||
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
|
||||
}),
|
||||
).toThrow("max_capture_age_ms");
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import { digestProcessCommitment } from "./processCapture.js";
|
||||
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: JsonValue[] = [];
|
||||
const replayPlan = {};
|
||||
|
||||
/** Minimal valid process capture retained as a public contract example. */
|
||||
export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "1.1.0",
|
||||
provider_version: "3",
|
||||
platform: "fixture",
|
||||
architecture: "fixture",
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
} satisfies JsonValue;
|
||||
@@ -0,0 +1,160 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import {
|
||||
processCaptureSchema,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "./processCapture.js";
|
||||
import {
|
||||
createProcessObservation,
|
||||
projectProcessObservation,
|
||||
} from "./processObservation.js";
|
||||
|
||||
const emptyCapture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
|
||||
const capture: UnverifiedProcessCapture = {
|
||||
...emptyCapture,
|
||||
frames: [{ sequence: 0, at_ms: 1, data: "Ready" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 2,
|
||||
columns: 80,
|
||||
rows: 24,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["Ready"],
|
||||
serialized_state: "Ready",
|
||||
},
|
||||
],
|
||||
interaction_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
scheduled_at_ms: 2,
|
||||
dispatched_at_ms: 3,
|
||||
type: "signal",
|
||||
data: "SIGINT",
|
||||
outcome: "dispatched",
|
||||
},
|
||||
],
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 4,
|
||||
pid: 2,
|
||||
parent_pid: 1,
|
||||
command: "worker",
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
},
|
||||
],
|
||||
shim_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 5,
|
||||
command: "helper",
|
||||
route_index: 0,
|
||||
arguments: [],
|
||||
working_directory: "/fixture",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
protocol_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 6,
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method: "GET",
|
||||
path: "/done",
|
||||
data: "",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
replay_transitions: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 7,
|
||||
transition_id: "done",
|
||||
state_before: "open",
|
||||
state_after: "closed",
|
||||
sensitive_aliases: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("process observation vocabulary", () => {
|
||||
it("projects every capture collection without timestamp sorting", () => {
|
||||
const locations = [
|
||||
{ collection: "frames", index: 0, capture_order: 4 },
|
||||
{ collection: "rendered_frames", index: 0, capture_order: 3 },
|
||||
{ collection: "interaction_events", index: 0, capture_order: 2 },
|
||||
{ collection: "lifecycle", index: 0, capture_order: 8 },
|
||||
{ collection: "lifecycle", index: 1, capture_order: 9 },
|
||||
{ collection: "process_samples", index: 0, capture_order: 1 },
|
||||
{ collection: "filesystem_checkpoints", index: 0, capture_order: 0 },
|
||||
{ collection: "shim_events", index: 0, capture_order: 5 },
|
||||
{ collection: "protocol_events", index: 0, capture_order: 6 },
|
||||
{ collection: "replay_transitions", index: 0, capture_order: 7 },
|
||||
] as const;
|
||||
const observations = locations.map((location) =>
|
||||
projectProcessObservation(capture, location),
|
||||
);
|
||||
|
||||
expect(observations.map((value) => value?.source)).toEqual([
|
||||
"terminal_raw",
|
||||
"terminal_rendered",
|
||||
"interaction",
|
||||
"lifecycle",
|
||||
"lifecycle",
|
||||
"process",
|
||||
"filesystem",
|
||||
"shim",
|
||||
"http",
|
||||
"replay_transition",
|
||||
]);
|
||||
expect(observations.map((value) => value?.capture_order)).toEqual(
|
||||
locations.map(({ capture_order }) => capture_order),
|
||||
);
|
||||
expect(observations[5]).toMatchObject({
|
||||
event_id: "obs.process_samples.0",
|
||||
source_sequence: 0,
|
||||
captured_at_ms: 4,
|
||||
subject_id: "process:2",
|
||||
});
|
||||
expect(observations[7]).toMatchObject({
|
||||
event_id: "obs.shim_events.0",
|
||||
subject_id: "shim:helper:route:0",
|
||||
});
|
||||
expect(observations[3]?.captured_at_ms).toBeNull();
|
||||
expect(observations[4]?.captured_at_ms).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the same constructor for live and post-hoc observations", () => {
|
||||
const location = {
|
||||
collection: "frames" as const,
|
||||
index: 0,
|
||||
capture_order: 4,
|
||||
};
|
||||
const projected = projectProcessObservation(capture, location);
|
||||
const live = createProcessObservation({
|
||||
source: "terminal_raw",
|
||||
source_sequence: 0,
|
||||
captured_at_ms: 1,
|
||||
subject_id: null,
|
||||
location,
|
||||
payload: capture.frames[0],
|
||||
});
|
||||
expect(live).toEqual(projected);
|
||||
});
|
||||
|
||||
it("returns no observation for a missing raw record", () => {
|
||||
expect(
|
||||
projectProcessObservation(capture, {
|
||||
collection: "frames",
|
||||
index: 1,
|
||||
capture_order: 10,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import { parseProcessCapture, type ProcessCapture } from "./processCapture.js";
|
||||
import {
|
||||
compareProcessTraces,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import { parseProcessCapture, type ProcessCapture } from "./processCapture.js";
|
||||
import {
|
||||
compareProcessTraces,
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyProtocolFamily,
|
||||
decodeGrpcFrame,
|
||||
decodeJsonRpc,
|
||||
decodeMessagePack,
|
||||
inferMessageSchema,
|
||||
looksLikeCredential,
|
||||
protocolCaptureSchema,
|
||||
type ProtocolMessage,
|
||||
} from "./protocolCapture.js";
|
||||
|
||||
describe("protocol capture", () => {
|
||||
it("classifies gRPC from content type", () => {
|
||||
expect(classifyProtocolFamily("application/grpc+proto", null)).toBe("grpc");
|
||||
});
|
||||
|
||||
it("classifies protobuf from content type", () => {
|
||||
expect(classifyProtocolFamily("application/x-protobuf", null)).toBe(
|
||||
"protobuf",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies json-rpc from content type", () => {
|
||||
expect(classifyProtocolFamily("application/json-rpc", null)).toBe(
|
||||
"json-rpc",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies msgpack from content type", () => {
|
||||
expect(classifyProtocolFamily("application/msgpack", null)).toBe(
|
||||
"messagepack",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies from path when content type is null", () => {
|
||||
expect(classifyProtocolFamily(null, "/some/grpc/method")).toBe("grpc");
|
||||
expect(classifyProtocolFamily(null, "/api/json-rpc/2.0")).toBe("json-rpc");
|
||||
});
|
||||
|
||||
it("returns null for unknown protocols", () => {
|
||||
expect(classifyProtocolFamily("text/plain", null)).toBeNull();
|
||||
expect(classifyProtocolFamily(null, null)).toBeNull();
|
||||
});
|
||||
|
||||
it("detects credential-like field names", () => {
|
||||
expect(looksLikeCredential("password")).toBe(true);
|
||||
expect(looksLikeCredential("api_key")).toBe(true);
|
||||
expect(looksLikeCredential("authorization")).toBe(true);
|
||||
expect(looksLikeCredential("username")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JSON-RPC decoding", () => {
|
||||
it("decodes a simple JSON-RPC request", () => {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
method: "add",
|
||||
params: [1, 2],
|
||||
id: 1,
|
||||
}),
|
||||
);
|
||||
const result = decodeJsonRpc(payload);
|
||||
expect(result.decoded_fields.length).toBe(4);
|
||||
expect(result.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it("redacts credential-like fields", () => {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
password: "secret123",
|
||||
username: "admin",
|
||||
}),
|
||||
);
|
||||
const result = decodeJsonRpc(payload);
|
||||
const passwordField = result.decoded_fields.find(
|
||||
(f) => f.path === "password",
|
||||
);
|
||||
expect(passwordField?.value).toBe("[REDACTED]");
|
||||
const usernameField = result.decoded_fields.find(
|
||||
(f) => f.path === "username",
|
||||
);
|
||||
expect(usernameField?.value).toBe("admin");
|
||||
});
|
||||
});
|
||||
|
||||
describe("MessagePack decoding", () => {
|
||||
it("detects map type", () => {
|
||||
const payload = new Uint8Array([0x82]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("map");
|
||||
});
|
||||
|
||||
it("detects array type", () => {
|
||||
const payload = new Uint8Array([0x92]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("array");
|
||||
});
|
||||
|
||||
it("reports unknown type for other tags", () => {
|
||||
const payload = new Uint8Array([0xff]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("unknown");
|
||||
expect(result.decoded_fields[0]?.inferred).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("gRPC frame decoding", () => {
|
||||
it("decodes a valid gRPC frame header", () => {
|
||||
const payload = new Uint8Array([
|
||||
0x00, 0x00, 0x00, 0x00, 0x05, 1, 2, 3, 4, 5,
|
||||
]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields).toHaveLength(2);
|
||||
expect(result.decoded_fields[0]?.path).toBe("compressed");
|
||||
expect(result.decoded_fields[0]?.value).toBe(false);
|
||||
expect(result.decoded_fields[1]?.path).toBe("message_length");
|
||||
expect(result.decoded_fields[1]?.value).toBe(5);
|
||||
});
|
||||
|
||||
it("detects compressed flag", () => {
|
||||
const payload = new Uint8Array([0x01, 0x00, 0x00, 0x00, 0x0a]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe(true);
|
||||
});
|
||||
|
||||
it("handles too-short frames", () => {
|
||||
const payload = new Uint8Array([0x00, 0x01]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields[0]?.path).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("schema inference", () => {
|
||||
it("infers schema from repeated messages", () => {
|
||||
const messages: ProtocolMessage[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
family: "json-rpc",
|
||||
direction: "request",
|
||||
endpoint: "/api",
|
||||
content_type: "application/json",
|
||||
raw_payload: null,
|
||||
decoded_fields: [
|
||||
{ path: "method", wire_type: "json", value: "add", inferred: false },
|
||||
{ path: "id", wire_type: "json", value: 1, inferred: false },
|
||||
],
|
||||
schema_hypotheses: [],
|
||||
truncated: false,
|
||||
credentials_redacted: false,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
family: "json-rpc",
|
||||
direction: "response",
|
||||
endpoint: "/api",
|
||||
content_type: "application/json",
|
||||
raw_payload: null,
|
||||
decoded_fields: [
|
||||
{ path: "result", wire_type: "json", value: 3, inferred: false },
|
||||
{ path: "id", wire_type: "json", value: 1, inferred: false },
|
||||
],
|
||||
schema_hypotheses: [],
|
||||
truncated: false,
|
||||
credentials_redacted: false,
|
||||
},
|
||||
];
|
||||
const hypotheses = inferMessageSchema(messages);
|
||||
expect(hypotheses).toHaveLength(3);
|
||||
const idHypothesis = hypotheses.find((h) => h.field_name === "id");
|
||||
expect(idHypothesis).toBeDefined();
|
||||
expect(idHypothesis!.evidence_count).toBe(2);
|
||||
expect(idHypothesis!.confidence).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("protocol capture schema validation", () => {
|
||||
it("validates a well-formed capture", () => {
|
||||
const capture = {
|
||||
family: "grpc" as const,
|
||||
messages: [],
|
||||
inferred_schema: [],
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
const result = protocolCaptureSchema.safeParse(capture);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -77,7 +77,6 @@ export const protocolCaptureSchema = z.strictObject({
|
||||
/** Whether credentials were detected and redacted. */
|
||||
credentials_detected: z.boolean().default(false),
|
||||
});
|
||||
export type ProtocolCapture = z.infer<typeof protocolCaptureSchema>;
|
||||
|
||||
/** Classification of a byte sequence as a known protocol family. */
|
||||
export function classifyProtocolFamily(
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
verifyReconstruction,
|
||||
} from "./reconstructionVerification.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCapture.fixture.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../contracts/artifactComparisonExample.js";
|
||||
import { createResidualUnknown } from "./residualUnknown.js";
|
||||
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
replayMachineRunInputSchema,
|
||||
runReplayMachine,
|
||||
} from "./replayMachineRun.js";
|
||||
|
||||
const loginRun = () =>
|
||||
replayMachineRunInputSchema.parse({
|
||||
machine: {
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_json", path: ["token"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 204,
|
||||
headers: { "x-token": "target-secret" },
|
||||
body: "target-secret",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: {},
|
||||
body: "done",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
limits: {
|
||||
connections: 2,
|
||||
messages: 4,
|
||||
bytes: 1_000,
|
||||
duration_ms: 100,
|
||||
},
|
||||
},
|
||||
events: [
|
||||
{
|
||||
protocol: "http",
|
||||
connection: "not_applicable",
|
||||
at_ms: 1,
|
||||
method: "post",
|
||||
path: "/login",
|
||||
headers: {},
|
||||
body: '{"token":"target-secret"}',
|
||||
},
|
||||
{
|
||||
protocol: "http",
|
||||
connection: "not_applicable",
|
||||
at_ms: 2,
|
||||
method: "GET",
|
||||
path: "/api",
|
||||
headers: { Authorization: "target-secret" },
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const parseMachineRun = (machine: unknown, events: unknown[]) =>
|
||||
replayMachineRunInputSchema.parse({ machine, events });
|
||||
|
||||
const httpEvent = (path: string, atMs = 0) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: atMs,
|
||||
method: "GET",
|
||||
path,
|
||||
headers: {},
|
||||
body: "",
|
||||
});
|
||||
|
||||
describe("direct replay machine execution", () => {
|
||||
it("returns actions, aliases, terminal state, and exact limit use", () => {
|
||||
const result = runReplayMachine(loginRun());
|
||||
|
||||
expect(result).toMatchObject({
|
||||
schema_version: 1,
|
||||
initial_state: "login",
|
||||
final_state: "complete",
|
||||
terminal: true,
|
||||
decisions: [
|
||||
{ event_sequence: 0, outcome: "matched", transition_sequence: 0 },
|
||||
{ event_sequence: 1, outcome: "matched", transition_sequence: 1 },
|
||||
],
|
||||
transition_journal: [
|
||||
{
|
||||
transition_id: "capture_token",
|
||||
captured_aliases: [{ name: "token", sensitive: true }],
|
||||
},
|
||||
{
|
||||
transition_id: "authorize",
|
||||
captured_aliases: [],
|
||||
},
|
||||
],
|
||||
transition_actions: [
|
||||
{
|
||||
transition_id: "capture_token",
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 204,
|
||||
headers: { "x-token": "<secret:token>" },
|
||||
body: "<secret:token>",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
transition_id: "authorize",
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: {},
|
||||
body: "done",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
limits: {
|
||||
configured: {
|
||||
transitions: 2,
|
||||
connections: 2,
|
||||
messages: 4,
|
||||
bytes: 1_000,
|
||||
duration_ms: 100,
|
||||
},
|
||||
usage: {
|
||||
offered_events: 2,
|
||||
admitted_events: 2,
|
||||
transitions: 2,
|
||||
connections: 0,
|
||||
messages: 0,
|
||||
bytes: 25,
|
||||
last_at_ms: 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("target-secret");
|
||||
});
|
||||
|
||||
it("classifies unmatched and guard-failed events without aborting", () => {
|
||||
const input = loginRun();
|
||||
const result = runReplayMachine({
|
||||
...input,
|
||||
events: [httpEvent("/missing"), input.events[0]!, httpEvent("/api", 2)],
|
||||
});
|
||||
|
||||
expect(result.decisions.map(({ outcome }) => outcome)).toEqual([
|
||||
"unmatched",
|
||||
"matched",
|
||||
"guard_failed",
|
||||
]);
|
||||
});
|
||||
|
||||
it("classifies exhausted transitions", () => {
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 3 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "retry_once",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/retry" },
|
||||
actions: [{ type: "http_response", status: 200, body: "retry" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [{ type: "http_response", status: 200, body: "done" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
},
|
||||
[httpEvent("/retry"), httpEvent("/retry", 1)],
|
||||
);
|
||||
|
||||
expect(
|
||||
runReplayMachine(input).decisions.map(({ outcome }) => outcome),
|
||||
).toEqual(["matched", "transition_exhausted"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("direct replay machine protocol and limits", () => {
|
||||
it("classifies reconnects that arrive in the wrong state", () => {
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "connected",
|
||||
states: [
|
||||
{ name: "connected" },
|
||||
{ name: "reconnecting" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "disconnect",
|
||||
from: "connected",
|
||||
to: "reconnecting",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/socket",
|
||||
body: "disconnect",
|
||||
},
|
||||
actions: [{ type: "disconnect" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "reconnect",
|
||||
from: "reconnecting",
|
||||
to: "done",
|
||||
trigger: { protocol: "websocket_connect", path: "/socket" },
|
||||
actions: [{ type: "websocket_send", data: "ready" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
},
|
||||
[
|
||||
{
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/socket",
|
||||
headers: {},
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
expect(runReplayMachine(input).decisions[0]?.outcome).toBe(
|
||||
"unexpected_reconnect",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects protocol-inconsistent events at the boundary", () => {
|
||||
const input = loginRun();
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [{ ...httpEvent("/login"), method: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [
|
||||
{
|
||||
...httpEvent("/login"),
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [
|
||||
{
|
||||
...httpEvent("/login"),
|
||||
headers: { Authorization: "first", authorization: "second" },
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("reports limit refusals without committing rejected usage", () => {
|
||||
const input = loginRun();
|
||||
const result = runReplayMachine({
|
||||
...input,
|
||||
machine: {
|
||||
...input.machine,
|
||||
limits: { ...input.machine.limits, bytes: 1 },
|
||||
},
|
||||
events: [input.events[0]!],
|
||||
});
|
||||
|
||||
expect(result.decisions).toEqual([
|
||||
{
|
||||
event_sequence: 0,
|
||||
outcome: "limit_exhausted",
|
||||
transition_sequence: null,
|
||||
},
|
||||
]);
|
||||
expect(result.limits.usage).toMatchObject({
|
||||
offered_events: 1,
|
||||
admitted_events: 0,
|
||||
transitions: 0,
|
||||
bytes: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("direct replay machine output bounds", () => {
|
||||
it("records large repeated actions once instead of amplifying each match", () => {
|
||||
const largeBody = "x".repeat(1_000_000);
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 11 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "repeat",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/repeat" },
|
||||
actions: [{ type: "http_response", status: 200, body: largeBody }],
|
||||
max_uses: 10,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [{ type: "http_response", status: 204, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 11,
|
||||
},
|
||||
Array.from({ length: 10 }, (_, index) => httpEvent("/repeat", index)),
|
||||
);
|
||||
|
||||
const result = runReplayMachine(input);
|
||||
expect(result.transition_journal).toHaveLength(10);
|
||||
expect(result.transition_actions).toHaveLength(1);
|
||||
expect(JSON.stringify(result).length).toBeLessThan(1_100_000);
|
||||
});
|
||||
|
||||
it("rejects aggregate action output above four MiB", () => {
|
||||
const largeBody = "x".repeat(1_000_000);
|
||||
const parsed = replayMachineRunInputSchema.safeParse({
|
||||
machine: {
|
||||
initial_state: "waiting",
|
||||
states: [{ name: "waiting" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "send",
|
||||
from: "waiting",
|
||||
to: "done",
|
||||
trigger: { protocol: "websocket_connect", path: "/socket" },
|
||||
actions: Array.from({ length: 5 }, () => ({
|
||||
type: "websocket_send",
|
||||
data: largeBody,
|
||||
})),
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
events: [],
|
||||
});
|
||||
|
||||
expect(parsed.success).toBe(false);
|
||||
if (!parsed.success)
|
||||
expect(parsed.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ path: ["machine", "transitions"] }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds action-field and sensitive-redaction work structurally", () => {
|
||||
const input = loginRun();
|
||||
const excessiveCaptures = replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: Array.from({ length: 1_025 }, () => input.events[0]),
|
||||
});
|
||||
expect(excessiveCaptures.success).toBe(false);
|
||||
if (!excessiveCaptures.success)
|
||||
expect(excessiveCaptures.error.issues).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ path: ["events"] })]),
|
||||
);
|
||||
|
||||
const excessiveFields = replayMachineRunInputSchema.safeParse({
|
||||
machine: {
|
||||
initial_state: "waiting",
|
||||
states: [{ name: "waiting" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "respond",
|
||||
from: "waiting",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: Object.fromEntries(
|
||||
Array.from({ length: 1_024 }, (_, index) => [
|
||||
`x-field-${String(index)}`,
|
||||
"",
|
||||
]),
|
||||
),
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
events: [],
|
||||
});
|
||||
expect(excessiveFields.success).toBe(false);
|
||||
if (!excessiveFields.success)
|
||||
expect(excessiveFields.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ path: ["machine", "transitions"] }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { replayMachineSchema } from "./replayMachine.js";
|
||||
import { ReplayMachineRuntime } from "./replayMachineRuntime.js";
|
||||
|
||||
const machine = replayMachineSchema.parse({
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["session_value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize_api",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
const event = (
|
||||
method: string,
|
||||
path: string,
|
||||
body = "",
|
||||
headers: Readonly<Record<string, string>> = {},
|
||||
) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method,
|
||||
path,
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
it("compares captured JSON values canonically", () => {
|
||||
const objectMachine = replayMachineSchema.parse({
|
||||
initial_state: "capture",
|
||||
states: [
|
||||
{ name: "capture" },
|
||||
{ name: "guard" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_profile",
|
||||
from: "capture",
|
||||
to: "guard",
|
||||
trigger: { protocol: "http", method: "POST", path: "/capture" },
|
||||
captures: [
|
||||
{
|
||||
variable: "profile",
|
||||
value: { source: "request_json", path: ["profile"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "guard_profile",
|
||||
from: "guard",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "POST", path: "/guard" },
|
||||
guards: [
|
||||
{
|
||||
variable: "profile",
|
||||
value: { source: "request_json", path: ["profile"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
const runtime = new ReplayMachineRuntime(objectMachine);
|
||||
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/capture", '{"profile":{"name":"A","id":1}}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/guard", '{"profile":{"id":1,"name":"A"}}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
});
|
||||
|
||||
it("does not traverse inherited properties in JSON capture paths", () => {
|
||||
const inheritedPathMachine = replayMachineSchema.parse({
|
||||
...machine,
|
||||
transitions: machine.transitions.map((transition, index) =>
|
||||
index === 0
|
||||
? {
|
||||
...transition,
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: {
|
||||
source: "request_json" as const,
|
||||
path: ["__proto__", "toString"],
|
||||
},
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
: transition,
|
||||
),
|
||||
});
|
||||
|
||||
expect(
|
||||
new ReplayMachineRuntime(inheritedPathMachine).dispatch(
|
||||
event("POST", "/login", "{}"),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
});
|
||||
|
||||
it("rejects non-string sensitive captures and retains rotated values", () => {
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(
|
||||
event("POST", "/login", '{"session_value":1234}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
|
||||
const rotatingMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 3 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "rotate",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "POST", path: "/rotate" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 2,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
});
|
||||
const rotating = new ReplayMachineRuntime(rotatingMachine);
|
||||
rotating.dispatch(event("POST", "/rotate", '{"value":"alpha"}'));
|
||||
rotating.dispatch(event("POST", "/rotate", '{"value":"beta"}'));
|
||||
const alias = ["<", "secret", ":session_value>"].join("");
|
||||
|
||||
expect(rotating.redact("alpha beta")).toBe(`${alias} ${alias}`);
|
||||
});
|
||||
|
||||
it("falls back to a lower-priority transition after a preferred one is exhausted", () => {
|
||||
const fallbackMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 2 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "preferred",
|
||||
from: "active",
|
||||
to: "active",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/next" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "again" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "fallback",
|
||||
from: "active",
|
||||
to: "done",
|
||||
priority: 20,
|
||||
trigger: { protocol: "http", method: "GET", path: "/next" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
const runtime = new ReplayMachineRuntime(fallbackMachine);
|
||||
|
||||
expect(runtime.dispatch(event("GET", "/next"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: { transition_id: "preferred" },
|
||||
});
|
||||
expect(runtime.dispatch(event("GET", "/next"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: { transition_id: "fallback" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects non-finite parsed JSON captures and guard values", () => {
|
||||
const jsonMachine = replayMachineSchema.parse({
|
||||
initial_state: "capture",
|
||||
states: [
|
||||
{ name: "capture" },
|
||||
{ name: "guard" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_value",
|
||||
from: "capture",
|
||||
to: "guard",
|
||||
trigger: { protocol: "http", method: "POST", path: "/capture" },
|
||||
captures: [
|
||||
{
|
||||
variable: "value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "guard_value",
|
||||
from: "guard",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "POST", path: "/guard" },
|
||||
guards: [
|
||||
{
|
||||
variable: "value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
expect(
|
||||
new ReplayMachineRuntime(jsonMachine).dispatch(
|
||||
event("POST", "/capture", '{"value":1e400}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
|
||||
const guarded = new ReplayMachineRuntime(jsonMachine);
|
||||
expect(
|
||||
guarded.dispatch(event("POST", "/capture", '{"value":null}')),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
guarded.dispatch(event("POST", "/guard", '{"value":1e400}')),
|
||||
).toMatchObject({ outcome: "guard_failed" });
|
||||
});
|
||||
@@ -0,0 +1,333 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { replayMachineSchema } from "./replayMachine.js";
|
||||
import { ReplayMachineRuntime } from "./replayMachineRuntime.js";
|
||||
|
||||
const machine = replayMachineSchema.parse({
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["session_value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize_api",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
const event = (
|
||||
method: string,
|
||||
path: string,
|
||||
body = "",
|
||||
headers: Readonly<Record<string, string>> = {},
|
||||
) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method,
|
||||
path,
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
it("captures secret values in memory and journals aliases only", () => {
|
||||
const runtime = new ReplayMachineRuntime(machine);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/login", '{"session_value":"test-auth-token"}'),
|
||||
),
|
||||
).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: {
|
||||
transition_id: "capture_token",
|
||||
sensitive_aliases: ["session_value"],
|
||||
},
|
||||
});
|
||||
const expectedRedaction = ["Bearer <", "secret", ":session_value>"].join("");
|
||||
expect(runtime.redact("Bearer test-auth-token")).toBe(expectedRedaction);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("GET", "/api", "", { Authorization: "test-auth-token" }),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(JSON.stringify(runtime.timeline)).not.toContain("test-auth-token");
|
||||
expect(runtime.state).toBe("complete");
|
||||
});
|
||||
|
||||
it("classifies wrong-state, guard, capture, and exhaustion failures", () => {
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(event("GET", "/api")),
|
||||
).toMatchObject({ outcome: "invalid_state" });
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(event("POST", "/login", "{}")),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
const runtime = new ReplayMachineRuntime(machine);
|
||||
runtime.dispatch(
|
||||
event("POST", "/login", '{"session_value":"test-auth-token"}'),
|
||||
);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("GET", "/api", "", {
|
||||
authorization: "test-token-placeholder",
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
outcome: "guard_failed",
|
||||
});
|
||||
const bounded = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [{ name: "active" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "once",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/once" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
}),
|
||||
);
|
||||
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
});
|
||||
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
|
||||
outcome: "transition_exhausted",
|
||||
});
|
||||
});
|
||||
|
||||
it("matches bounded headers and bodies and distinguishes wrong-state reconnects", () => {
|
||||
const runtime = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
initial_state: "connected",
|
||||
states: [{ name: "connected" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "finish",
|
||||
from: "connected",
|
||||
to: "done",
|
||||
trigger: {
|
||||
protocol: "http",
|
||||
method: "POST",
|
||||
path: "/finish",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: '{"done":true}',
|
||||
},
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "initial_socket",
|
||||
from: "connected",
|
||||
to: "connected",
|
||||
trigger: { protocol: "websocket_connect", path: "/ws" },
|
||||
actions: [{ type: "disconnect" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
}),
|
||||
);
|
||||
expect(runtime.dispatch(event("POST", "/finish", "wrong"))).toMatchObject({
|
||||
outcome: "unmatched",
|
||||
});
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "initial",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "transition_exhausted" });
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/finish", '{"done":true}', {
|
||||
"content-type": "application/json",
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "unexpected_reconnect" });
|
||||
});
|
||||
|
||||
it("enforces state, connection, message, byte, and duration limits", () => {
|
||||
const limitedMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 1 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "loop",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "websocket_message", path: "/ws" },
|
||||
actions: [{ type: "websocket_send", data: "ack" }],
|
||||
max_uses: 2,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
limits: { connections: 1, messages: 1, bytes: 100, duration_ms: 10 },
|
||||
});
|
||||
const stateLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
stateLimited.dispatch({
|
||||
protocol: "websocket_message",
|
||||
connection: "not_applicable",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "one",
|
||||
}),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const messageLimited = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
...limitedMachine,
|
||||
states: limitedMachine.states.map((state) =>
|
||||
state.name === "active" ? { ...state, max_visits: 3 } : state,
|
||||
),
|
||||
}),
|
||||
);
|
||||
const message = {
|
||||
protocol: "websocket_message" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "one",
|
||||
};
|
||||
expect(messageLimited.dispatch(message)).toMatchObject({
|
||||
outcome: "matched",
|
||||
});
|
||||
expect(messageLimited.dispatch(message)).toMatchObject({
|
||||
outcome: "limit_exhausted",
|
||||
});
|
||||
const durationLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
durationLimited.dispatch({ ...event("GET", "/done"), at_ms: 11 }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
expect(
|
||||
new ReplayMachineRuntime(limitedMachine).dispatch({
|
||||
...event("GET", "/done"),
|
||||
at_ms: Number.NaN,
|
||||
}),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const monotonic = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
monotonic.dispatch({ ...event("GET", "/missing"), at_ms: 5 }),
|
||||
).toMatchObject({ outcome: "unmatched" });
|
||||
expect(
|
||||
monotonic.dispatch({ ...event("GET", "/missing"), at_ms: 4 }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const byteLimited = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
...limitedMachine,
|
||||
limits: { ...limitedMachine.limits, bytes: 4 },
|
||||
}),
|
||||
);
|
||||
expect(byteLimited.dispatch(event("GET", "/missing", "12345"))).toMatchObject(
|
||||
{ outcome: "limit_exhausted" },
|
||||
);
|
||||
const connectionLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
const connect = {
|
||||
protocol: "websocket_connect" as const,
|
||||
connection: "initial" as const,
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/unknown",
|
||||
headers: {},
|
||||
body: "",
|
||||
};
|
||||
expect(connectionLimited.dispatch(connect)).toMatchObject({
|
||||
outcome: "unmatched",
|
||||
});
|
||||
expect(
|
||||
connectionLimited.dispatch({ ...connect, connection: "reconnect" }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
});
|
||||
Reference in New Issue
Block a user