From 43fe059944095389414252baf43ae9609a365304 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sun, 29 Nov 2026 11:56:45 +0900 Subject: [PATCH] Fix security finding acf_bfb52d2e6823fd40297687a78192a08a --- .../docs/reference/configuration/advisor.md | 2 +- src/advisor/client-mcp.ts | 6 +-- src/advisor/external-consult.ts | 11 ++++- src/advisor/mcp-server.ts | 13 +++--- structure/advisor.md | 2 + .../advisor/advisor-client-mcp-safety.test.ts | 42 +++++++++++++++++++ 6 files changed, 65 insertions(+), 11 deletions(-) diff --git a/docs-site/src/content/docs/reference/configuration/advisor.md b/docs-site/src/content/docs/reference/configuration/advisor.md index 613db5963c2..d7fbc623031 100644 --- a/docs-site/src/content/docs/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/reference/configuration/advisor.md @@ -18,7 +18,7 @@ never sees — even a worker that never spawns anything can be advised. `autoMountMcp` defaults to `false`. Enable it with `ocx advisor set --auto-mount-mcp on` to follow compatible active routes, or choose explicit clients with `--mcp-clients `; `auto` clears the explicit list and `none` selects no clients. External clients can use the `consult_advisor` MCP tool served by `ocx advisor mcp`, or start a consultation with `ocx advisor consult --question "..."` and poll it with `ocx advisor consult --consultation-id `. Current context-sharing consent is required. -`context` is the default bounded context, `question-only` sends the question only and pauses automatic consultations, and `full` uses expanded bounds and can attach a matching local transcript when a session or task ID or permitted transcript path is supplied. Transcript text and tool results may be sent to the configured Advisor provider. A transcript is not guaranteed to be found. +`context` is the default bounded context, `question-only` sends the question only and pauses automatic consultations, and `full` uses expanded bounds. Operator-invoked CLI/API consultations can attach a matching local transcript when a session or task ID or permitted transcript path is supplied. MCP-provided session and task IDs scope adaptive consultation budgets only and never select local transcripts; MCP callers must provide relevant material explicitly in `context`. Attached transcript text and tool results may be sent to the configured Advisor provider. A transcript is not guaranteed to be found. `timeoutMs` is an inactivity timeout: response data resets it. A separate hard ceiling is `max(4 × timeoutMs, 600000 ms)`; the default is 600000 ms and the maximum configurable inactivity timeout is 1800000 ms. diff --git a/src/advisor/client-mcp.ts b/src/advisor/client-mcp.ts index 96613325f65..418f1921957 100644 --- a/src/advisor/client-mcp.ts +++ b/src/advisor/client-mcp.ts @@ -525,9 +525,9 @@ cat <<'EOF' Consult it PROACTIVELY (not only when asked) before committing to a complex/high-risk architecture design, after 2 failed repair attempts on the same issue, or for final verification. If MCP lazy-loading is active, use \`mcp_get\` / \`mcp_call\` on \`mcp__opencodex_advisor__consult_advisor\` with a focused \`question\` and optional \`context\`. EOF if [ -n "$SESSION_ID" ]; then - printf 'Pass sessionId="%s" when available. In full-context mode, OpenCodex may attach a matching local session transcript if found. ' "$SESSION_ID" + printf 'Pass sessionId="%s" when available to scope adaptive consultation budgets. Include relevant task material explicitly in context. ' "$SESSION_ID" else - printf 'In full-context mode, OpenCodex may attach a matching local session transcript when a session or task ID is available. ' + printf 'Include relevant task material explicitly in context. MCP-provided session and task IDs never select local transcripts. ' fi cat <<'EOF' If it returns status="in_progress" with nextCallArguments ({ "consultationId": "...", "afterElapsedMs": }), immediately call it again with nextCallArguments to keep waiting cleanly until finished. @@ -553,7 +553,7 @@ You have access to the stronger OpenCodex Advisor model via \`consult_advisor\` ## How to invoke - Direct MCP clients: call \`consult_advisor({ question, context?, sessionId? })\`. - Lazy-loading MCP clients (e.g. Qoder): call \`mcp_get({ toolName: "mcp__opencodex_advisor__consult_advisor" })\` or \`mcp_call({ toolName: "mcp__opencodex_advisor__consult_advisor", arguments: { question, context?, sessionId? } })\`. -- Pass \`sessionId\` when available. In full-context mode, OpenCodex may attach a matching local session transcript if found. +- Pass \`sessionId\` when available to scope adaptive consultation budgets. MCP-provided session and task IDs never select local transcripts; include relevant task material explicitly in \`context\`. - If the call returns \`status: "in_progress"\` with \`consultationId\` and \`elapsedMs\`, immediately poll again with \`{ "consultationId": "...", "afterElapsedMs": }\` (updating \`afterElapsedMs\` each round avoids duplicate-tool-call guards). `; diff --git a/src/advisor/external-consult.ts b/src/advisor/external-consult.ts index 98a1cb6bcfe..7807c050845 100644 --- a/src/advisor/external-consult.ts +++ b/src/advisor/external-consult.ts @@ -42,6 +42,8 @@ export interface ExternalAdvisorConsultRequest { question?: string; context?: string; workerModel?: string; + /** Stable accounting label only; never used to locate a transcript. */ + budgetId?: string; taskId?: string; sessionId?: string; transcriptPath?: string; @@ -620,6 +622,9 @@ export async function runExternalAdvisorConsult( if (rawBody.workerModel !== undefined && (typeof rawBody.workerModel !== "string" || rawBody.workerModel.trim().length > MAX_WORKER_MODEL_CHARS)) { return errorResponse(400, "invalid_worker_model", "workerModel must be a string of at most 200 characters"); } + if (rawBody.budgetId !== undefined && (typeof rawBody.budgetId !== "string" || rawBody.budgetId.trim().length > MAX_TASK_ID_CHARS)) { + return errorResponse(400, "invalid_budget_id", "budgetId must be a string of at most 256 characters"); + } if (rawBody.taskId !== undefined && (typeof rawBody.taskId !== "string" || rawBody.taskId.trim().length > MAX_TASK_ID_CHARS)) { return errorResponse(400, "invalid_task_id", "taskId must be a string of at most 256 characters"); } @@ -646,6 +651,7 @@ export async function runExternalAdvisorConsult( const rawQuestion = rawBody.question.trim(); const question = rawQuestion.length > MAX_QUESTION_CHARS ? rawQuestion.slice(0, MAX_QUESTION_CHARS) : rawQuestion; const contextText = typeof rawBody.context === "string" ? rawBody.context.trim() : ""; + const budgetId = typeof rawBody.budgetId === "string" ? rawBody.budgetId.trim() : ""; const sessionId = typeof rawBody.sessionId === "string" && rawBody.sessionId.trim() ? rawBody.sessionId.trim() : undefined; const transcriptPath = typeof rawBody.transcriptPath === "string" && rawBody.transcriptPath.trim() ? rawBody.transcriptPath.trim() : undefined; const taskId = typeof rawBody.taskId === "string" ? rawBody.taskId.trim() : ""; @@ -693,6 +699,7 @@ export async function runExternalAdvisorConsult( workerModel, question, contextText, + budgetId, taskId, sessionId ?? "", transcriptPath ?? "", @@ -719,7 +726,7 @@ export async function runExternalAdvisorConsult( ); } - const explicitBudgetId = taskId || sessionId; + const explicitBudgetId = budgetId || taskId || sessionId; let budgetIdentity: string | undefined; if (explicitBudgetId) { budgetIdentity = `external:${explicitBudgetId}`; @@ -747,7 +754,7 @@ export async function runExternalAdvisorConsult( return errorResponse( 400, "advisor_budget_identity_required", - "Adaptive advisor policy requires a stable taskId, sessionId, or validated transcriptPath to enforce the per-task consultation limit.", + "Adaptive advisor policy requires a stable budgetId, taskId, sessionId, or validated transcriptPath to enforce the per-task consultation limit.", formatAdvisorUnavailable("budget", "adaptive policy requires a stable taskId or sessionId; no consultation sent"), ); } diff --git a/src/advisor/mcp-server.ts b/src/advisor/mcp-server.ts index e841f957983..28a73edd36e 100644 --- a/src/advisor/mcp-server.ts +++ b/src/advisor/mcp-server.ts @@ -31,9 +31,9 @@ export function resolveDefaultMcpWaitMs(rawEnv: string | undefined = process.env export const consultAdvisorInput = { question: z.string().max(32_000).optional().describe("Focused engineering question for the advisor model. Required when starting a new consultation."), context: z.string().max(400_000).optional().describe("Optional task background, failing commands/errors, file snippets, or draft notes."), - workerModel: z.string().max(200).optional().describe("Optional caller/worker model identifier (auto-detected from the local session transcript when available)."), - taskId: z.string().max(256).optional().describe("Task or session identifier. Under adaptive policy, taskId or sessionId is required to enforce the per-task consultation limit."), - sessionId: z.string().max(128).optional().describe("Client session UUID so OpenCodex can attach the raw local session transcript and scope adaptive task budgets."), + workerModel: z.string().max(200).optional().describe("Optional caller/worker model identifier."), + taskId: z.string().max(256).optional().describe("Stable task identifier used only to scope the adaptive per-task consultation limit."), + sessionId: z.string().max(128).optional().describe("Client session identifier used only as a fallback scope for adaptive task budgets."), consultationId: z.string().max(128).optional().describe("Resume/poll an in-progress consultation returned by a prior consult_advisor call."), afterElapsedMs: z.number().int().min(0).optional().describe("Elapsed milliseconds from the previous in_progress result when polling so repeated poll calls stay distinct."), }; @@ -88,14 +88,17 @@ export async function callAdvisorConsultApi( }; } const effectiveWaitMs = options.waitMs ?? resolveDefaultMcpWaitMs(); + // Model-controlled identifiers are budget labels, never filesystem authority. In particular, + // do not forward them as sessionId/taskId, which the operator-facing API may use to select a + // local transcript when contextMode is "full". + const budgetId = input.taskId?.trim() || input.sessionId?.trim(); const payload: Record = consultationId ? { consultationId, waitMs: effectiveWaitMs } : { question, ...(input.context?.trim() ? { context: input.context.trim() } : {}), ...(input.workerModel?.trim() ? { workerModel: input.workerModel.trim() } : {}), - ...(input.taskId?.trim() ? { taskId: input.taskId.trim() } : {}), - ...(input.sessionId?.trim() ? { sessionId: input.sessionId.trim() } : {}), + ...(budgetId ? { budgetId } : {}), waitMs: effectiveWaitMs, }; const deadline = new AbortController(); diff --git a/structure/advisor.md b/structure/advisor.md index 0f8d741d037..001e046e0aa 100644 --- a/structure/advisor.md +++ b/structure/advisor.md @@ -522,6 +522,8 @@ API, CLI (`ocx advisor consult`), and stdio MCP (`src/advisor/mcp-server.ts`, `o annotated `readOnlyHint: false, openWorldHint: true`) to stay below the 255s HTTP listener idle timeout; `nextCallArguments` (`{ consultationId, afterElapsedMs }`) accepts any nonnegative integer cursor alongside `notifications/progress` heartbeats. +The MCP bridge maps model-provided `taskId`/`sessionId` values to the budget-only `budgetId` field; +those values never enter transcript discovery, while explicit `context` remains available. Operator-facing CLI/API callers retain explicit transcript selection. The MCP client bounds the local HTTP request and body read to `waitMs` plus one second, combines caller cancellation, and advises polling the same ID after a transport deadline. Advisor CLI settings output reports MCP reconciliation errors separately from mounted-client trust status; JSON retains the management response. The dashboard keeps a failed MCP reconciliation retry available across edits and failed saves, until a response confirms successful reconciliation. diff --git a/tests/advisor/advisor-client-mcp-safety.test.ts b/tests/advisor/advisor-client-mcp-safety.test.ts index 2055c59befa..bb69286a821 100644 --- a/tests/advisor/advisor-client-mcp-safety.test.ts +++ b/tests/advisor/advisor-client-mcp-safety.test.ts @@ -69,6 +69,48 @@ describe("Advisor client MCP safety", () => { expect(cancelled.isError).toBe(true); expect(cancelled.content[0]?.text).not.toContain("timed out"); }); + test("MCP identifiers scope budgets without selecting local transcripts", async () => { + const bodies: Array> = []; + const fetchImpl = (async (_input: RequestInfo | URL, init?: RequestInit) => { + bodies.push(JSON.parse(String(init?.body)) as Record); + return Response.json({ status: "completed", content: "done" }); + }) as typeof fetch; + await callAdvisorConsultApi( + { question: "review", context: "caller context", taskId: "task-file", sessionId: "session-file" }, + { baseUrl: "http://proxy.test", fetchImpl, waitMs: 0 }, + ); + await callAdvisorConsultApi( + { question: "review session", sessionId: "session-file" }, + { baseUrl: "http://proxy.test", fetchImpl, waitMs: 0 }, + ); + expect(bodies).toEqual([ + { question: "review", context: "caller context", budgetId: "task-file", waitMs: 0 }, + { question: "review session", budgetId: "session-file", waitMs: 0 }, + ]); + + const root = tempHome("ocx-advisor-mcp-transcript-boundary-"); + writeFileSync(join(root, "task-file.jsonl"), JSON.stringify({ type: "message", message: { role: "user", content: "victim transcript" } })); + let sentMessages = ""; + const config = { port: 10100, providers: {}, advisor: { + enabled: true, model: "expert/gpt-6-astra", contextSharingConsent: "v1", + contextMode: "full", policy: "adaptive", maxConsultationsPerTask: 3, + } } as unknown as OcxConfig; + const response = await runExternalAdvisorConsult( + config, + bodies[0], + { + workbuddyProjectsDir: root, + consultFn: async input => { + sentMessages = JSON.stringify(input.parsed.context.messages); + return { ok: true, advice: "done", advisorModel: "expert/gpt-6-astra", durationMs: 1 }; + }, + }, + ); + expect(response.status).toBe(200); + expect(sentMessages).toContain("caller context"); + expect(sentMessages).toContain("review"); + expect(sentMessages).not.toContain("victim transcript"); + }); test("transcript selection prefers the session over a newer task fallback and filters direct advisor calls", () => { const root = tempHome("ocx-advisor-transcript-priority-"); writeFileSync(join(root, "session.jsonl"), [