Files
rea/tests/boundary/cli/nativeFeatureTraceDelivery.test.ts
morluto efbb66c16a fix(errors)!: report wrong-format, missing-file and missing-Evidence refusals by their cause (#15581)
* fix(errors)!: report wrong-format, missing-file and missing-Evidence refusals by their cause

- inspect_labview_artifact refuses a file with no LabVIEW RSRC data as an
  unrecognized target (code unsupported_target, failure_kind unrecognized),
  as its format siblings do, instead of invalid_request. A PE whose
  resource tree could not be fully read is a malformed PE target.
- inspect_gpu_code_objects, inspect_model_artifact and Apktool reported a
  missing or non-regular selected file through their own copy of the
  selected-file refusal (BinaryTargetError, target_unavailable). They now
  use the shared projectSelectedArtifactFileFailure owner
  (invalid_request, conforming, with its own next step), and the copy is
  removed. The shared owner keeps the verified-symlink recovery the copy
  carried.
- A retained Evidence reference the session does not hold is
  invalid_request / invalid_input instead of evidence_integrity_mismatch.
  Altered or unauthenticated Evidence stays evidence_integrity_mismatch.

BREAKING CHANGE: error codes change for three refusals. A non-LabVIEW
file given to inspect_labview_artifact is unsupported_target (was
invalid_request). A missing or non-regular selected file for
inspect_gpu_code_objects, inspect_model_artifact or Apktool operations is
invalid_request (was target_unavailable). A missing retained Evidence
reference (details.reason "missing") is invalid_request with category
invalid_input (was evidence_integrity_mismatch / integrity_mismatch).
Callers that branch on these codes should match the new values;
details.reason, retry_class and the remediation are unchanged in meaning.

* test(model): expect the shared selected-file refusal for a missing model path

The process-global host read failure test still expected
target_unavailable for path errors on a model file. Those are now the
shared selected-file input refusal.

* fix(resources): name a rejected symlink in the shared selected-file refusal

The GPU and model readers' copy of the selected-file refusal said the
path was a symbolic link; the shared owner reported only ELOOP, so
rejectedSymlinkRecovery failed once they moved to it. Use the rejected
symlink's own message, and keep the errno message for every other
selected-path refusal.

* docs(errors): describe missing references and closure members as the caller's selection

The comment above RESOURCE_SNAPSHOT_NOT_APPLICABLE still said a missing
Evidence reference stays an integrity failure. Missing references,
including retained sources and closure members, are invalid_request; only
altered or unauthenticated Evidence stays an integrity failure.
2026-12-01 17:11:08 -05:00

221 lines
7.1 KiB
TypeScript

import { noProviderEffects } from "../../fixtures/analysisExecution.js";
import { createCommandCli } from "../../support/cli/commandCli.js";
import { unknownTarget } from "../../../src/domain/targetIdentity.js";
import { readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import pino from "pino";
import { expect, it } from "vitest";
import {
createAnalysisExecution,
type AnalysisProvider,
} from "../../../src/ports/AnalysisProvider.js";
import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js";
import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js";
import { registerCoreBinaryCommands } from "../../../src/cli/coreBinaryCommands.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { parseEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { ok } from "../../../src/domain/result.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const identity = { id: "fixture", name: "Fixture", version: "1" } as const;
const effects = noProviderEffects();
const verifyReplay = async (
cli: ReturnType<typeof createCommandCli>,
path: string,
snapshot: string,
root: string,
originalBundle: ReturnType<typeof parseEvidenceBundle>,
traceId: string | undefined,
) => {
const output = join(root, "replay-evidence.json");
let stdout = "";
await cli.serve(
[
"trace",
path,
"goal",
"--provider",
"fixture",
"--snapshot",
snapshot,
"--detail",
"summary",
"--evidence_output",
output,
"--json",
],
{
env: {},
stdout: (text) => {
stdout += text;
},
exit: () => undefined,
},
);
const response = JSON.parse(stdout);
expect(response, JSON.stringify(response)).toHaveProperty("summary");
const bundle = parseEvidenceBundle(
JSON.parse(await readFile(output, "utf8")),
);
expect(response.summary.normalized_result.parent_evidence_id).toBe(traceId);
expect(bundle.records.map((record) => record.evidence_id).sort()).toEqual(
originalBundle.records.map((record) => record.evidence_id).sort(),
);
};
it.each([
{ detail: "summary", missing: false },
{ detail: "complete", missing: false },
{ detail: "summary", missing: true },
{ detail: "summary", missing: false, replay: true },
])(
"publishes $detail trace only when its source closure is available (missing=$missing, replay=$replay)",
async ({ detail, missing, replay }) => {
const root = await createTestTempDirectory("rea-native-trace-cli-source-");
const path = join(root, "fixture.hop");
const output = join(root, "evidence.json");
const snapshot = join(root, "snapshot.json");
let allowProvider = true;
await writeFile(path, "synthetic analysis database");
const history = createEvidence(unknownTarget("not-observed"), identity, {
operation: "health",
parameters: { facet: "historical-project-analysis-reports" },
result: { origin: "caller-project" },
confidence: "observed",
...(missing ? { evidenceLinks: ["ev_" + "a".repeat(64)] } : {}),
});
const provider: AnalysisProvider = {
identity: () => identity,
capabilities: () =>
(
[
"search_strings",
"search_procedures",
"xrefs",
"resolve_containing_procedure",
] as const
).map((operation) => ({
provider: identity,
operation,
available: true,
reason: null,
cachePolicy: replay ? "snapshot" : "live",
limitations: [],
effects,
})),
resolveAnalysisProfile: async () =>
ok({ profile: createAnalysisProfile(identity, { fixture: true }) }),
createClient: () => {
if (!allowProvider)
throw new Error("Snapshot replay reopened the provider");
return {
execute: async (operation) => {
const value =
operation === "search_procedures"
? [{ address: "0x1000", value: "goal" }]
: operation === "xrefs"
? ["0x1010"]
: operation === "resolve_containing_procedure"
? {
query_address: "0x1010",
found: false,
procedure: null,
reason: "not_in_procedure",
}
: operation === "search_strings"
? []
: null;
return ok(
createAnalysisExecution(value, identity, {
sourceEvidence: [history],
}),
);
},
close: async () => ok(null),
};
},
};
const createSession = () => createTestBinarySession(provider);
const dependencies: DirectAnalysisDependencies = {
readConfiguration: () => parseConfig({}),
createBinarySession: createSession,
createNativeDispatchBinarySession: createSession,
createArtifactBinarySession: createSession,
createNativeBinarySession: createSession,
createManagedBinarySession: createSession,
};
const cli = createCommandCli();
registerCoreBinaryCommands(
cli,
pino({ enabled: false }),
(target, tool, args, options) =>
runDirectAnalysis(dependencies, target, tool, args, options),
{},
);
let stdout = "";
await cli.serve(
[
"trace",
path,
"goal",
"--provider",
"fixture",
...(replay ? ["--snapshot", snapshot] : []),
"--detail",
detail,
"--evidence_output",
output,
"--json",
],
{
env: {},
stdout: (text) => {
stdout += text;
},
exit: () => undefined,
},
);
const response = JSON.parse(stdout);
if (missing) {
expect(response).toMatchObject({
code: "invalid_request",
details: { reason: "missing", evidence_id: "ev_" + "a".repeat(64) },
});
await expect(stat(output)).rejects.toMatchObject({ code: "ENOENT" });
} else {
const bundle = parseEvidenceBundle(
JSON.parse(await readFile(output, "utf8")),
);
const trace = bundle.records.find(
(record) => record.operation === "trace_feature",
);
expect(
detail === "summary"
? response.summary.normalized_result.parent_evidence_id
: response.evidence_id,
).toBe(trace?.evidence_id);
expect(trace?.evidence_links).toContain(history.evidence_id);
expect(
bundle.records.some(
(record) => record.evidence_id === history.evidence_id,
),
).toBe(true);
if (replay) {
allowProvider = false;
await verifyReplay(
cli,
path,
snapshot,
root,
bundle,
trace?.evidence_id,
);
}
}
},
);