feat(dotnet): verify managed native boundaries

Add the verify_managed_native_boundaries workflow for comparing authenticated inspect_managed_native_boundaries Evidence with supplied native export or function Evidence. The workflow verifies only P/Invoke declaration names against observed native symbols, keeps verified, inferred, contradicted, unresolved, and unsupported-native states explicit, and does not translate managed metadata tokens or RVAs into native addresses.

Expose schema-identical MCP and CLI surfaces, update managed workflow contracts, product catalog facts, TypeDoc output, README/localized docs, ADR status, package verification, and the REA analysis skill metadata for the 90-tool/50-command inventory.

Verification: npx vitest run tests/managedNativeVerification.test.ts --coverage=false; npm run typecheck; npm run docs:generate; npm run check (first run hit a load-sensitive sessionMcp timeout, isolated rerun passed); npx vitest run tests/sessionMcp.test.ts --coverage=false; npm run check; npm run knip; npm run jscpd; npm run scan:todos; npm run verify:managed; CXX=/usr/bin/g++-13 CC=/usr/bin/gcc-13 npm run verify:package.
This commit is contained in:
N0zoM1z0
2026-07-16 21:26:38 +09:00
committed by N0zoM1z0
parent cc1e47c615
commit 8cbc125b93
97 changed files with 1857 additions and 160 deletions
@@ -0,0 +1,64 @@
import { z } from "zod";
import {
AnalysisInputError,
AnalysisProtocolError,
type AnalysisError,
} from "../domain/errors.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
managedNativeVerificationInputSchema,
verifyManagedNativeBoundaries,
type ManagedNativeVerificationInput,
type ManagedNativeVerificationResult,
} from "../domain/managedNativeVerification.js";
import { err, ok, type Result } from "../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
const OPERATION = "verify_managed_native_boundaries" as const;
/** Verify managed/native boundary declarations against native Evidence. */
export const verifyManagedNativeBoundariesEvidence = (
rawInput: unknown,
): Result<Evidence, AnalysisError> => {
const parsed = managedNativeVerificationInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
try {
const result = verifyManagedNativeBoundaries(parsed.data);
return ok(createManagedNativeVerificationEvidence(parsed.data, result));
} catch (cause: unknown) {
return err(
cause instanceof TypeError || cause instanceof z.ZodError
? new AnalysisInputError(OPERATION, { cause })
: new AnalysisProtocolError(
"Managed/native verification produced an invalid result",
{ cause },
),
);
}
};
const createManagedNativeVerificationEvidence = (
input: ManagedNativeVerificationInput,
result: ManagedNativeVerificationResult,
): Evidence =>
createEvidence(undefined, MANAGED_WORKFLOW_PROVIDER, {
predicateType: "rea.managed-native-verification/v1",
operation: OPERATION,
parameters: {
managed_boundaries_evidence_id: input.managed_boundaries.evidence_id,
native_evidence_ids: jsonValueSchema.parse(
input.native_observations.map(({ evidence_id: id }) => id),
),
limits: jsonValueSchema.parse(input.limits),
},
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations: result.limitations,
evidenceLinks: result.evidence_links,
});
+20
View File
@@ -9,6 +9,7 @@ import {
runSessionStatus,
} from "./application/DirectAnalysis.js";
import { compareManagedMemberPaths } from "./application/ManagedMemberComparisonService.js";
import { verifyManagedNativeBoundariesEvidence } from "./application/ManagedNativeVerificationService.js";
import { importManagedReconstructionEvidence } from "./application/ManagedReconstructionService.js";
import { planManagedRuntimeCorrelationEvidence } from "./application/ManagedRuntimeCorrelationService.js";
import {
@@ -913,6 +914,25 @@ const registerManagedCommands = (
return result.ok ? result.value : projectAnalysisError(result.error);
}),
});
cli.command(CLI_COMMANDS.verifyManagedNativeBoundaries, {
description:
"Verify managed P/Invoke declarations against authenticated native Evidence",
args: z.object({
inputJson: z
.string()
.describe("Inline managed/native verification JSON or JSON file path"),
}),
run: ({ args }) =>
logCliCommand(logger, "verify-managed-native-boundaries", async () => {
const input = await parseCliJsonInput(
args.inputJson,
"verify-managed-native-boundaries",
);
if (!input.ok) return input.error;
const result = verifyManagedNativeBoundariesEvidence(input.value);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
});
cli.command(CLI_COMMANDS.planManagedRuntimeCorrelation, {
description:
"Plan a separately authorized managed runtime-correlation experiment without executing target code",
+1
View File
@@ -20,6 +20,7 @@ export const CLI_COMMANDS = Object.freeze({
inspectManagedMembers: "inspect-managed-members",
inspectManagedNativeBoundaries: "inspect-managed-native-boundaries",
compareManagedMembers: "compare-managed-members",
verifyManagedNativeBoundaries: "verify-managed-native-boundaries",
importManagedReconstruction: "import-managed-reconstruction",
planManagedRuntimeCorrelation: "plan-managed-runtime-correlation",
inspectMacho: "inspect-macho",
+174 -1
View File
@@ -1,5 +1,9 @@
import { createEvidence } from "../domain/evidence.js";
import type { ManagedMemberInspection } from "../domain/managedArtifact.js";
import type {
ManagedMemberInspection,
ManagedNativeBoundaryInspection,
} from "../domain/managedArtifact.js";
import type { InspectMacho } from "../domain/nativeInspection.js";
const MANAGED_STATIC_EXAMPLE_PROVIDER = {
id: "rea-dotnet-static",
@@ -7,6 +11,12 @@ const MANAGED_STATIC_EXAMPLE_PROVIDER = {
version: "1",
} as const;
const NATIVE_EXAMPLE_PROVIDER = {
id: "native-macos",
name: "REA native macOS provider",
version: "1",
} as const;
const emptyManagedMembers = (
sha256: string,
mvid: string,
@@ -142,6 +152,159 @@ export const MANAGED_MEMBER_COMPARISON_EXAMPLE = {
const runtimeExampleEvidence = evidence(runtimeMembers());
const boundaryEvidence = () => {
const result: ManagedNativeBoundaryInspection = {
schema_version: 1,
artifact: {
path: "/examples/ManagedInterop.exe",
sha256: "6".repeat(64),
byte_length: 8192,
format: "pe",
},
module: {
name: "ManagedInterop.exe",
generation: 0,
mvid: "00112233-4455-4677-8899-aabbccddeeff",
enc_id: null,
enc_base_id: null,
token: "0x00000001",
row_offset: 0,
},
metadata: {
status: "complete",
version: "v4.0.30319",
table_row_counts: {},
},
identity_scope: {
token_identity: "build-local",
requires_artifact_sha256: "6".repeat(64),
requires_mvid: "00112233-4455-4677-8899-aabbccddeeff",
},
cli_native: {
il_only: true,
requires_32bit: false,
strong_name_signed: false,
native_entry_point: false,
ready_to_run_signature: false,
managed_native_header_rva: 0,
managed_native_header_size: 0,
},
module_refs: {
items: [
{
token: "0x1a000001",
row_offset: 256,
name: "nativehelper.dll",
},
],
offset: 0,
limit: 100,
total: 1,
returned: 1,
dropped: 0,
complete: true,
},
pinvoke_imports: {
items: [
{
token: "0x1c000001",
row_offset: 288,
mapping_flags: 0,
mapping_flags_hex: "0x0000",
member_token: "0x06000001",
member_kind: "method",
member_name: "OpenNative",
import_name: "open_native",
import_scope_token: "0x1a000001",
import_scope_name: "nativehelper.dll",
no_mangle: true,
char_set: "not-specified",
call_convention: "cdecl",
supports_last_error: false,
best_fit: "assembly-default",
throw_on_unmappable_char: "assembly-default",
verification: "managed-declaration-only",
},
],
offset: 0,
limit: 100,
total: 1,
returned: 1,
dropped: 0,
complete: true,
},
native_implementations: emptyPage(100),
summary: {
module_ref_count: 1,
pinvoke_import_count: 1,
native_implementation_count: 0,
ready_to_run: false,
mixed_mode_or_native_header: false,
},
coverage: { state: "complete", issues: [] },
limitations: [],
};
return createEvidence(undefined, MANAGED_STATIC_EXAMPLE_PROVIDER, {
operation: "inspect_managed_native_boundaries",
parameters: {},
result,
rawResult: null,
limitations: result.limitations,
});
};
const nativeExportEvidence = () => {
const result: InspectMacho = {
format: "mach-o",
endian: "little",
word_size: 64,
file_type: "dylib",
flags: [],
uuid: null,
entrypoints: coverage([]),
architectures: coverage([]),
build_metadata: coverage([]),
load_commands: coverage([]),
dependencies: coverage([]),
imports: coverage([]),
exports: coverage([
{
name: "open_native",
address: "0x1000",
weak: false,
reexport: false,
source: "nm",
},
]),
segments: coverage([]),
provenance: [],
limitations: [],
};
return createEvidence(
{
path: "/examples/nativehelper.dll",
sha256: "7".repeat(64),
format: "mach-o",
architecture: "x86_64",
},
NATIVE_EXAMPLE_PROVIDER,
{
operation: "inspect_macho",
parameters: {},
result,
rawResult: null,
limitations: result.limitations,
},
);
};
const coverage = <Item>(items: readonly Item[]) => ({
items: [...items],
total: items.length,
exhaustive: true,
limitations: [],
});
/** Minimal valid managed decompiler reconstruction import request. */
export const MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE = {
static_members: runtimeExampleEvidence,
@@ -172,6 +335,16 @@ export const MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE = {
],
};
/** Minimal valid managed/native verification request. */
export const MANAGED_NATIVE_VERIFICATION_EXAMPLE = {
managed_boundaries: boundaryEvidence(),
native_observations: [nativeExportEvidence()],
limits: {
max_native_observations: 20,
max_candidates_per_import: 25,
},
};
/** Minimal valid managed runtime-correlation planning request. */
export const MANAGED_RUNTIME_CORRELATION_EXAMPLE = {
static_members: runtimeExampleEvidence,
@@ -1,10 +1,12 @@
import { compareManagedMembersInputSchema } from "../domain/managedMemberComparison.js";
import { managedNativeVerificationInputSchema } from "../domain/managedNativeVerification.js";
import { managedReconstructionImportInputSchema } from "../domain/managedReconstruction.js";
import { managedRuntimeCorrelationInputSchema } from "../domain/managedRuntimeCorrelation.js";
import type { ToolContract } from "./toolContracts.js";
import { managedWorkflowOutputSchemas } from "./toolOutputSchemas.js";
import {
MANAGED_MEMBER_COMPARISON_EXAMPLE,
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
MANAGED_RUNTIME_CORRELATION_EXAMPLE,
} from "./managedWorkflowExamples.js";
@@ -27,6 +29,12 @@ if (reconstructionOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for import_managed_reconstruction",
);
const nativeVerificationOutputSchema =
managedWorkflowOutputSchemas.verify_managed_native_boundaries;
if (nativeVerificationOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for verify_managed_native_boundaries",
);
/** Provider-neutral managed-code workflow contracts. */
export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
@@ -50,6 +58,26 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
},
],
},
{
name: "verify_managed_native_boundaries",
description:
"Verify managed P/Invoke/native-boundary declarations against authenticated native export or function Evidence without executing managed code or translating managed metadata tokens into native addresses. The workflow preserves declaration-only, verified, inferred, contradicted, and unresolved states.",
kind: "application",
inputSchema: managedNativeVerificationInputSchema,
outputSchema: nativeVerificationOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Verify a managed P/Invoke declaration against native Evidence",
input: MANAGED_NATIVE_VERIFICATION_EXAMPLE,
},
],
},
{
name: "import_managed_reconstruction",
description:
+4
View File
@@ -30,6 +30,7 @@ import {
managedNativeBoundaryInspectionSchema,
} from "../domain/managedArtifact.js";
import { managedMemberComparisonResultSchema } from "../domain/managedMemberComparison.js";
import { managedNativeVerificationResultSchema } from "../domain/managedNativeVerification.js";
import { managedReconstructionImportResultSchema } from "../domain/managedReconstruction.js";
import { managedRuntimeCorrelationResultSchema } from "../domain/managedRuntimeCorrelation.js";
import { artifactComparisonResultSchema } from "../domain/artifactComparison.js";
@@ -551,6 +552,9 @@ export const managedWorkflowOutputSchemas: Readonly<
Record<string, z.ZodObject>
> = {
compare_managed_members: resultOf(managedMemberComparisonResultSchema),
verify_managed_native_boundaries: resultOf(
managedNativeVerificationResultSchema,
),
import_managed_reconstruction: resultOf(
managedReconstructionImportResultSchema,
),
+528
View File
@@ -0,0 +1,528 @@
import { createHash } from "node:crypto";
import { basename } from "node:path";
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceSchema, parseEvidence } from "./evidence.js";
import { functionDossierSchema } from "./hopperValues.js";
import {
managedNativeBoundaryInspectionSchema,
type ManagedNativeBoundaryInspection,
} from "./managedArtifact.js";
import { inspectMachoSchema } from "./nativeInspection.js";
import type { JsonValue } from "./jsonValue.js";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
const nativeVerificationLimitsSchema = z.strictObject({
max_native_observations: z.number().int().min(1).max(50).default(20),
max_candidates_per_import: z.number().int().min(1).max(100).default(25),
});
/** Authenticated managed boundary Evidence plus native observations. */
export const managedNativeVerificationInputSchema = z
.strictObject({
managed_boundaries: evidenceSchema,
native_observations: z.array(evidenceSchema).min(1).max(50),
limits: nativeVerificationLimitsSchema.default({
max_native_observations: 20,
max_candidates_per_import: 25,
}),
unknown_registry_approved: z.literal(true).optional(),
})
.superRefine((input, context) => {
const ids = new Set<string>();
for (const [index, evidence] of input.native_observations.entries()) {
if (evidence.evidence_id === input.managed_boundaries.evidence_id) {
context.addIssue({
code: "custom",
path: ["native_observations", index],
message:
"Native observation Evidence must be distinct from managed boundary Evidence",
});
}
if (ids.has(evidence.evidence_id)) {
context.addIssue({
code: "custom",
path: ["native_observations", index],
message: "Native observation Evidence IDs must be unique",
});
}
ids.add(evidence.evidence_id);
}
});
const nativeSymbolSchema = z.strictObject({
evidence_id: evidenceIdSchema,
operation: z.string().min(1),
name: z.string().min(1),
address: z.string().nullable(),
module_name: z.string().nullable(),
module_path: z.string().nullable(),
source: z.enum(["macho-export", "function-dossier"]),
});
const matchStatusSchema = z.enum([
"verified",
"inferred",
"unresolved",
"contradicted",
]);
const matchBasisSchema = z.enum([
"exact-export-name",
"exact-function-name",
"decorated-name-candidate",
"module-mismatch",
"no-native-candidate",
"unsupported-native-evidence",
]);
const pinvokeVerificationSchema = z.strictObject({
item_id: z.string().regex(/^mnv_pinvoke_[a-f0-9]{64}$/u),
managed: z.strictObject({
token: tokenSchema,
member_token: tokenSchema.nullable(),
member_name: z.string().nullable(),
import_name: z.string().min(1),
import_scope_name: z.string().nullable(),
no_mangle: z.boolean(),
char_set: z.enum(["not-specified", "ansi", "unicode", "auto", "unknown"]),
call_convention: z.enum([
"not-specified",
"winapi",
"cdecl",
"stdcall",
"thiscall",
"fastcall",
"unknown",
]),
declaration_verification: z.literal("managed-declaration-only"),
}),
status: matchStatusSchema,
basis: matchBasisSchema,
confidence: z.enum(["observed", "inferred", "unknown"]),
matched_native: nativeSymbolSchema.nullable(),
candidates: z.array(nativeSymbolSchema).max(100),
evidence_links: z.array(evidenceIdSchema).min(1).max(51),
limitations: z.array(boundedTextSchema).max(100),
});
/** Provider-neutral managed/native verification result. */
export const managedNativeVerificationResultSchema = z.strictObject({
schema_version: z.literal(1),
verification_id: z.string().regex(/^mnv_[a-f0-9]{64}$/u),
algorithm: z.strictObject({
name: z.literal("rea-managed-native-verification"),
version: z.literal(1),
token_identity: z.literal("build-local"),
token_to_address_mapping: z.literal("not-inferred"),
}),
managed_boundary: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
artifact_path: z.string().min(1),
mvid: z.string().uuid().nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
pinvoke_imports_total: z.number().int().min(0),
native_implementations_total: z.number().int().min(0),
coverage_state: z.enum(["complete", "partial", "unavailable"]),
}),
native_observations: z.strictObject({
total: z.number().int().min(1),
accepted: z.number().int().min(0),
unsupported: z.number().int().min(0),
symbols: z.number().int().min(0),
truncated: z.boolean(),
}),
summary: z.strictObject({
verified: z.number().int().min(0),
inferred: z.number().int().min(0),
unresolved: z.number().int().min(0),
contradicted: z.number().int().min(0),
native_body_unresolved: z.number().int().min(0),
}),
pinvoke_imports: z.array(pinvokeVerificationSchema).max(50_000),
native_implementations: z.strictObject({
unresolved: z.number().int().min(0),
reason: boundedTextSchema,
}),
coverage: z.strictObject({
status: z.enum(["complete-within-inputs", "partial", "truncated"]),
omitted_native_observations: z.number().int().min(0),
omitted_candidates: z.number().int().min(0),
}),
evidence_links: z.array(evidenceIdSchema).min(2).max(51),
limitations: z.array(boundedTextSchema).max(1_000),
});
export type ManagedNativeVerificationInput = z.infer<
typeof managedNativeVerificationInputSchema
>;
export type ManagedNativeVerificationResult = z.infer<
typeof managedNativeVerificationResultSchema
>;
type NativeSymbol = z.infer<typeof nativeSymbolSchema>;
type PinvokeImport =
ManagedNativeBoundaryInspection["pinvoke_imports"]["items"][number];
type PinvokeVerification = z.infer<typeof pinvokeVerificationSchema>;
type VerifiedPinvoke = {
readonly verification: PinvokeVerification;
readonly omittedCandidates: number;
};
const sha256 = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed/native verification canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
/** Verify managed P/Invoke declarations against authenticated native Evidence. */
export const verifyManagedNativeBoundaries = (
input: ManagedNativeVerificationInput,
): ManagedNativeVerificationResult => {
const managedEvidence = parseEvidence(input.managed_boundaries);
if (managedEvidence.operation !== "inspect_managed_native_boundaries")
throw new TypeError(
"Evidence operation is not inspect_managed_native_boundaries",
);
const managed = managedNativeBoundaryInspectionSchema.parse(
managedEvidence.normalized_result,
);
const native = collectNativeSymbols(
input.native_observations.slice(0, input.limits.max_native_observations),
);
const verifiedPinvokes = managed.pinvoke_imports.items.map((item) =>
verifyPinvoke(
item,
managedEvidence.evidence_id,
native.symbols,
native.accepted > 0,
input,
),
);
const pinvokeImports = verifiedPinvokes.map(
({ verification }) => verification,
);
const counts = countStatuses(pinvokeImports);
const omittedNativeObservations = Math.max(
0,
input.native_observations.length - input.limits.max_native_observations,
);
const omittedCandidates = verifiedPinvokes.reduce(
(sum, item) => sum + item.omittedCandidates,
0,
);
const coverageStatus =
omittedNativeObservations > 0 || omittedCandidates > 0
? "truncated"
: managed.coverage.state === "complete" && native.unsupported === 0
? "complete-within-inputs"
: "partial";
const withoutId = {
schema_version: 1 as const,
algorithm: {
name: "rea-managed-native-verification" as const,
version: 1 as const,
token_identity: "build-local" as const,
token_to_address_mapping: "not-inferred" as const,
},
managed_boundary: {
evidence_id: managedEvidence.evidence_id,
artifact_sha256: managed.artifact.sha256,
artifact_path: managed.artifact.path,
mvid: managed.module?.mvid ?? null,
metadata_status: managed.metadata.status,
pinvoke_imports_total: managed.pinvoke_imports.total,
native_implementations_total: managed.native_implementations.total,
coverage_state: managed.coverage.state,
},
native_observations: {
total: input.native_observations.length,
accepted: native.accepted,
unsupported: native.unsupported,
symbols: native.symbols.length,
truncated: omittedNativeObservations > 0,
},
summary: {
...counts,
native_body_unresolved: managed.native_implementations.items.filter(
({ boundary_kind: kind }) => kind !== "pinvoke",
).length,
},
pinvoke_imports: pinvokeImports,
native_implementations: {
unresolved: managed.native_implementations.items.filter(
({ boundary_kind: kind }) => kind !== "pinvoke",
).length,
reason:
"Managed metadata tokens and RVAs are not translated to native provider addresses by this workflow; C++/CLI, ReadyToRun, and native-body mappings require explicit provider-supported bridge evidence.",
},
coverage: {
status: coverageStatus,
omitted_native_observations: omittedNativeObservations,
omitted_candidates: omittedCandidates,
},
evidence_links: [
managedEvidence.evidence_id,
...input.native_observations
.slice(0, input.limits.max_native_observations)
.map(({ evidence_id: id }) => id),
],
limitations: [
"P/Invoke verification checks declared import names against supplied native export or function-name Evidence only.",
"A matching native symbol verifies that a candidate export/function was observed; it does not prove CLR binding, marshaling behavior, call reachability, or runtime loading.",
"Missing supplied native symbols are reported as unresolved, not proof that a dependency cannot exist.",
"Managed metadata tokens and method RVAs are not interpreted as native addresses.",
...(managed.coverage.state === "complete"
? []
: ["Managed boundary input is partial or unavailable."]),
...(native.unsupported === 0
? []
: [
"Some native Evidence operations were unsupported by this workflow.",
]),
],
};
return managedNativeVerificationResultSchema.parse({
...withoutId,
verification_id: `mnv_${sha256(withoutId)}`,
});
};
const collectNativeSymbols = (
observations: readonly ManagedNativeVerificationInput["native_observations"][number][],
): {
readonly symbols: readonly NativeSymbol[];
readonly accepted: number;
readonly unsupported: number;
} => {
const symbols: NativeSymbol[] = [];
let accepted = 0;
let unsupported = 0;
for (const raw of observations) {
const evidence = parseEvidence(raw);
const extracted = symbolsForEvidence(evidence);
if (!extracted.supported) {
unsupported += 1;
} else {
accepted += 1;
symbols.push(...extracted.symbols);
}
}
return { symbols, accepted, unsupported };
};
const symbolsForEvidence = (
evidence: ReturnType<typeof parseEvidence>,
): {
readonly supported: boolean;
readonly symbols: readonly NativeSymbol[];
} => {
if (evidence.operation === "inspect_macho") {
const result = inspectMachoSchema.parse(evidence.normalized_result);
return {
supported: true,
symbols: result.exports.items.map((symbol) => ({
evidence_id: evidence.evidence_id,
operation: evidence.operation,
name: symbol.name,
address: symbol.address,
module_name: moduleName(evidence),
module_path: modulePath(evidence),
source: "macho-export" as const,
})),
};
}
if (evidence.operation === "analyze_function") {
const dossier = functionDossierSchema.parse(evidence.normalized_result);
return {
supported: true,
symbols: [
{
evidence_id: evidence.evidence_id,
operation: evidence.operation,
name: dossier.procedure.name,
address: dossier.procedure.address,
module_name: moduleName(evidence),
module_path: modulePath(evidence),
source: "function-dossier" as const,
},
],
};
}
return { supported: false, symbols: [] };
};
const verifyPinvoke = (
item: PinvokeImport,
managedEvidenceId: string,
symbols: readonly NativeSymbol[],
hasSupportedNativeEvidence: boolean,
input: ManagedNativeVerificationInput,
): VerifiedPinvoke => {
const managed = {
token: item.token,
member_token: item.member_token,
member_name: item.member_name,
import_name: item.import_name,
import_scope_name: item.import_scope_name,
no_mangle: item.no_mangle,
char_set: item.char_set,
call_convention: item.call_convention,
declaration_verification: item.verification,
};
const names = candidateNames(managed);
const allCandidates = symbols.filter((symbol) =>
names.some((name) => sameSymbolName(name, symbol.name)),
);
const candidates = allCandidates.slice(
0,
input.limits.max_candidates_per_import,
);
const exact = candidates.find(
(symbol) =>
sameSymbolName(item.import_name, symbol.name) &&
moduleCompatible(item.import_scope_name, symbol),
);
const decorated = candidates.find((symbol) =>
moduleCompatible(item.import_scope_name, symbol),
);
const selected = exact ?? decorated ?? candidates[0] ?? null;
const basis =
selected === null
? hasSupportedNativeEvidence
? "no-native-candidate"
: "unsupported-native-evidence"
: !moduleCompatible(item.import_scope_name, selected)
? "module-mismatch"
: exact !== undefined
? selected.source === "macho-export"
? "exact-export-name"
: "exact-function-name"
: "decorated-name-candidate";
const status =
selected === null
? "unresolved"
: basis === "module-mismatch"
? "contradicted"
: basis === "decorated-name-candidate"
? "inferred"
: "verified";
const limitations = [
...(item.import_scope_name === null
? ["Managed declaration does not name an import scope/module."]
: []),
...(status === "inferred"
? [
"Native symbol matched a decorated candidate rather than the exact declared import name.",
]
: []),
...(status === "contradicted"
? [
"A symbol name candidate exists, but the supplied native Evidence module identity does not match the managed import scope.",
]
: []),
...(status === "unresolved"
? [
"No supplied native export/function Evidence matched this declared import.",
]
: []),
];
return {
verification: pinvokeVerificationSchema.parse({
item_id: `mnv_pinvoke_${sha256({
managedEvidenceId,
token: item.token,
importName: item.import_name,
importScope: item.import_scope_name,
candidates,
})}`,
managed,
status,
basis,
confidence:
status === "verified"
? "observed"
: status === "inferred"
? "inferred"
: "unknown",
matched_native: selected,
candidates,
evidence_links: [
managedEvidenceId,
...new Set(candidates.map(({ evidence_id: id }) => id)),
],
limitations,
}),
omittedCandidates: Math.max(0, allCandidates.length - candidates.length),
};
};
const candidateNames = (
managed: Pick<
PinvokeImport,
"import_name" | "char_set" | "call_convention" | "no_mangle"
>,
): readonly string[] => {
const names = new Set<string>([managed.import_name]);
if (!managed.no_mangle) {
if (managed.char_set === "unicode") names.add(`${managed.import_name}W`);
if (managed.char_set === "ansi") names.add(`${managed.import_name}A`);
if (managed.call_convention === "stdcall") {
names.add(`_${managed.import_name}`);
names.add(`_${managed.import_name}@0`);
}
}
return [...names];
};
const sameSymbolName = (left: string, right: string): boolean =>
normalizeSymbol(left) === normalizeSymbol(right);
const normalizeSymbol = (value: string): string =>
value.replace(/^_+/u, "").replace(/@\d+$/u, "").toLowerCase();
const moduleCompatible = (
scope: string | null,
symbol: NativeSymbol,
): boolean => {
if (scope === null) return true;
const expected = normalizeModule(scope);
return [symbol.module_name, symbol.module_path]
.filter((value): value is string => value !== null)
.map(normalizeModule)
.some((value) => value === expected);
};
const normalizeModule = (value: string): string =>
basename(value)
.toLowerCase()
.replace(/^lib/u, "")
.replace(/\.(dll|dylib|so|node|exe)$/u, "");
const moduleName = (
evidence: ReturnType<typeof parseEvidence>,
): string | null => evidence.subject?.name ?? null;
const modulePath = (
evidence: ReturnType<typeof parseEvidence>,
): string | null => evidence.subject?.local_path ?? null;
const countStatuses = (
items: readonly z.infer<typeof pinvokeVerificationSchema>[],
): Pick<
ManagedNativeVerificationResult["summary"],
"verified" | "inferred" | "unresolved" | "contradicted"
> => ({
verified: items.filter(({ status }) => status === "verified").length,
inferred: items.filter(({ status }) => status === "inferred").length,
unresolved: items.filter(({ status }) => status === "unresolved").length,
contradicted: items.filter(({ status }) => status === "contradicted").length,
});
+1
View File
@@ -156,4 +156,5 @@ export const demangleSwiftSchema = z.object({
export type NativeCommandInvocation = z.infer<
typeof nativeCommandInvocationSchema
>;
export type InspectMacho = z.infer<typeof inspectMachoSchema>;
export type InspectSignature = z.infer<typeof inspectSignatureSchema>;
@@ -2,6 +2,7 @@ import type { McpServer } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { compareManagedMembersEvidence } from "../application/ManagedMemberComparisonService.js";
import { verifyManagedNativeBoundariesEvidence } from "../application/ManagedNativeVerificationService.js";
import { importManagedReconstructionEvidence } from "../application/ManagedReconstructionService.js";
import {
planManagedRuntimeCorrelationEvidence,
@@ -12,6 +13,10 @@ import {
compareManagedMembersInputSchema,
managedMemberComparisonResultSchema,
} from "../domain/managedMemberComparison.js";
import {
managedNativeVerificationInputSchema,
managedNativeVerificationResultSchema,
} from "../domain/managedNativeVerification.js";
import { managedReconstructionImportInputSchema } from "../domain/managedReconstruction.js";
import { managedRuntimeCorrelationInputSchema } from "../domain/managedRuntimeCorrelation.js";
import type { Evidence } from "../domain/evidence.js";
@@ -35,6 +40,9 @@ export const registerManagedWorkflowTools = (
options: ManagedWorkflowToolRegistration,
): void => {
const compareContract = contract("compare_managed_members");
const nativeVerificationContract = contract(
"verify_managed_native_boundaries",
);
const reconstructionContract = contract("import_managed_reconstruction");
const runtimeContract = contract("plan_managed_runtime_correlation");
server.registerTool(
@@ -91,6 +99,66 @@ export const registerManagedWorkflowTools = (
);
},
);
server.registerTool(
nativeVerificationContract.name,
toolRegistrationOptions(nativeVerificationContract),
async (input) => {
const parsed = managedNativeVerificationInputSchema.parse(input);
const result = await logToolExecution(
options.logger,
nativeVerificationContract.name,
() => Promise.resolve(verifyManagedNativeBoundariesEvidence(parsed)),
);
if (!result.ok)
return toCallToolResult(result, nativeVerificationContract);
const recordedSources = recordSources(options.recordEvidence, [
parsed.managed_boundaries,
...parsed.native_observations,
]);
if (!recordedSources.ok)
return toCallToolResult(recordedSources, nativeVerificationContract);
const verification = managedNativeVerificationResultSchema.parse(
result.value.normalized_result,
);
const unknown =
verification.summary.unresolved > 0 ||
verification.summary.contradicted > 0 ||
verification.summary.native_body_unresolved > 0;
const output =
parsed.unknown_registry_approved === true && unknown
? options.recordEvidenceWithUnknown?.(result.value, {
approved: true,
question:
"Which managed/native boundaries remain unresolved or contradicted by the supplied native Evidence?",
severity: "medium",
domain: "managed-native-verification",
supporting_evidence_ids: [result.value.evidence_id],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "inspect_managed_native_boundaries",
rationale:
"Repeat managed boundary inspection with complete ModuleRef, ImplMap, and native implementation pages.",
},
{
operation: "analyze_function",
rationale:
"Analyze the provider-resolved native function candidate for the declared export.",
},
],
relationships: [],
})
: options.recordEvidence?.(result.value);
if (output !== undefined && !output.ok)
return toCallToolResult(output, nativeVerificationContract);
return toCallToolResult(result, nativeVerificationContract, {
evidenceResourcesAvailable: output !== undefined,
});
},
);
server.registerTool(
reconstructionContract.name,
toolRegistrationOptions(reconstructionContract),