feat(permissions): add scoped process capture elicitation
This commit is contained in:
@@ -0,0 +1,230 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
acceptedContent,
|
||||
inputRequired,
|
||||
inputResponse,
|
||||
type InputRequiredResult,
|
||||
type RequestStateCodec,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import { PermissionRequiredError } from "../domain/errors.js";
|
||||
import {
|
||||
isPermissionRequestWithinCeiling,
|
||||
type PermissionGrant,
|
||||
type PermissionRequest,
|
||||
} from "../domain/permissionPolicy.js";
|
||||
|
||||
const RESPONSE_KEY = "process_capture_grant";
|
||||
const STATE_VERSION = 1;
|
||||
const STATE_TTL_MS = 600_000;
|
||||
const MAX_CONSUMED_NONCES = 4_096;
|
||||
|
||||
const grantResponseSchema = z.object({
|
||||
lifetime: z.enum(["once", "session"]).default("session"),
|
||||
});
|
||||
|
||||
const grantResponseJsonSchema = {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
lifetime: {
|
||||
type: "string" as const,
|
||||
enum: ["once", "session"],
|
||||
default: "session",
|
||||
},
|
||||
},
|
||||
required: ["lifetime"],
|
||||
};
|
||||
|
||||
const stateSchema = z.object({
|
||||
version: z.literal(STATE_VERSION),
|
||||
nonce: z.string().uuid(),
|
||||
request: z.object({
|
||||
capability: z.literal("process_capture"),
|
||||
roots: z.array(z.string()),
|
||||
executables: z.array(z.string()),
|
||||
environment_names: z.array(z.string()),
|
||||
origins: z.array(z.string()).optional(),
|
||||
network: z.enum(["none", "loopback", "external"]),
|
||||
mount: z.boolean(),
|
||||
operation_identity: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type ProcessCaptureElicitationState = z.infer<typeof stateSchema>;
|
||||
|
||||
/** Connection-owned SDK state used for process-capture grant elicitation. */
|
||||
export interface ProcessCaptureElicitation {
|
||||
readonly stateCodec: RequestStateCodec<ProcessCaptureElicitationState>;
|
||||
readonly supported: () => boolean;
|
||||
readonly modern: () => boolean;
|
||||
readonly consumedNonces: Map<string, number>;
|
||||
}
|
||||
|
||||
interface ProcessCaptureElicitationContext {
|
||||
readonly mcpReq: {
|
||||
readonly inputResponses?: Record<string, unknown>;
|
||||
readonly requestState: () => unknown;
|
||||
};
|
||||
}
|
||||
|
||||
type PermissionResult = Awaited<ReturnType<PermissionAuthority["authorize"]>>;
|
||||
|
||||
/** Authorize capture or return a signed MCP input-required continuation. */
|
||||
export const authorizeProcessCaptureWithElicitation = async (
|
||||
authority: PermissionAuthority,
|
||||
request: PermissionRequest,
|
||||
context: ProcessCaptureElicitationContext,
|
||||
elicitation: ProcessCaptureElicitation,
|
||||
): Promise<PermissionResult | InputRequiredResult> => {
|
||||
const supported = elicitation.supported() && elicitation.modern();
|
||||
const initial = await authority.authorize(request, "read", {
|
||||
elicitationSupported: supported,
|
||||
});
|
||||
if (initial.ok || !(initial.error instanceof PermissionRequiredError))
|
||||
return initial;
|
||||
const denied = initial.error;
|
||||
if (
|
||||
!supported ||
|
||||
denied.requested.capability !== "process_capture" ||
|
||||
denied.ceiling === null ||
|
||||
!isPermissionRequestWithinCeiling(denied.requested, denied.ceiling)
|
||||
)
|
||||
return initial;
|
||||
|
||||
const encodedState = context.mcpReq.requestState();
|
||||
if (encodedState !== undefined) {
|
||||
const state = stateSchema.safeParse(encodedState);
|
||||
if (!state.success || !sameRequest(state.data.request, denied.requested))
|
||||
return initial;
|
||||
const response = inputResponse(context.mcpReq.inputResponses, RESPONSE_KEY);
|
||||
if (response.kind === "elicit") {
|
||||
if (!consumeNonce(elicitation.consumedNonces, state.data.nonce))
|
||||
return initial;
|
||||
}
|
||||
if (response.kind === "elicit" && response.action === "accept") {
|
||||
const content = acceptedContent(
|
||||
context.mcpReq.inputResponses,
|
||||
RESPONSE_KEY,
|
||||
grantResponseSchema,
|
||||
);
|
||||
if (content === undefined) return initial;
|
||||
return grantAndAuthorize(authority, state.data.request, content.lifetime);
|
||||
}
|
||||
if (
|
||||
response.kind === "elicit" &&
|
||||
(response.action === "decline" || response.action === "cancel")
|
||||
)
|
||||
return initial;
|
||||
}
|
||||
|
||||
const state = await elicitation.stateCodec.mint({
|
||||
version: STATE_VERSION,
|
||||
nonce: randomUUID(),
|
||||
request: {
|
||||
capability: "process_capture",
|
||||
roots: [...denied.requested.roots],
|
||||
executables: [...denied.requested.executables],
|
||||
environment_names: [...denied.requested.environment_names],
|
||||
network: denied.requested.network,
|
||||
mount: denied.requested.mount,
|
||||
operation_identity: denied.requested.operation_identity,
|
||||
...(denied.requested.origins === undefined
|
||||
? {}
|
||||
: { origins: [...denied.requested.origins] }),
|
||||
},
|
||||
});
|
||||
return inputRequired({
|
||||
inputRequests: {
|
||||
[RESPONSE_KEY]: inputRequired.elicit({
|
||||
message: permissionMessage(denied.requested),
|
||||
requestedSchema: grantResponseJsonSchema,
|
||||
}),
|
||||
},
|
||||
requestState: state,
|
||||
});
|
||||
};
|
||||
|
||||
const grantAndAuthorize = async (
|
||||
authority: PermissionAuthority,
|
||||
request: PermissionRequest,
|
||||
lifetime: "once" | "session",
|
||||
): Promise<PermissionResult> => {
|
||||
const grant: PermissionGrant = {
|
||||
...request,
|
||||
grant_id: `elicited:${randomUUID()}`,
|
||||
lifetime,
|
||||
operation_identity: lifetime === "once" ? request.operation_identity : null,
|
||||
expires_at: null,
|
||||
};
|
||||
const granted = authority.grant(grant);
|
||||
if (!granted.ok)
|
||||
return authority.authorize(request, "read", {
|
||||
elicitationSupported: true,
|
||||
});
|
||||
let authorized: PermissionResult;
|
||||
try {
|
||||
authorized = await authority.authorize(request, "read", {
|
||||
elicitationSupported: true,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
authority.revoke(grant.grant_id);
|
||||
throw cause;
|
||||
}
|
||||
if (!authorized.ok) authority.revoke(grant.grant_id);
|
||||
return authorized;
|
||||
};
|
||||
|
||||
const sameRequest = (
|
||||
left: PermissionRequest,
|
||||
right: PermissionRequest,
|
||||
): boolean =>
|
||||
left.capability === right.capability &&
|
||||
left.network === right.network &&
|
||||
left.mount === right.mount &&
|
||||
left.operation_identity === right.operation_identity &&
|
||||
sameOptionalStrings(left.origins, right.origins) &&
|
||||
sameStrings(left.roots, right.roots) &&
|
||||
sameStrings(left.executables, right.executables) &&
|
||||
sameStrings(left.environment_names, right.environment_names);
|
||||
|
||||
const sameStrings = (
|
||||
left: readonly string[],
|
||||
right: readonly string[],
|
||||
): boolean =>
|
||||
left.length === right.length &&
|
||||
left.every((value, index) => value === right[index]);
|
||||
|
||||
const sameOptionalStrings = (
|
||||
left: readonly string[] | undefined,
|
||||
right: readonly string[] | undefined,
|
||||
): boolean =>
|
||||
left === undefined
|
||||
? right === undefined
|
||||
: right !== undefined && sameStrings(left, right);
|
||||
|
||||
const consumeNonce = (
|
||||
consumed: Map<string, number>,
|
||||
nonce: string,
|
||||
): boolean => {
|
||||
const now = Date.now();
|
||||
for (const [candidate, expiresAt] of consumed)
|
||||
if (expiresAt <= now) consumed.delete(candidate);
|
||||
if (consumed.has(nonce) || consumed.size >= MAX_CONSUMED_NONCES) return false;
|
||||
consumed.set(nonce, now + STATE_TTL_MS);
|
||||
return true;
|
||||
};
|
||||
|
||||
const permissionMessage = (request: PermissionRequest): string =>
|
||||
[
|
||||
"Allow REA to run this exact process-capture scope?",
|
||||
`Executable: ${request.executables.join(", ") || "none"}`,
|
||||
`Filesystem roots: ${request.roots.join(", ") || "none"}`,
|
||||
`Environment names: ${request.environment_names.join(", ") || "none"}`,
|
||||
`Origins: ${request.origins?.join(", ") || "none"}`,
|
||||
`Network: ${request.network}`,
|
||||
`Mount access: ${request.mount ? "yes" : "no"}`,
|
||||
"Choose whether the grant applies once or for this MCP session.",
|
||||
].join("\n");
|
||||
@@ -1,4 +1,9 @@
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
import {
|
||||
createRequestStateCodec,
|
||||
McpServer,
|
||||
} from "@modelcontextprotocol/server";
|
||||
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
@@ -30,6 +35,7 @@ import type {
|
||||
import type { ManagedRuntimePolicy } from "../application/ManagedRuntimeCorrelationService.js";
|
||||
import { LinuxJavaScriptReplayRunner } from "../replay/LinuxJavaScriptReplayRunner.js";
|
||||
import { SystemJavaScriptReplayHost } from "../replay/SystemJavaScriptReplayHost.js";
|
||||
import type { ProcessCaptureElicitationState } from "./ProcessCaptureElicitation.js";
|
||||
|
||||
export interface CreateServerOptions {
|
||||
readonly logger?: Logger;
|
||||
@@ -67,6 +73,13 @@ export const createServer = (
|
||||
): McpServer => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const logger = options.logger ?? silentLogger;
|
||||
const permissionAuthority =
|
||||
options.permissionAuthority?.createConnectionAuthority();
|
||||
const processCaptureStateCodec =
|
||||
createRequestStateCodec<ProcessCaptureElicitationState>({
|
||||
key: randomBytes(32),
|
||||
ttlSeconds: 600,
|
||||
});
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: PRODUCT_IDENTITY.mcpServerKey,
|
||||
@@ -77,12 +90,17 @@ export const createServer = (
|
||||
tools: { listChanged: true },
|
||||
resources: { listChanged: true },
|
||||
},
|
||||
inputRequired: { maxRounds: 3, roundTimeoutMs: 600_000 },
|
||||
requestState: { verify: processCaptureStateCodec.verify },
|
||||
instructions:
|
||||
session === undefined
|
||||
? "Reverse-engineering tools for an active analysis target. Start with binary_overview."
|
||||
: "Reverse-engineering tools for configured analysis providers. Open a target with open_binary, then start with binary_overview.",
|
||||
},
|
||||
);
|
||||
server.server.onclose = () => {
|
||||
permissionAuthority?.clearSessionGrants();
|
||||
};
|
||||
session?.onAvailabilityChanged?.(() => server.sendToolListChanged());
|
||||
server.registerResource(
|
||||
"server-identity",
|
||||
@@ -170,9 +188,7 @@ export const createServer = (
|
||||
logger: toolLogger,
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
...(options.permissionAuthority === undefined
|
||||
? {}
|
||||
: { permissionAuthority: options.permissionAuthority }),
|
||||
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
|
||||
});
|
||||
registerManagedTools(server, analysis, {
|
||||
logger: toolLogger,
|
||||
@@ -191,19 +207,19 @@ export const createServer = (
|
||||
roots: [],
|
||||
executablePath: "/usr/bin/dotnet",
|
||||
},
|
||||
authority: options.permissionAuthority,
|
||||
authority: permissionAuthority,
|
||||
},
|
||||
});
|
||||
registerBrowserTools(server, {
|
||||
logger: toolLogger,
|
||||
browser: options.browserObservation,
|
||||
permissionAuthority: options.permissionAuthority,
|
||||
permissionAuthority,
|
||||
recordEvidence,
|
||||
});
|
||||
registerElectronTools(server, {
|
||||
logger: toolLogger,
|
||||
electron: options.electronObservation,
|
||||
permissionAuthority: options.permissionAuthority,
|
||||
permissionAuthority,
|
||||
recordEvidence,
|
||||
});
|
||||
registerApplicationTools(server, {
|
||||
@@ -217,7 +233,7 @@ export const createServer = (
|
||||
maxStringLength: 1,
|
||||
maxNodes: 1,
|
||||
},
|
||||
permissionAuthority: options.permissionAuthority,
|
||||
permissionAuthority,
|
||||
retainCoverageWorkspace:
|
||||
session === undefined
|
||||
? undefined
|
||||
@@ -240,7 +256,7 @@ export const createServer = (
|
||||
host: options.javascriptReplayHost ?? new SystemJavaScriptReplayHost(),
|
||||
runner:
|
||||
options.javascriptReplayRunner ?? new LinuxJavaScriptReplayRunner(),
|
||||
authority: options.permissionAuthority,
|
||||
authority: permissionAuthority,
|
||||
},
|
||||
});
|
||||
registerGuidedPrompts(server, analysis, session);
|
||||
@@ -248,7 +264,18 @@ export const createServer = (
|
||||
registerEvidenceResources(server, session);
|
||||
registerSessionTools(server, session, toolLogger, {
|
||||
...options,
|
||||
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
|
||||
startedAt,
|
||||
processCaptureElicitation: {
|
||||
stateCodec: processCaptureStateCodec,
|
||||
supported: () =>
|
||||
server.server.getClientCapabilities()?.elicitation?.form !==
|
||||
undefined,
|
||||
modern: () =>
|
||||
server.server.getNegotiatedProtocolVersion()?.startsWith("2026-") ===
|
||||
true,
|
||||
consumedNonces: new Map(),
|
||||
},
|
||||
});
|
||||
}
|
||||
return server;
|
||||
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
} from "../domain/processCapture.js";
|
||||
import { processScenarioSchema } from "../domain/processCapture.js";
|
||||
import { captureProcessScenario } from "../application/ProcessHarness.js";
|
||||
import { processCapturePermissionRequest } from "../application/ProcessCapturePermission.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import {
|
||||
@@ -60,6 +61,11 @@ import {
|
||||
import { registerSessionStatusTool } from "./registerSessionStatusTool.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import {
|
||||
authorizeProcessCaptureWithElicitation,
|
||||
type ProcessCaptureElicitation,
|
||||
} from "./ProcessCaptureElicitation.js";
|
||||
import { isInputRequiredResult } from "@modelcontextprotocol/server";
|
||||
|
||||
const permissionFailure = (
|
||||
failure: Awaited<ReturnType<PermissionAuthority["authorize"]>>,
|
||||
@@ -121,6 +127,7 @@ interface ProcessToolRegistration {
|
||||
readonly processPolicy: ProcessExecutionPolicy;
|
||||
readonly captureContract: (typeof SESSION_TOOL_CONTRACTS)[5];
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
readonly processCaptureElicitation?: ProcessCaptureElicitation;
|
||||
readonly availabilityPolicy?: () => {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
@@ -134,6 +141,7 @@ const registerProcessTools = ({
|
||||
processPolicy,
|
||||
captureContract,
|
||||
permissionAuthority,
|
||||
processCaptureElicitation,
|
||||
}: ProcessToolRegistration): void => {
|
||||
server.registerTool(
|
||||
captureContract.name,
|
||||
@@ -148,21 +156,17 @@ const registerProcessTools = ({
|
||||
return toCallToolResult(parsedInput, captureContract);
|
||||
const scenario = parsedInput.value;
|
||||
if (permissionAuthority !== undefined) {
|
||||
const authorized = await permissionAuthority.authorize(
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: [scenario.working_directory, ...scenario.filesystem_roots],
|
||||
executables: [scenario.executable],
|
||||
environment_names: [
|
||||
...Object.keys(scenario.environment),
|
||||
...scenario.inherit_environment,
|
||||
],
|
||||
network: scenario.network_access === "host" ? "external" : "none",
|
||||
mount: false,
|
||||
operation_identity: `capture_process_scenario:${scenario.executable}`,
|
||||
},
|
||||
"read",
|
||||
);
|
||||
const request = processCapturePermissionRequest(scenario);
|
||||
const authorized =
|
||||
processCaptureElicitation === undefined
|
||||
? await permissionAuthority.authorize(request, "read")
|
||||
: await authorizeProcessCaptureWithElicitation(
|
||||
permissionAuthority,
|
||||
request,
|
||||
context,
|
||||
processCaptureElicitation,
|
||||
);
|
||||
if (isInputRequiredResult(authorized)) return authorized;
|
||||
if (!authorized.ok)
|
||||
return toCallToolResult(
|
||||
permissionFailure(authorized),
|
||||
@@ -595,6 +599,7 @@ export interface SessionToolOptions {
|
||||
readonly analysisSnapshotFilePolicy?: EvidenceFilePolicy;
|
||||
readonly startedAt?: string;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
readonly processCaptureElicitation?: ProcessCaptureElicitation;
|
||||
readonly artifactIntegrityContinueEnabled?: () => boolean;
|
||||
readonly availabilityPolicy?: () => {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
@@ -677,6 +682,9 @@ export const registerSessionTools = (
|
||||
...(options.permissionAuthority === undefined
|
||||
? {}
|
||||
: { permissionAuthority: options.permissionAuthority }),
|
||||
...(options.processCaptureElicitation === undefined
|
||||
? {}
|
||||
: { processCaptureElicitation: options.processCaptureElicitation }),
|
||||
});
|
||||
registerProcessComparisonTool(server, session, compareContract);
|
||||
registerArtifactComparisonTool(server, session, compareArtifactsContract);
|
||||
|
||||
Reference in New Issue
Block a user