diff --git a/src/ida/IdaDiagnosticRedactor.test.ts b/src/ida/IdaDiagnosticRedactor.test.ts index 272f2a252a7..1574413b506 100644 --- a/src/ida/IdaDiagnosticRedactor.test.ts +++ b/src/ida/IdaDiagnosticRedactor.test.ts @@ -5,6 +5,34 @@ import { } from "./IdaDiagnosticRedactor.js"; describe("IDA diagnostic credential redaction", () => { + it("redacts known URL-encoded credentials while preserving unrelated URL spelling", () => { + const redact = createIdaDiagnosticRedactor({ + url: "http://localhost:1234/mcp", + headers: { Authorization: "Bearer fixture-secret" }, + mode: "attached", + timeoutMs: 1000, + }).url; + expect( + redact("HTTP://localhost:1234/mcp?token=fixture%2Dsecret&cursor=%2Fkeep"), + ).toBe( + "HTTP://localhost:1234/mcp?token=[redacted transport credential]&cursor=%2Fkeep", + ); + }); + + it("maps encoded UTF-8 and query plus signs to their original URL spans", () => { + const redact = createIdaDiagnosticRedactor({ + url: "http://localhost:1234/mcp", + headers: { "X-Private": "café secret" }, + sensitive: { headers: ["X-Private"], env: [] }, + mode: "attached", + timeoutMs: 1000, + }).url; + expect( + redact("http://localhost/mcp?token=caf%C3%A9+secret&cursor=keep"), + ).toBe( + "http://localhost/mcp?token=[redacted transport credential]&cursor=keep", + ); + }); it.each([false, true])( "redacts literal credentials once regardless of header order (reversed: %s)", (reversed) => { diff --git a/src/ida/IdaDiagnosticRedactor.ts b/src/ida/IdaDiagnosticRedactor.ts index e705ce5d4f1..a2954b2fb94 100644 --- a/src/ida/IdaDiagnosticRedactor.ts +++ b/src/ida/IdaDiagnosticRedactor.ts @@ -146,6 +146,7 @@ export const createIdaDiagnosticRedactor = ( config?: IdaConfiguration, ): Readonly<{ text(message: string): string; + url(message: string): string; json(message: string): string; blocks(messages: readonly string[]): string; message(prefix: string, ownedBody: string): string; @@ -215,8 +216,75 @@ export const createIdaDiagnosticRedactor = ( ? message : redactIdaJsonDiagnostic(message, matches, replacement), ); + // A URL may carry the same known credential in percent-encoded form. Map + // decoded characters back to their original spans so unrelated spelling is + // preserved, including mixed encoded and literal characters. + const url = boundedDiagnostic((message) => { + let decoded = ""; + const spans: IdaDiagnosticMatch[] = []; + const query = message.indexOf("?"); + const fragment = message.indexOf("#", query + 1); + for (let index = 0; index < message.length;) { + const first = message.slice(index, index + 3); + const byte = /^%[\dA-Fa-f]{2}$/u.test(first) + ? Number.parseInt(first.slice(1), 16) + : undefined; + const width = + byte === undefined + ? 0 + : byte < 0x80 + ? 1 + : byte >= 0xc2 && byte <= 0xdf + ? 2 + : byte >= 0xe0 && byte <= 0xef + ? 3 + : byte >= 0xf0 && byte <= 0xf4 + ? 4 + : 0; + const encoded = + width === 0 ? undefined : message.slice(index, index + width * 3); + if (encoded !== undefined && /^(?:%[\dA-Fa-f]{2})+$/u.test(encoded)) { + try { + const value = decodeURIComponent(encoded); + let offset = index; + for (const scalar of value) { + const end = offset + Buffer.byteLength(scalar, "utf8") * 3; + decoded += scalar; + for (let unit = 0; unit < scalar.length; unit++) + spans.push({ start: offset, end }); + offset = end; + } + index += encoded.length; + continue; + } catch { + // Invalid percent-encoded UTF-8 has no decoded Unicode identity. + } + } + const scalar = String.fromCodePoint(message.codePointAt(index)!); + const end = index + scalar.length; + decoded += + scalar === "+" && + query >= 0 && + index > query && + (fragment < 0 || index < fragment) + ? " " + : scalar; + for (let unit = 0; unit < scalar.length; unit++) + spans.push({ start: index, end }); + index = end; + } + const decodedSpans = [...matches(decoded)].map((match) => ({ + start: spans[match.start]!.start, + end: spans[match.end - 1]!.end, + })); + const all = [...matches(message), ...decodedSpans].sort( + (left, right) => left.start - right.start || left.end - right.end, + ); + return writeIdaDiagnostic(message, all, replacement); + }); return { text, + url, json, blocks(messages) { let bytes = 0; diff --git a/src/ida/IdaSessionClient.test.ts b/src/ida/IdaSessionClient.test.ts index 5d713c290fd..f3ac679990c 100644 --- a/src/ida/IdaSessionClient.test.ts +++ b/src/ida/IdaSessionClient.test.ts @@ -95,6 +95,84 @@ const fixture = async ( return { root, target, producer, client }; }; +it.each([ + new Error("HTTP 404: fixture response"), + new ProviderAdapterError("ida", "transport", { + diagnostics: { reason: "fixture response" }, + }), + new AnalysisTimeoutError("ida_mcp_connect", 1000), + new AnalysisProtocolError("Malformed MCP response"), + new AnalysisResourceConstraintError( + "ida_mcp_connect", + "transport", + "fixture limit", + { max_response_bytes: 1 }, + ), +])( + "retains the selected HTTP endpoint on a connection failure", + async (cause) => { + const { root, target } = await createIdaTarget(); + roots.push(root); + const producer = new RecordingIdaMcp(target, "attached"); + vi.spyOn(producer, "connect").mockRejectedValue(cause); + const selected = "HTTP://LOCALHOST:01234/mcp?cursor=kept"; + const client = new IdaSessionClient( + { + url: selected, + headers: { Authorization: "Bearer fixture-secret" }, + mode: "attached", + timeoutMs: 1000, + }, + target, + producer, + ); + const result = await client.execute("list_procedures", {}); + expect(result.ok).toBe(false); + if (result.ok) throw new Error("Expected connection failure"); + expect(result.error.diagnostics).toMatchObject({ endpoint: selected }); + expect(JSON.stringify(projectAnalysisError(result.error))).not.toContain( + "fixture-secret", + ); + await client.close(); + }, +); + +it.each([ + "fixture-secret", + "fixture%2Dsecret", + "fixture%2dsecret", + "%66%69%78%74%75%72%65-secret", +])( + "redacts a known transport credential in the selected endpoint: %s", + async (encoded) => { + const { root, target } = await createIdaTarget(); + roots.push(root); + const producer = new RecordingIdaMcp(target, "attached"); + vi.spyOn(producer, "connect").mockRejectedValue( + new Error("fixture failure"), + ); + const client = new IdaSessionClient( + { + url: `http://localhost:1234/mcp?token=${encoded}&cursor=keep`, + headers: { Authorization: "Bearer fixture-secret" }, + mode: "attached", + timeoutMs: 1000, + }, + target, + producer, + ); + const result = await client.execute("list_procedures", {}); + expect(result.ok).toBe(false); + if (result.ok) throw new Error("Expected connection failure"); + const output = JSON.stringify(projectAnalysisError(result.error)); + expect(output).not.toContain("fixture-secret"); + expect(output).not.toContain(encoded); + expect(output).toContain("http://localhost:1234/mcp?token="); + expect(output).toContain("&cursor=keep"); + await client.close(); + }, +); + it.each(["initialize", "transport"])( "preserves producer outcome facts when attributing a cached %s failure", async (operation) => { diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index 4eaddac4ed4..c0740155eae 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -24,6 +24,7 @@ import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js"; import { err, ok, type Result } from "../domain/result.js"; import type { IdaConfiguration } from "./IdaConfiguration.js"; import { idaCompatibilityProfile } from "./IdaConfiguration.js"; +import { createIdaDiagnosticRedactor } from "./IdaDiagnosticRedactor.js"; import type { IdaMcpConnection } from "./IdaMcpConnection.js"; import { nativeTools } from "./IdaNativeProtocol.js"; import { readSettledHealth } from "./IdaBusyHealth.js"; @@ -60,7 +61,10 @@ import { } from "../artifacts/ArtifactFileOperation.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; -import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js"; +import { + analysisClientFailureContext, + analysisClientFailureForOperation, +} from "../providers/AnalysisClientFailure.js"; const legacyTools = [ "get_metadata", @@ -456,6 +460,16 @@ export class IdaSessionClient implements AnalysisClient { ) { const artifactFailure = cause instanceof ArtifactReaderFailure ? cause : undefined; + // The validated registration owns the exact endpoint spelling. Apply the + // same credential exclusions used for upstream transport diagnostics. + const endpoint = + artifactFailure === undefined && "url" in this.config + ? { + endpoint: createIdaDiagnosticRedactor(this.config).url( + this.config.url, + ), + } + : {}; if (artifactFailure !== undefined) cause = artifactFilePrimaryFacts(artifactFailure).cause; let failure: AnalysisError; @@ -475,7 +489,7 @@ export class IdaSessionClient implements AnalysisClient { cause: cause.cause === undefined ? options?.signal?.reason : cause.cause, capturedOutput: cause.capturedOutput, - diagnostics: cause.diagnostics, + diagnostics: { ...cause.diagnostics, ...endpoint }, partialObservation: cause.partialObservation, cleanup: cause.cleanup ?? @@ -486,22 +500,38 @@ export class IdaSessionClient implements AnalysisClient { .bindCleanupDependencies([cause]) .bindCleanupResourceOwner(cause); } else if ( - cause instanceof AnalysisTimeoutError && - cause.operation !== operation + (cause instanceof AnalysisTimeoutError || + cause instanceof AnalysisResourceConstraintError) && + cause.operation === operation && + cause.diagnostics?.startup_operation !== undefined + ) { + // #start has already attributed this failure and its endpoint; wrapping + // it again would replace the original producer cause with an intermediate. + failure = cause; + } else if ( + cause instanceof AnalysisTimeoutError || + cause instanceof AnalysisResourceConstraintError ) { failure = analysisClientFailureForOperation( cause, "ida", operation, + endpoint, ).bindCleanupResourceOwner(cause); } else if ( cause instanceof ProviderAdapterError && cause.operation === "transport" ) failure = analysisClientFailureForOperation(cause, "ida", operation, { + ...endpoint, recovery: "Check the configured upstream MCP registration and selected target; see docs/ida-provider.md.", }).bindCleanupResourceOwner(cause); + else if (cause instanceof AnalysisProtocolError && "endpoint" in endpoint) + failure = new AnalysisProtocolError(cause.message, { + ...analysisClientFailureContext(cause, "ida", operation), + diagnostics: { ...cause.diagnostics, ...endpoint }, + }).bindCleanupResourceOwner(cause); else if (cause instanceof AnalysisError) failure = cause; else if (cause instanceof z.ZodError) failure = new AnalysisOutputError( @@ -513,6 +543,7 @@ export class IdaSessionClient implements AnalysisClient { failure = new ProviderAdapterError("ida", operation, { cause, diagnostics: { + ...endpoint, reason: cause instanceof Error ? cause.message : "Unknown upstream failure", recovery: @@ -621,6 +652,13 @@ export class IdaSessionClient implements AnalysisClient { // mutating the cached startup failure. throw analysisClientFailureForOperation(cause, "ida", operation, { startup_operation: cause.operation, + ...("url" in this.config + ? { + endpoint: createIdaDiagnosticRedactor(this.config).url( + this.config.url, + ), + } + : {}), }).bindCleanupResourceOwner(cause); } } diff --git a/tests/acceptance/providers/idaEndpointFailure.test.ts b/tests/acceptance/providers/idaEndpointFailure.test.ts new file mode 100644 index 00000000000..3fb8e2b90ce --- /dev/null +++ b/tests/acceptance/providers/idaEndpointFailure.test.ts @@ -0,0 +1,98 @@ +import { once } from "node:events"; +import { writeFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { expect } from "vitest"; + +import { elf } from "../../../src/domain/binaryTarget.fixture.js"; +import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { workspaceCliTest as test } from "../../support/cli/workspaceCliFixture.js"; + +for (const encodedCredential of [false, true]) + test(`preserves the selected IDA endpoint on a real HTTP failure (encoded credential: ${String(encodedCredential)})`, async ({ + cli, + workspace, + }) => { + const server = createServer((_request, response) => { + response.writeHead(404, { "content-type": "text/plain" }); + response.end("fixture-ida-not-found"); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + let closed = false; + try { + const address = server.address(); + if (address === null || typeof address === "string") + throw new Error("Missing loopback listener address"); + const base = `HTTP://127.0.0.1:0${address.port}/mcp?cursor=kept`; + const endpoint = encodedCredential + ? `${base}&token=fixture%2Dsecret` + : base; + const expectedEndpoint = encodedCredential + ? `${base}&token=[redacted transport credential]` + : base; + const target = workspace.path("target.elf"); + const registration = workspace.path("ida.json"); + await writeFile(target, elf(2, 1, 62)); + await writeFile( + registration, + JSON.stringify({ + url: endpoint, + headers: { Authorization: "Bearer fixture-secret" }, + }), + ); + const result = await cli.run({ + arguments: ["analyze", target, "--provider", "ida", "--json"], + environment: { REA_IDA_MCP_CONFIG: registration }, + }); + expect(result.exitCode, result.stderr).toBe(1); + expect(result.json).toMatchObject({ + code: "execution_failure", + details: { diagnostics: { endpoint: expectedEndpoint } }, + }); + expect(JSON.stringify(result.json)).toContain("fixture-ida-not-found"); + expect(JSON.stringify(result.json)).not.toContain("fixture-secret"); + expect(JSON.stringify(result.json)).not.toContain("fixture%2Dsecret"); + const { call } = await connectLocalToolsMcp({ + REA_IDA_MCP_CONFIG: registration, + }); + const opened = await call("open_binary", { + path: target, + provider_id: "ida", + }); + if (opened.isError) throw new Error(JSON.stringify(opened)); + const failure = parseMcpToolError(await call("list_procedures", {})); + expect(failure.error).toMatchObject({ + code: "execution_failure", + details: { diagnostics: { endpoint: expectedEndpoint } }, + }); + expect(JSON.stringify(failure)).not.toContain("fixture-secret"); + expect(JSON.stringify(failure)).not.toContain("fixture%2Dsecret"); + server.closeAllConnections(); + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + closed = true; + const stopped = await cli.run({ + arguments: ["analyze", target, "--provider", "ida", "--json"], + environment: { REA_IDA_MCP_CONFIG: registration }, + }); + expect(stopped.exitCode, stopped.stderr).toBe(1); + expect(stopped.json).toMatchObject({ + code: "execution_failure", + details: { + diagnostics: { + endpoint: expectedEndpoint, + reason: expect.stringContaining("fetch failed"), + }, + }, + }); + } finally { + if (!closed) { + server.closeAllConnections(); + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + } + } + });