feat(dotnet): add managed runtime correlation planning

This commit is contained in:
N0zoM1z0
2026-07-16 20:10:36 +09:00
committed by N0zoM1z0
parent 2b75fcfaac
commit 5f66cfd57a
149 changed files with 2034 additions and 365 deletions
+1 -1
View File
@@ -37,7 +37,7 @@ describe("browser MCP tools", () => {
const connected = await connectBrowser(browser);
const tools = await connected.client.listTools();
expect(tools.tools).toHaveLength(87);
expect(tools.tools).toHaveLength(88);
expect(tools.tools.map(({ name }) => name)).toEqual(
expect.arrayContaining([
"list_browser_targets",
+44
View File
@@ -39,6 +39,11 @@ describe("runtime configuration", () => {
enabled: false,
roots: [],
});
expect(result.value.managedRuntimePolicy).toMatchObject({
enabled: false,
roots: [],
executablePath: "/usr/bin/dotnet",
});
}
});
@@ -132,6 +137,45 @@ describe("runtime configuration", () => {
).toBe(false);
});
it("builds a no-network managed runtime ceiling only when enabled", () => {
const result = parseConfig({
REA_MANAGED_RUNTIME_ENABLED: "true",
REA_MANAGED_RUNTIME_ROOTS_JSON: '["/tmp/managed-targets"]',
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: "/opt/dotnet/dotnet",
});
if (!result.ok) throw result.error;
expect(result.value.managedRuntimePolicy).toEqual({
enabled: true,
roots: ["/tmp/managed-targets"],
executablePath: "/opt/dotnet/dotnet",
});
expect(result.value.permissionCeilings).toContainEqual({
capability: "managed_runtime",
roots: ["/tmp/managed-targets"],
executables: ["/opt/dotnet/dotnet"],
environment_names: [],
network: "none",
mount: false,
});
expect(result.value.administratorPermissionGrants).toContainEqual(
expect.objectContaining({
capability: "managed_runtime",
lifetime: "administrator",
}),
);
});
it("rejects relative managed runtime roots and executables", () => {
expect(
parseConfig({ REA_MANAGED_RUNTIME_ROOTS_JSON: '["relative/assembly"]' })
.ok,
).toBe(false);
expect(
parseConfig({ REA_MANAGED_RUNTIME_EXECUTABLE_PATH: "relative/dotnet" })
.ok,
).toBe(false);
});
it("rejects relative Electron file roots", () => {
expect(
parseConfig({ REA_ELECTRON_FILE_ROOTS_JSON: '["relative/app"]' }).ok,
+3 -3
View File
@@ -66,7 +66,7 @@ describe("tool contract surface", () => {
...ELECTRON_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(69);
expect(contracts).toHaveLength(70);
for (const contract of contracts) {
const inputSchema = contractJsonSchema(contract.inputSchema);
const outputSchema = contractJsonSchema(contract.outputSchema);
@@ -164,7 +164,7 @@ describe("tool contract surface", () => {
}
});
it("publishes no unconstrained output-schema holes across all 87 tools", () => {
it("publishes no unconstrained output-schema holes across all 88 tools", () => {
const contracts = [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
@@ -177,7 +177,7 @@ describe("tool contract surface", () => {
...APPLICATION_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(87);
expect(contracts).toHaveLength(88);
for (const contract of contracts) {
const schema = contractJsonSchema(contract.outputSchema);
expect(emptySchemaPaths(schema), contract.name).toEqual([]);
+2 -2
View File
@@ -131,7 +131,7 @@ describe("full MCP integration with multi-tool sequences", () => {
});
});
it("preserves the complete 87-tool inventory with a session", async () => {
it("preserves the complete 88-tool inventory with a session", async () => {
const session = new BinarySession(
(_path) =>
({
@@ -154,7 +154,7 @@ describe("full MCP integration with multi-tool sequences", () => {
await client.connect(clientTransport);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(87);
expect(listed.tools).toHaveLength(88);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
+99 -1
View File
@@ -9,7 +9,9 @@ import { z } from "zod";
import { AnalysisProviderRegistry } from "../src/application/AnalysisProviderRegistry.js";
import { BinarySession } from "../src/application/BinarySession.js";
import { createPermissionAuthority } from "../src/application/PermissionAuthority.js";
import { SessionProviderRouter } from "../src/application/SessionProviderRouter.js";
import type { PermissionCeiling } from "../src/domain/permissionPolicy.js";
import { ManagedStaticProvider } from "../src/dotnet/ManagedStaticProvider.js";
import { createServer } from "../src/server/createServer.js";
import { buildManagedPeFixture } from "./fixtures/managedPe.js";
@@ -19,7 +21,9 @@ describe("managed artifact MCP tools", () => {
const directory = await mkdtemp(join(tmpdir(), "rea-managed-mcp-"));
const path = join(directory, "fixture.exe");
const rightPath = join(directory, "fixture-renamed.exe");
const runtimePath = join(directory, "dotnet");
await writeFile(path, buildManagedPeFixture());
await writeFile(runtimePath, "#!/bin/sh\n");
await writeFile(
rightPath,
buildManagedPeFixture({ methodName: "Renamed" }),
@@ -29,7 +33,43 @@ describe("managed artifact MCP tools", () => {
new ManagedStaticProvider(),
]),
);
const server = createServer(session, session);
const runtimeCeiling: PermissionCeiling = {
capability: "managed_runtime",
roots: [directory],
executables: [runtimePath],
environment_names: [],
network: "none",
mount: false,
};
const authority = await createPermissionAuthority(
[runtimeCeiling],
[
{
...runtimeCeiling,
grant_id: "administrator:managed_runtime",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
},
],
);
if (!authority.ok) throw authority.error;
const server = createServer(session, session, {
permissionAuthority: authority.value,
managedRuntimePolicy: {
enabled: true,
roots: [directory],
executablePath: runtimePath,
},
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
browserObservationEnabled: false,
electronObservationEnabled: false,
javascriptReplayEnabled: false,
managedRuntimeEnabled: true,
}),
});
const client = new Client({ name: "managed-mcp-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
@@ -49,6 +89,9 @@ describe("managed artifact MCP tools", () => {
expect(tools.tools.map(({ name }) => name)).toContain(
"compare_managed_members",
);
expect(tools.tools.map(({ name }) => name)).toContain(
"plan_managed_runtime_correlation",
);
await client.callTool({
name: "open_binary",
@@ -145,6 +188,61 @@ describe("managed artifact MCP tools", () => {
matching: { exact_il_signature: 1 },
},
});
const method = z
.record(z.string(), z.unknown())
.parse(members.normalized_result).methods;
const methodItem = z
.object({
items: z.array(
z.object({
token: z.string(),
signature: z.object({ raw_sha256: z.string() }),
body: z.object({ normalized_il_sha256: z.string().nullable() }),
}),
),
})
.parse(method).items[0];
expect(methodItem).toBeDefined();
if (methodItem === undefined) return;
const planned = structured(
await client.callTool({
name: "plan_managed_runtime_correlation",
arguments: {
static_members: members,
method: {
token: methodItem.token,
signature_sha256: methodItem.signature.raw_sha256,
normalized_il_sha256: methodItem.body.normalized_il_sha256,
},
requested_effect: "attach",
host: {
os: "linux",
clr_family: "dotnet",
architecture: "x86_64",
},
bounds: {
timeout_ms: 5000,
max_threads: 32,
max_output_bytes: 65536,
allow_network: false,
allow_ui: false,
},
},
}),
);
expect(planned).toMatchObject({
operation: "plan_managed_runtime_correlation",
provider: { id: "rea-dotnet-workflows" },
confidence: "derived",
normalized_result: {
executed: false,
authority_model: { capability: "managed_runtime" },
requested_runtime: { effect: "attach", network: "none" },
effect_taxonomy: { attaches_process: true },
},
});
} finally {
await Promise.all([client.close(), server.close()]);
await session.close();
+238
View File
@@ -0,0 +1,238 @@
import { createHash } from "node:crypto";
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
planManagedRuntimeCorrelationEvidence,
type ManagedRuntimePolicy,
} from "../src/application/ManagedRuntimeCorrelationService.js";
import { MANAGED_STATIC_PROVIDER } from "../src/application/InvestigationProviders.js";
import { createPermissionAuthority } from "../src/application/PermissionAuthority.js";
import { createEvidence } from "../src/domain/evidence.js";
import { managedRuntimeCorrelationResultSchema } from "../src/domain/managedRuntimeCorrelation.js";
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
import type { PermissionCeiling } from "../src/domain/permissionPolicy.js";
import { inspectManagedMembersBytes } from "../src/dotnet/ManagedMemberInspector.js";
import { buildManagedPeFixture } from "./fixtures/managedPe.js";
const memberLimits = {
typeOffset: 0,
typeLimit: 100,
methodOffset: 0,
methodLimit: 100,
fieldOffset: 0,
fieldLimit: 100,
memberRefOffset: 0,
memberRefLimit: 100,
edgeOffset: 0,
edgeLimit: 100,
instructionAnchorLimit: 100,
maxMetadataBytes: 1024 * 1024,
maxTableRows: 1_000,
maxHeapItemBytes: 1024 * 1024,
maxMethodBodyBytes: 1024 * 1024,
maxMethodInstructions: 1_000,
};
describe("managed runtime correlation planning", () => {
it("fails closed while the managed runtime authority is disabled", async () => {
const fixture = inspect(buildManagedPeFixture(), "/tmp/disabled.dll");
const result = await planManagedRuntimeCorrelationEvidence(
{
policy: disabledPolicy,
authority: undefined,
},
inputFor(fixture.evidence, fixture.method),
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error._tag).toBe("AnalysisCapabilityUnavailableError");
});
it("requires an explicit managed_runtime grant under an enabled ceiling", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-managed-runtime-"));
const artifactPath = join(directory, "fixture.dll");
const executablePath = join(directory, "dotnet");
await writeFile(artifactPath, buildManagedPeFixture());
await writeFile(executablePath, "#!/bin/sh\n");
const fixture = inspect(buildManagedPeFixture(), artifactPath);
const authority = await authorityFor(directory, executablePath, false);
const result = await planManagedRuntimeCorrelationEvidence(
{
policy: { enabled: true, roots: [directory], executablePath },
authority,
},
inputFor(fixture.evidence, fixture.method),
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error._tag).toBe("PermissionRequiredError");
});
it("records an exact-build non-executing admission plan when authorized", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-managed-runtime-"));
const artifactPath = join(directory, "fixture.dll");
const executablePath = join(directory, "dotnet");
await writeFile(artifactPath, buildManagedPeFixture());
await writeFile(executablePath, "#!/bin/sh\n");
const fixture = inspect(buildManagedPeFixture(), artifactPath);
const policy = { enabled: true, roots: [directory], executablePath };
const authority = await authorityFor(directory, executablePath, true);
const result = await planManagedRuntimeCorrelationEvidence(
{ policy, authority },
inputFor(fixture.evidence, fixture.method),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.operation).toBe("plan_managed_runtime_correlation");
expect(result.value.confidence).toBe("derived");
expect(result.value.authority).toBe("analyst-inference");
const plan = managedRuntimeCorrelationResultSchema.parse(
result.value.normalized_result,
);
expect(plan).toMatchObject({
executed: false,
authority_model: {
capability: "managed_runtime",
default_enabled: false,
per_call_approval_required: true,
},
method_lock: {
token: "0x06000001",
exact_build_required: true,
},
requested_runtime: {
effect: "instrumentation",
executable_path: executablePath,
network: "none",
},
effect_taxonomy: {
instruments_code: true,
invokes_target_code: false,
},
unsupported_until_executor_exists: true,
});
});
it("rejects a method lock that no longer matches static Evidence", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-managed-runtime-"));
const artifactPath = join(directory, "fixture.dll");
const executablePath = join(directory, "dotnet");
await writeFile(artifactPath, buildManagedPeFixture());
await writeFile(executablePath, "#!/bin/sh\n");
const fixture = inspect(buildManagedPeFixture(), artifactPath);
const authority = await authorityFor(directory, executablePath, true);
const result = await planManagedRuntimeCorrelationEvidence(
{
policy: { enabled: true, roots: [directory], executablePath },
authority,
},
{
...inputFor(fixture.evidence, fixture.method),
method: {
...inputFor(fixture.evidence, fixture.method).method,
normalized_il_sha256: "0".repeat(64),
},
},
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error._tag).toBe("AnalysisInputError");
});
});
const disabledPolicy: ManagedRuntimePolicy = {
enabled: false,
roots: [],
executablePath: "/usr/bin/dotnet",
};
const authorityFor = async (
root: string,
executablePath: string,
granted: boolean,
) => {
const ceiling: PermissionCeiling = {
capability: "managed_runtime",
roots: [root],
executables: [executablePath],
environment_names: [],
network: "none",
mount: false,
};
const authority = await createPermissionAuthority(
[ceiling],
granted
? [
{
...ceiling,
grant_id: "administrator:managed_runtime",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
},
]
: [],
);
if (!authority.ok) throw authority.error;
return authority.value;
};
const inputFor = (
staticMembers: ReturnType<typeof createEvidence>,
method: ReturnType<typeof inspect>["method"],
) => ({
static_members: staticMembers,
method: {
token: method.token,
signature_sha256: method.signature.raw_sha256,
normalized_il_sha256: method.body.normalized_il_sha256,
},
requested_effect: "instrumentation" as const,
host: {
os: "linux" as const,
clr_family: "dotnet" as const,
architecture: "x86_64" as const,
},
bounds: {
timeout_ms: 5_000,
max_threads: 32,
max_output_bytes: 65_536,
allow_network: false as const,
allow_ui: false as const,
},
});
const inspect = (bytes: Buffer, path: string) => {
const target: BinaryTarget = {
path,
sha256: hash(bytes),
kind: "executable",
format: "pe",
architecture: "x86",
};
const result = inspectManagedMembersBytes(bytes, target, memberLimits);
const method = result.methods.items[0];
if (method === undefined) throw new Error("fixture has no method");
return {
result,
method,
evidence: createEvidence(target, MANAGED_STATIC_PROVIDER, {
operation: "inspect_managed_members",
parameters: {},
result,
rawResult: null,
limitations: result.limitations,
}),
};
};
const hash = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
+1 -1
View File
@@ -117,7 +117,7 @@ describe("canonical product catalog", () => {
expect(
catalog.providers.find(({ id }) => id === MANAGED_WORKFLOW_PROVIDER.id)
?.capabilities,
).toEqual(["compare_managed_members"]);
).toEqual(["compare_managed_members", "plan_managed_runtime_correlation"]);
expect(
z.toJSONSchema(analysisSnapshotSchema).properties?.snapshot_version,
).toMatchObject({
+1 -1
View File
@@ -54,7 +54,7 @@ describe("guided prompts over MCP", () => {
),
);
}
expect((await client.listTools()).tools).toHaveLength(87);
expect((await client.listTools()).tools).toHaveLength(88);
const result = await client.getPrompt({
name: "investigate_feature",
arguments: {
+3 -3
View File
@@ -10,7 +10,7 @@ const fixturePath = fileURLToPath(
);
describe("production stdio runtime", () => {
it("starts the built entrypoint, lists 87 tools, calls one, and shuts down", async () => {
it("starts the built entrypoint, lists 88 tools, calls one, and shuts down", async () => {
const transport = new StdioClientTransport({
command: process.execPath,
args: [mainPath],
@@ -32,7 +32,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
const tools = await client.listTools();
expect(tools.tools).toHaveLength(87);
expect(tools.tools).toHaveLength(88);
const result = await client.callTool({
name: "current_document",
arguments: {},
@@ -78,7 +78,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
expect((await client.listTools()).tools).toHaveLength(87);
expect((await client.listTools()).tools).toHaveLength(88);
} finally {
await client.close();
await transport.close();
+5 -5
View File
@@ -24,11 +24,11 @@ describe("server and catalog identity", () => {
});
expect(PRODUCT_IDENTITY.packageVersion).toBe(packageJson.version);
expect(SDK_IDENTITY.server).toBe("2.0.0-beta.4");
expect(CLI_COMMAND_NAMES).toHaveLength(47);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(47);
expect(CLI_COMMAND_NAMES).toHaveLength(48);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(48);
expect(CATALOG_IDENTITY.counts).toEqual({
cli_commands: 47,
mcp_tools: 87,
cli_commands: 48,
mcp_tools: 88,
mcp_prompts: 6,
mcp_resources: 2,
mcp_resource_templates: 7,
@@ -162,7 +162,7 @@ describe("server and catalog identity", () => {
expect(status.structuredContent).toMatchObject({
result: {
server_identity: {
catalog: { counts: { mcp_tools: 87, cli_commands: 47 } },
catalog: { counts: { mcp_tools: 88, cli_commands: 48 } },
alignment: { state: "mcp_server_restart_required" },
},
tool_availability: expect.arrayContaining([
+1 -1
View File
@@ -142,7 +142,7 @@ describe("target-free MCP lifecycle", () => {
expect(text(before)).toBe(
"No app is open. Ask the user which app to investigate, then call open_binary with its local path.",
);
expect((await mcp.listTools()).tools).toHaveLength(87);
expect((await mcp.listTools()).tools).toHaveLength(88);
const deniedCapture = await mcp.callTool({
name: "capture_process_scenario",
arguments: {
+4 -3
View File
@@ -15,7 +15,7 @@ import { ELECTRON_TOOL_CONTRACTS } from "../src/contracts/electronToolContracts.
import { APPLICATION_TOOL_CONTRACTS } from "../src/contracts/applicationToolContracts.js";
describe("tool contract inventory", () => {
it("publishes 69 analysis contracts and eighteen session tools", () => {
it("publishes 70 analysis contracts and eighteen session tools", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(33);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(10);
expect(NATIVE_TOOL_CONTRACTS).toHaveLength(5);
@@ -27,6 +27,7 @@ describe("tool contract inventory", () => {
]);
expect(MANAGED_WORKFLOW_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"compare_managed_members",
"plan_managed_runtime_correlation",
]);
expect(BROWSER_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"list_browser_targets",
@@ -69,8 +70,8 @@ describe("tool contract inventory", () => {
"update_unknown",
"verify_unknown_resolution",
]);
expect(TOOL_CONTRACTS).toHaveLength(87);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(87);
expect(TOOL_CONTRACTS).toHaveLength(88);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(88);
});
it("retains documented enhanced-tool limits at the input boundary", () => {