From 751a75242af5b5c6d3e698918c23f96184fce1cf Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 11:18:08 +0800 Subject: [PATCH 1/5] fix: authenticate loopback debug adapter sessions and bind no-config JDWP to loopback - Negotiate startDebugSession protocol v2 ({ protocolVersion: 2 }) and connect via an inline AuthenticatedSocketDebugAdapter over 127.0.0.1 that sends the per-session JavaDebug-Auth handshake before queued DAP requests, with incremental UTF-8 byte framing and legacy numeric-port loopback fallback. - Bind no-config debug wrapper scripts (debugjava, debugjava.fish, debugjava.ps1, debugjava.bat, and jdwp-wrapper.js) strictly to ddress=127.0.0.1:0 and preserve 127.0.0.1 in oConfigDebugInit.ts. - Add Mocha coverage for AuthenticatedSocketDebugAdapter, descriptor negotiation, and loopback JDWP wrapper execution. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .gitattributes | 1 + bundled/scripts/noConfigScripts/debugjava | 2 +- bundled/scripts/noConfigScripts/debugjava.bat | 2 +- .../scripts/noConfigScripts/debugjava.fish | 2 +- bundled/scripts/noConfigScripts/debugjava.ps1 | 2 +- .../scripts/noConfigScripts/jdwp-wrapper.js | 4 +- src/authenticatedDebugAdapter.ts | 229 ++++++++++++++++++ src/javaDebugAdapterDescriptorFactory.ts | 35 ++- src/languageServerPlugin.ts | 13 +- src/noConfigDebugInit.ts | 3 +- test/authenticatedDebugAdapter.test.ts | 206 ++++++++++++++++ test/noConfigDebugInit.test.ts | 19 ++ 12 files changed, 503 insertions(+), 15 deletions(-) create mode 100644 src/authenticatedDebugAdapter.ts create mode 100644 test/authenticatedDebugAdapter.test.ts diff --git a/.gitattributes b/.gitattributes index ddef66b4..178cf781 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ bundled/scripts/noConfigScripts/debugjava text eol=lf +bundled/scripts/noConfigScripts/debugjava.fish text eol=lf diff --git a/bundled/scripts/noConfigScripts/debugjava b/bundled/scripts/noConfigScripts/debugjava index 881a9211..2f8e1b11 100755 --- a/bundled/scripts/noConfigScripts/debugjava +++ b/bundled/scripts/noConfigScripts/debugjava @@ -8,5 +8,5 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Set environment variables only for the node process, not the current shell # This ensures JAVA_TOOL_OPTIONS doesn't affect subsequent commands in the terminal JDWP_ADAPTER_ENDPOINTS=$VSCODE_JDWP_ADAPTER_ENDPOINTS \ -JAVA_TOOL_OPTIONS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=0" \ +JAVA_TOOL_OPTIONS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0" \ exec node "$SCRIPT_DIR/jdwp-wrapper.js" "$@" diff --git a/bundled/scripts/noConfigScripts/debugjava.bat b/bundled/scripts/noConfigScripts/debugjava.bat index 3606188c..9a0c08a0 100644 --- a/bundled/scripts/noConfigScripts/debugjava.bat +++ b/bundled/scripts/noConfigScripts/debugjava.bat @@ -10,7 +10,7 @@ set JDWP_ADAPTER_ENDPOINTS=%VSCODE_JDWP_ADAPTER_ENDPOINTS% REM Set JDWP options only for this debugjava invocation REM This overrides the global JAVA_TOOL_OPTIONS to avoid affecting other Java processes -set JAVA_TOOL_OPTIONS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=0 +set JAVA_TOOL_OPTIONS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0 REM Use Node.js wrapper to capture JDWP port node "%~dp0jdwp-wrapper.js" %* diff --git a/bundled/scripts/noConfigScripts/debugjava.fish b/bundled/scripts/noConfigScripts/debugjava.fish index 47d7cf75..f1f0eae5 100644 --- a/bundled/scripts/noConfigScripts/debugjava.fish +++ b/bundled/scripts/noConfigScripts/debugjava.fish @@ -8,5 +8,5 @@ set script_dir (dirname (status -f)) # Set environment variables only for the node process, not the current shell # This ensures JAVA_TOOL_OPTIONS doesn't affect subsequent commands in the terminal env JDWP_ADAPTER_ENDPOINTS=$VSCODE_JDWP_ADAPTER_ENDPOINTS \ - JAVA_TOOL_OPTIONS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=0" \ + JAVA_TOOL_OPTIONS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0" \ node "$script_dir/jdwp-wrapper.js" $argv diff --git a/bundled/scripts/noConfigScripts/debugjava.ps1 b/bundled/scripts/noConfigScripts/debugjava.ps1 index 0404a860..c8c7bfdd 100644 --- a/bundled/scripts/noConfigScripts/debugjava.ps1 +++ b/bundled/scripts/noConfigScripts/debugjava.ps1 @@ -11,7 +11,7 @@ $oldJdwpAdapterEndpoints = $env:JDWP_ADAPTER_ENDPOINTS try { # Set environment variables only for this debugjava invocation $env:JDWP_ADAPTER_ENDPOINTS = $env:VSCODE_JDWP_ADAPTER_ENDPOINTS - $env:JAVA_TOOL_OPTIONS = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=0" + $env:JAVA_TOOL_OPTIONS = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0" # Use Node.js wrapper to capture JDWP port & node (Join-Path $scriptDir "jdwp-wrapper.js") $args diff --git a/bundled/scripts/noConfigScripts/jdwp-wrapper.js b/bundled/scripts/noConfigScripts/jdwp-wrapper.js index cae86170..58c2204d 100644 --- a/bundled/scripts/noConfigScripts/jdwp-wrapper.js +++ b/bundled/scripts/noConfigScripts/jdwp-wrapper.js @@ -85,7 +85,7 @@ if (!isDebugEnabled) { setupSignalHandlers(child); let portCaptured = false; - const jdwpPortRegex = /Listening for transport dt_socket at address:\s*(\d+)/; + const jdwpPortRegex = /Listening for transport dt_socket at address:\s*(?:127\.0\.0\.1:|localhost:|\[::1\]:)?(\d+)/; // Shared function to capture JDWP port from output const capturePort = (output) => { @@ -106,7 +106,7 @@ if (!isDebugEnabled) { // Write port to endpoint file const endpointData = JSON.stringify({ client: { - host: 'localhost', + host: '127.0.0.1', port: port } }); diff --git a/src/authenticatedDebugAdapter.ts b/src/authenticatedDebugAdapter.ts new file mode 100644 index 00000000..ce214ef5 --- /dev/null +++ b/src/authenticatedDebugAdapter.ts @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +import * as net from "net"; +import { DebugAdapter, DebugProtocolMessage, Event, EventEmitter } from "vscode"; + +const AUTH_HEADER_PREFIX = "JavaDebug-Auth: "; +const TWO_CRLF = "\r\n\r\n"; +const TWO_CRLF_BYTES = 4; +const MAX_HEADER_BYTES = 8 * 1024; +const MAX_CONTENT_BYTES = 32 * 1024 * 1024; +const CONTENT_LENGTH_PATTERN = /Content-Length:\s*(\d+)/i; + +interface IDapEnvelope { + seq?: number; + type?: string; + command?: string; + event?: string; + request_seq?: number; +} + +export class AuthenticatedSocketDebugAdapter implements DebugAdapter { + public readonly onDidSendMessage: Event; + + private readonly sendMessageEmitter = new EventEmitter(); + private readonly host: string; + private readonly port: number; + private readonly authToken: string; + private readonly inFlightRequests = new Map(); + + private socket: net.Socket | undefined; + private connected: boolean = false; + private disposed: boolean = false; + private terminatedEmitted: boolean = false; + private lastSocketError: Error | undefined; + private pendingOutbound: Buffer[] = []; + private rawData: Buffer = Buffer.alloc(0); + private contentLength: number = -1; + private syntheticSeq: number = 1000000; + + public constructor(port: number, authToken: string, host: string = "127.0.0.1") { + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`Invalid debug server port: ${port}`); + } + if (!authToken || /[\r\n]/.test(authToken)) { + throw new Error("Invalid debug session authentication token."); + } + + this.port = port; + this.authToken = authToken; + this.host = host; + this.onDidSendMessage = this.sendMessageEmitter.event; + this.connect(); + } + + public handleMessage(message: DebugProtocolMessage): void { + if (this.disposed) { + return; + } + + const envelope = message as unknown as IDapEnvelope; + if (envelope && envelope.type === "request" && typeof envelope.seq === "number" && typeof envelope.command === "string") { + this.inFlightRequests.set(envelope.seq, envelope.command); + } + + const jsonBytes = Buffer.from(JSON.stringify(message), "utf8"); + const headerBytes = Buffer.from(`Content-Length: ${jsonBytes.length}${TWO_CRLF}`, "ascii"); + const frame = Buffer.concat([headerBytes, jsonBytes]); + + if (this.connected && this.socket && !this.socket.destroyed) { + this.socket.write(frame); + } else { + this.pendingOutbound.push(frame); + } + } + + public dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + this.pendingOutbound = []; + this.inFlightRequests.clear(); + this.rawData = Buffer.alloc(0); + if (this.socket) { + this.socket.destroy(); + this.socket = undefined; + } + this.sendMessageEmitter.dispose(); + } + + private connect(): void { + const socket = net.createConnection({ + host: this.host, + port: this.port, + }); + this.socket = socket; + + socket.on("connect", () => { + if (this.disposed) { + socket.destroy(); + return; + } + socket.setNoDelay(true); + const handshake = Buffer.from(`${AUTH_HEADER_PREFIX}${this.authToken}${TWO_CRLF}`, "ascii"); + socket.write(handshake); + this.connected = true; + for (const frame of this.pendingOutbound) { + socket.write(frame); + } + this.pendingOutbound = []; + }); + + socket.on("data", (chunk: Buffer) => { + this.handleData(chunk); + }); + + socket.on("error", (err: Error) => { + this.lastSocketError = err; + }); + + socket.on("close", () => { + this.connected = false; + if (!this.disposed) { + this.failPendingRequestsAndTerminate(); + } + }); + } + + private handleData(chunk: Buffer): void { + if (this.disposed || chunk.length === 0) { + return; + } + + this.rawData = this.rawData.length === 0 ? chunk : Buffer.concat([this.rawData, chunk]); + + while (!this.disposed) { + if (this.contentLength >= 0) { + if (this.rawData.length < this.contentLength) { + break; + } + + const bodyBytes = this.rawData.subarray(0, this.contentLength); + this.rawData = this.rawData.subarray(this.contentLength); + this.contentLength = -1; + + try { + const parsed = JSON.parse(bodyBytes.toString("utf8")) as IDapEnvelope; + if (parsed && parsed.type === "response" && typeof parsed.request_seq === "number") { + this.inFlightRequests.delete(parsed.request_seq); + } else if (parsed && parsed.type === "event" && parsed.event === "terminated") { + this.terminatedEmitted = true; + } + this.sendMessageEmitter.fire(parsed as unknown as DebugProtocolMessage); + } catch (_err) { + if (this.socket) { + this.socket.destroy(); + } + break; + } + continue; + } + + const headerEnd = this.rawData.indexOf(TWO_CRLF); + if (headerEnd === -1) { + if (this.rawData.length > MAX_HEADER_BYTES) { + this.lastSocketError = new Error("Debug adapter response header exceeded maximum length."); + if (this.socket) { + this.socket.destroy(); + } + } + break; + } + + const header = this.rawData.subarray(0, headerEnd).toString("ascii"); + this.rawData = this.rawData.subarray(headerEnd + TWO_CRLF_BYTES); + + const match = CONTENT_LENGTH_PATTERN.exec(header); + if (!match) { + this.lastSocketError = new Error("Debug adapter response missing Content-Length header."); + if (this.socket) { + this.socket.destroy(); + } + break; + } + + const parsedLength = Number.parseInt(match[1], 10); + if (!Number.isSafeInteger(parsedLength) || parsedLength < 0 || parsedLength > MAX_CONTENT_BYTES) { + this.lastSocketError = new Error(`Debug adapter Content-Length out of bounds: ${match[1]}`); + if (this.socket) { + this.socket.destroy(); + } + break; + } + + this.contentLength = parsedLength; + } + } + + private failPendingRequestsAndTerminate(): void { + const reason = this.lastSocketError + ? `Debug adapter socket closed: ${this.lastSocketError.message}` + : "Debug adapter socket closed unexpectedly."; + + const pendingEntries = Array.from(this.inFlightRequests.entries()); + this.inFlightRequests.clear(); + for (const [requestSeq, command] of pendingEntries) { + const errorResponse = { + seq: this.syntheticSeq++, + type: "response", + request_seq: requestSeq, + success: false, + command, + message: reason, + }; + this.sendMessageEmitter.fire(errorResponse as unknown as DebugProtocolMessage); + } + + if (!this.terminatedEmitted) { + this.terminatedEmitted = true; + const terminatedEvent = { + seq: this.syntheticSeq++, + type: "event", + event: "terminated", + }; + this.sendMessageEmitter.fire(terminatedEvent as unknown as DebugProtocolMessage); + } + } +} diff --git a/src/javaDebugAdapterDescriptorFactory.ts b/src/javaDebugAdapterDescriptorFactory.ts index 99bd78c0..6894e072 100644 --- a/src/javaDebugAdapterDescriptorFactory.ts +++ b/src/javaDebugAdapterDescriptorFactory.ts @@ -1,19 +1,31 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -import { DebugAdapterDescriptor, DebugAdapterDescriptorFactory, DebugAdapterExecutable, DebugAdapterServer, DebugSession } from "vscode"; +import { + DebugAdapterDescriptor, + DebugAdapterDescriptorFactory, + DebugAdapterExecutable, + DebugAdapterInlineImplementation, + DebugAdapterServer, + DebugSession, +} from "vscode"; +import { AuthenticatedSocketDebugAdapter } from "./authenticatedDebugAdapter"; import { Type } from "./javaLogger"; -import { startDebugSession } from "./languageServerPlugin"; +import { IDebugSessionDescriptor, startDebugSession } from "./languageServerPlugin"; import { convertErrorToMessage, showErrorMessageWithTroubleshooting } from "./utility"; export class JavaDebugAdapterDescriptorFactory implements DebugAdapterDescriptorFactory { public async createDebugAdapterDescriptor(_session: DebugSession, _executable: DebugAdapterExecutable): Promise { - let error: Error| undefined; + let error: Error | undefined; try { - const debugServerPort = (await startDebugSession()); - if (debugServerPort) { - return new DebugAdapterServer(debugServerPort); + const sessionDescriptor = await startDebugSession(); + if (isAuthenticatedSessionDescriptor(sessionDescriptor)) { + const host = sessionDescriptor.host || "127.0.0.1"; + return new DebugAdapterInlineImplementation( + new AuthenticatedSocketDebugAdapter(sessionDescriptor.port, sessionDescriptor.authToken, host)); + } else if (typeof sessionDescriptor === "number" && sessionDescriptor > 0) { + return new DebugAdapterServer(sessionDescriptor, "127.0.0.1"); } else { // Information for diagnostic: // tslint:disable-next-line:no-console @@ -31,3 +43,14 @@ export class JavaDebugAdapterDescriptorFactory implements DebugAdapterDescriptor return undefined; } } + +function isAuthenticatedSessionDescriptor(value: unknown): value is IDebugSessionDescriptor { + if (typeof value !== "object" || value === null) { + return false; + } + const candidate = value as Partial; + return typeof candidate.port === "number" + && candidate.port > 0 + && typeof candidate.authToken === "string" + && candidate.authToken.length > 0; +} diff --git a/src/languageServerPlugin.ts b/src/languageServerPlugin.ts index bbafd573..cb5d6775 100644 --- a/src/languageServerPlugin.ts +++ b/src/languageServerPlugin.ts @@ -47,8 +47,17 @@ export async function resolveMainMethod(uri: vscode.Uri, token?: vscode.Cancella return await commands.executeJavaLanguageServerCommand(commands.JAVA_RESOLVE_MAINMETHOD, uri.toString()); } -export function startDebugSession() { - return commands.executeJavaLanguageServerCommand(commands.JAVA_START_DEBUGSESSION); +export interface IDebugSessionDescriptor { + readonly host?: string; + readonly port: number; + readonly authToken: string; + readonly protocolVersion?: number; +} + +export function startDebugSession(): Promise { + return >commands.executeJavaLanguageServerCommand( + commands.JAVA_START_DEBUGSESSION, + JSON.stringify({ protocolVersion: 2 })); } export function resolveClasspath(mainClass: string, projectName: string, scope?: string) { diff --git a/src/noConfigDebugInit.ts b/src/noConfigDebugInit.ts index 9cffee11..afd6c4c4 100644 --- a/src/noConfigDebugInit.ts +++ b/src/noConfigDebugInit.ts @@ -156,6 +156,7 @@ export async function registerNoConfigDebug( } const clientPort = jsonData.client.port; + const clientHost = jsonData.client.host === '127.0.0.1' ? '127.0.0.1' : 'localhost'; // Validate port number if (!clientPort || typeof clientPort !== 'number' || clientPort < 1 || clientPort > 65535) { @@ -187,7 +188,7 @@ export async function registerNoConfigDebug( type: 'java', request: 'attach', name: 'Attach to Java (No-Config)', - hostName: 'localhost', + hostName: clientHost, port: clientPort, }, options, diff --git a/test/authenticatedDebugAdapter.test.ts b/test/authenticatedDebugAdapter.test.ts new file mode 100644 index 00000000..5d81a458 --- /dev/null +++ b/test/authenticatedDebugAdapter.test.ts @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +import * as assert from "assert"; +import { spawnSync } from "child_process"; +import * as fs from "fs"; +import * as net from "net"; +import * as os from "os"; +import * as path from "path"; +import { + DebugAdapterInlineImplementation, + DebugAdapterServer, + DebugProtocolMessage, +} from "vscode"; + +import { AuthenticatedSocketDebugAdapter } from "../src/authenticatedDebugAdapter"; +import { JavaDebugAdapterDescriptorFactory } from "../src/javaDebugAdapterDescriptorFactory"; +import * as languageServerPlugin from "../src/languageServerPlugin"; +import * as utility from "../src/utility"; + +const VALID_TOKEN = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90"; + +function frameDapMessage(payload: object): Buffer { + const bodyBytes = Buffer.from(JSON.stringify(payload), "utf8"); + const headerBytes = Buffer.from(`Content-Length: ${bodyBytes.length}\r\n\r\n`, "ascii"); + return Buffer.concat([headerBytes, bodyBytes]); +} + +suite("AuthenticatedSocketDebugAdapter", () => { + test("rejects invalid ports and CRLF-injected tokens", () => { + assert.throws(() => new AuthenticatedSocketDebugAdapter(0, VALID_TOKEN)); + assert.throws(() => new AuthenticatedSocketDebugAdapter(70000, VALID_TOKEN)); + assert.throws(() => new AuthenticatedSocketDebugAdapter(12345, "")); + assert.throws(() => new AuthenticatedSocketDebugAdapter(12345, "abc\r\nContent-Length: 2")); + }); + + test("sends JavaDebug-Auth prelude before queued DAP frames and handles split UTF-8 responses", async () => { + let receivedRaw = Buffer.alloc(0); + const expectedHandshake = `JavaDebug-Auth: ${VALID_TOKEN}\r\n\r\n`; + + const server = net.createServer((socket) => { + socket.on("data", (chunk: Buffer) => { + receivedRaw = Buffer.concat([receivedRaw, chunk]); + const rawText = receivedRaw.toString("utf8"); + if (rawText.startsWith(expectedHandshake) && rawText.includes("\"command\":\"initialize\"")) { + const responseFrame = frameDapMessage({ + seq: 1, + type: "response", + request_seq: 1, + success: true, + command: "initialize", + body: { + greeting: "こんにちは🚀", + }, + }); + // Split across an arbitrary multi-byte UTF-8 boundary to verify byte-accurate reassembly. + const splitIndex = responseFrame.length - 7; + socket.write(responseFrame.subarray(0, splitIndex)); + setTimeout(() => { + socket.write(responseFrame.subarray(splitIndex)); + }, 10); + } + }); + }); + + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const port = (server.address() as net.AddressInfo).port; + const adapter = new AuthenticatedSocketDebugAdapter(port, VALID_TOKEN, "127.0.0.1"); + + try { + const responsePromise = new Promise((resolve) => { + adapter.onDidSendMessage((msg: DebugProtocolMessage) => { + resolve(msg); + }); + }); + + // Queue message immediately before connect callback completes. + adapter.handleMessage({ + seq: 1, + type: "request", + command: "initialize", + arguments: { adapterID: "java" }, + } as unknown as DebugProtocolMessage); + + const response = await responsePromise; + assert.strictEqual(response.type, "response"); + assert.strictEqual(response.success, true); + assert.strictEqual(response.body.greeting, "こんにちは🚀"); + assert.ok(receivedRaw.toString("utf8").startsWith(expectedHandshake)); + } finally { + adapter.dispose(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + test("fails pending requests and emits terminated when server rejects handshake and closes socket", async () => { + const server = net.createServer((socket) => { + socket.on("data", () => { + socket.destroy(); + }); + }); + + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const port = (server.address() as net.AddressInfo).port; + const adapter = new AuthenticatedSocketDebugAdapter(port, VALID_TOKEN, "127.0.0.1"); + + try { + const receivedMessages: any[] = []; + const terminatedPromise = new Promise((resolve) => { + adapter.onDidSendMessage((msg: DebugProtocolMessage) => { + const envelope = msg as any; + receivedMessages.push(envelope); + if (envelope.type === "event" && envelope.event === "terminated") { + resolve(); + } + }); + }); + + adapter.handleMessage({ + seq: 7, + type: "request", + command: "initialize", + arguments: {}, + } as unknown as DebugProtocolMessage); + + await terminatedPromise; + const failedInit = receivedMessages.find((m) => m.type === "response" && m.request_seq === 7); + assert.ok(failedInit, "Expected pending initialize request to receive a synthetic error response."); + assert.strictEqual(failedInit.success, false); + assert.strictEqual(failedInit.command, "initialize"); + } finally { + adapter.dispose(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + test("JavaDebugAdapterDescriptorFactory returns inline authenticated adapter for protocol v2 and loopback server for legacy port", async () => { + const server = net.createServer((socket) => socket.destroy()); + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const port = (server.address() as net.AddressInfo).port; + + const origStart = languageServerPlugin.startDebugSession; + const origShowErr = utility.showErrorMessageWithTroubleshooting; + let reportedError: any; + + try { + (languageServerPlugin as any).startDebugSession = async () => ({ + protocolVersion: 2, + host: "127.0.0.1", + port, + authToken: VALID_TOKEN, + }); + (utility as any).showErrorMessageWithTroubleshooting = (msg: any) => { + reportedError = msg; + }; + + const factory = new JavaDebugAdapterDescriptorFactory(); + const v2Descriptor = await factory.createDebugAdapterDescriptor({} as any, {} as any); + assert.ok(v2Descriptor instanceof DebugAdapterInlineImplementation); + ((v2Descriptor as any).implementation as AuthenticatedSocketDebugAdapter).dispose(); + + (languageServerPlugin as any).startDebugSession = async () => port; + const legacyDescriptor = await factory.createDebugAdapterDescriptor({} as any, {} as any); + assert.ok(legacyDescriptor instanceof DebugAdapterServer); + assert.strictEqual((legacyDescriptor as DebugAdapterServer).port, port); + assert.strictEqual((legacyDescriptor as DebugAdapterServer).host, "127.0.0.1"); + + (languageServerPlugin as any).startDebugSession = async () => ({ invalid: true }); + const invalidDescriptor = await factory.createDebugAdapterDescriptor({} as any, {} as any); + assert.strictEqual(invalidDescriptor, undefined); + assert.ok(reportedError); + } finally { + (languageServerPlugin as any).startDebugSession = origStart; + (utility as any).showErrorMessageWithTroubleshooting = origShowErr; + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + test("jdwp-wrapper.js captures real JVM loopback JDWP port and writes 127.0.0.1 endpoint file", function() { + this.timeout(15000); + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "jdwp-wrapper-test-")); + const endpointFile = path.join(tempDir, "endpoint.txt"); + const wrapperScript = path.resolve(__dirname, "../../bundled/scripts/noConfigScripts/jdwp-wrapper.js"); + + try { + const result = spawnSync(process.execPath, [wrapperScript, "-version"], { + env: { + ...process.env, + JAVA_TOOL_OPTIONS: "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:0", + VSCODE_JDWP_ADAPTER_ENDPOINTS: endpointFile, + }, + encoding: "utf8", + timeout: 15000, + }); + + assert.strictEqual(result.status, 0, `jdwp-wrapper failed: ${result.stderr}`); + assert.ok(fs.existsSync(endpointFile), "Expected jdwp-wrapper.js to create endpoint.txt"); + const endpointJson = JSON.parse(fs.readFileSync(endpointFile, "utf8")); + assert.strictEqual(endpointJson.client.host, "127.0.0.1"); + assert.strictEqual(typeof endpointJson.client.port, "number"); + assert.ok(endpointJson.client.port > 0 && endpointJson.client.port <= 65535); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); +}); diff --git a/test/noConfigDebugInit.test.ts b/test/noConfigDebugInit.test.ts index 6d255f94..4c408c5a 100644 --- a/test/noConfigDebugInit.test.ts +++ b/test/noConfigDebugInit.test.ts @@ -103,4 +103,23 @@ suite("No-Config Debug scripts", () => { await ensureDebugJavaScriptExecutable(missingScriptPath, "win32"); }); + + test("all bundled no-config debug scripts bind JDWP strictly to 127.0.0.1:0", async () => { + const scriptsDir = path.resolve(__dirname, "../../bundled/scripts/noConfigScripts"); + for (const scriptName of ["debugjava", "debugjava.fish", "debugjava.ps1", "debugjava.bat"]) { + const contents = await fs.promises.readFile(path.join(scriptsDir, scriptName), "utf8"); + assert.ok( + contents.includes("address=127.0.0.1:0"), + `Expected ${scriptName} to bind JDWP to 127.0.0.1:0`, + ); + assert.strictEqual( + contents.includes("address=0"), + false, + `Expected ${scriptName} not to use wildcard address=0`, + ); + } + + const fishContents = await fs.promises.readFile(path.join(scriptsDir, "debugjava.fish"), "utf8"); + assert.strictEqual(fishContents.includes("\r"), false); + }); }); From 4a4885c65c4190ca718cb4e1ee30930ce0db4c54 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 11:38:29 +0800 Subject: [PATCH 2/5] fix: fail post-close requests and enforce single-chunk header limit - Immediately synthesize a failure DAP response when handleMessage receives a request after the socket has closed instead of queuing dead outbound frames. - Enforce MAX_HEADER_BYTES even when the \r\n\r\n header terminator arrives in the same TCP chunk as the oversized header. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/authenticatedDebugAdapter.ts | 34 ++++++++++++- test/authenticatedDebugAdapter.test.ts | 68 ++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 2 deletions(-) diff --git a/src/authenticatedDebugAdapter.ts b/src/authenticatedDebugAdapter.ts index ce214ef5..90da6ed5 100644 --- a/src/authenticatedDebugAdapter.ts +++ b/src/authenticatedDebugAdapter.ts @@ -30,6 +30,7 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { private socket: net.Socket | undefined; private connected: boolean = false; + private socketClosed: boolean = false; private disposed: boolean = false; private terminatedEmitted: boolean = false; private lastSocketError: Error | undefined; @@ -59,6 +60,21 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { } const envelope = message as unknown as IDapEnvelope; + if (this.socketClosed || (this.socket && this.socket.destroyed)) { + if (envelope && envelope.type === "request" && typeof envelope.seq === "number" && typeof envelope.command === "string") { + const errorResponse = { + seq: this.syntheticSeq++, + type: "response", + request_seq: envelope.seq, + success: false, + command: envelope.command, + message: this.getSocketClosedReason(), + }; + this.sendMessageEmitter.fire(errorResponse as unknown as DebugProtocolMessage); + } + return; + } + if (envelope && envelope.type === "request" && typeof envelope.seq === "number" && typeof envelope.command === "string") { this.inFlightRequests.set(envelope.seq, envelope.command); } @@ -121,6 +137,8 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { socket.on("close", () => { this.connected = false; + this.socketClosed = true; + this.pendingOutbound = []; if (!this.disposed) { this.failPendingRequestsAndTerminate(); } @@ -172,6 +190,14 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { break; } + if (headerEnd + TWO_CRLF_BYTES > MAX_HEADER_BYTES) { + this.lastSocketError = new Error("Debug adapter response header exceeded maximum length."); + if (this.socket) { + this.socket.destroy(); + } + break; + } + const header = this.rawData.subarray(0, headerEnd).toString("ascii"); this.rawData = this.rawData.subarray(headerEnd + TWO_CRLF_BYTES); @@ -197,10 +223,14 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { } } - private failPendingRequestsAndTerminate(): void { - const reason = this.lastSocketError + private getSocketClosedReason(): string { + return this.lastSocketError ? `Debug adapter socket closed: ${this.lastSocketError.message}` : "Debug adapter socket closed unexpectedly."; + } + + private failPendingRequestsAndTerminate(): void { + const reason = this.getSocketClosedReason(); const pendingEntries = Array.from(this.inFlightRequests.entries()); this.inFlightRequests.clear(); diff --git a/test/authenticatedDebugAdapter.test.ts b/test/authenticatedDebugAdapter.test.ts index 5d81a458..eb368fa4 100644 --- a/test/authenticatedDebugAdapter.test.ts +++ b/test/authenticatedDebugAdapter.test.ts @@ -128,6 +128,74 @@ suite("AuthenticatedSocketDebugAdapter", () => { assert.ok(failedInit, "Expected pending initialize request to receive a synthetic error response."); assert.strictEqual(failedInit.success, false); assert.strictEqual(failedInit.command, "initialize"); + + // Subsequent teardown requests (e.g. disconnect) after socket closure must fail immediately rather than hang. + const lateResponsePromise = new Promise((resolve) => { + adapter.onDidSendMessage((msg: DebugProtocolMessage) => { + resolve(msg); + }); + }); + adapter.handleMessage({ + seq: 8, + type: "request", + command: "disconnect", + arguments: {}, + } as unknown as DebugProtocolMessage); + const lateResponse = await lateResponsePromise; + assert.strictEqual(lateResponse.type, "response"); + assert.strictEqual(lateResponse.request_seq, 8); + assert.strictEqual(lateResponse.success, false); + assert.strictEqual(lateResponse.command, "disconnect"); + } finally { + adapter.dispose(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + test("rejects oversized response headers even when header terminator arrives in a single chunk", async () => { + const server = net.createServer((socket) => { + socket.once("data", () => { + const body = JSON.stringify({ + seq: 1, + type: "response", + request_seq: 1, + success: true, + command: "initialize", + }); + const padding = "X-Pad: " + "a".repeat(9000) + "\r\n"; + const oversizedFrame = Buffer.from(`${padding}Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`, "utf8"); + socket.write(oversizedFrame); + }); + }); + + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const port = (server.address() as net.AddressInfo).port; + const adapter = new AuthenticatedSocketDebugAdapter(port, VALID_TOKEN, "127.0.0.1"); + + try { + const receivedMessages: any[] = []; + const terminatedPromise = new Promise((resolve) => { + adapter.onDidSendMessage((msg: DebugProtocolMessage) => { + const envelope = msg as any; + receivedMessages.push(envelope); + if (envelope.type === "event" && envelope.event === "terminated") { + resolve(); + } + }); + }); + + adapter.handleMessage({ + seq: 1, + type: "request", + command: "initialize", + arguments: {}, + } as unknown as DebugProtocolMessage); + + await terminatedPromise; + const resp = receivedMessages.find((m) => m.type === "response" && m.request_seq === 1); + assert.ok(resp); + assert.strictEqual(resp.success, false); + assert.ok(String(resp.message).includes("exceeded maximum length")); } finally { adapter.dispose(); await new Promise((resolve) => server.close(() => resolve())); From f1a7a906c986e84d8668e1c9fbfa21c69791ce05 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 12:00:11 +0800 Subject: [PATCH 3/5] fix: enforce loopback host and O(n) chunked frame buffering - Validate literal loopback host (127.0.0.1 or ::1) in both JavaDebugAdapterDescriptorFactory and AuthenticatedSocketDebugAdapter before opening any socket. - Buffer inbound socket chunks in a chunk queue and assemble bytes once per completed frame to avoid quadratic copying on large responses. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/authenticatedDebugAdapter.ts | 95 +++++++++++++++++++++--- src/javaDebugAdapterDescriptorFactory.ts | 4 +- test/authenticatedDebugAdapter.test.ts | 32 ++++++-- 3 files changed, 112 insertions(+), 19 deletions(-) diff --git a/src/authenticatedDebugAdapter.ts b/src/authenticatedDebugAdapter.ts index 90da6ed5..912ebecb 100644 --- a/src/authenticatedDebugAdapter.ts +++ b/src/authenticatedDebugAdapter.ts @@ -19,6 +19,17 @@ interface IDapEnvelope { request_seq?: number; } +export function normalizeLoopbackHost(host: string = "127.0.0.1"): string { + const trimmed = host.trim(); + if (trimmed === "127.0.0.1") { + return "127.0.0.1"; + } + if (trimmed === "::1" || trimmed === "[::1]" || trimmed === "0:0:0:0:0:0:0:1") { + return "::1"; + } + throw new Error(`Invalid non-loopback debug server host: ${host}`); +} + export class AuthenticatedSocketDebugAdapter implements DebugAdapter { public readonly onDidSendMessage: Event; @@ -35,7 +46,8 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { private terminatedEmitted: boolean = false; private lastSocketError: Error | undefined; private pendingOutbound: Buffer[] = []; - private rawData: Buffer = Buffer.alloc(0); + private readChunks: Buffer[] = []; + private bufferedBytes: number = 0; private contentLength: number = -1; private syntheticSeq: number = 1000000; @@ -49,7 +61,7 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { this.port = port; this.authToken = authToken; - this.host = host; + this.host = normalizeLoopbackHost(host); this.onDidSendMessage = this.sendMessageEmitter.event; this.connect(); } @@ -97,7 +109,8 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { this.disposed = true; this.pendingOutbound = []; this.inFlightRequests.clear(); - this.rawData = Buffer.alloc(0); + this.readChunks = []; + this.bufferedBytes = 0; if (this.socket) { this.socket.destroy(); this.socket = undefined; @@ -150,16 +163,16 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { return; } - this.rawData = this.rawData.length === 0 ? chunk : Buffer.concat([this.rawData, chunk]); + this.readChunks.push(chunk); + this.bufferedBytes += chunk.length; while (!this.disposed) { if (this.contentLength >= 0) { - if (this.rawData.length < this.contentLength) { + if (this.bufferedBytes < this.contentLength) { break; } - const bodyBytes = this.rawData.subarray(0, this.contentLength); - this.rawData = this.rawData.subarray(this.contentLength); + const bodyBytes = this.consumeBytes(this.contentLength); this.contentLength = -1; try { @@ -179,9 +192,14 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { continue; } - const headerEnd = this.rawData.indexOf(TWO_CRLF); + if (this.bufferedBytes === 0) { + break; + } + + const headerWindow = this.peekPrefix(MAX_HEADER_BYTES + TWO_CRLF_BYTES); + const headerEnd = headerWindow.indexOf(TWO_CRLF); if (headerEnd === -1) { - if (this.rawData.length > MAX_HEADER_BYTES) { + if (this.bufferedBytes > MAX_HEADER_BYTES) { this.lastSocketError = new Error("Debug adapter response header exceeded maximum length."); if (this.socket) { this.socket.destroy(); @@ -198,8 +216,8 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { break; } - const header = this.rawData.subarray(0, headerEnd).toString("ascii"); - this.rawData = this.rawData.subarray(headerEnd + TWO_CRLF_BYTES); + const headerBytes = this.consumeBytes(headerEnd + TWO_CRLF_BYTES); + const header = headerBytes.subarray(0, headerEnd).toString("ascii"); const match = CONTENT_LENGTH_PATTERN.exec(header); if (!match) { @@ -223,6 +241,61 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { } } + private peekPrefix(maxBytes: number): Buffer { + const targetLength = Math.min(this.bufferedBytes, maxBytes); + if (targetLength === 0) { + return Buffer.alloc(0); + } + const first = this.readChunks[0]; + if (first.length >= targetLength) { + return first.subarray(0, targetLength); + } + const out = Buffer.allocUnsafe(targetLength); + let offset = 0; + for (const piece of this.readChunks) { + const toCopy = Math.min(piece.length, targetLength - offset); + piece.copy(out, offset, 0, toCopy); + offset += toCopy; + if (offset >= targetLength) { + break; + } + } + return out; + } + + private consumeBytes(length: number): Buffer { + if (length === 0) { + return Buffer.alloc(0); + } + const first = this.readChunks[0]; + if (first.length === length) { + this.readChunks.shift(); + this.bufferedBytes -= length; + return first; + } + if (first.length > length) { + const slice = first.subarray(0, length); + this.readChunks[0] = first.subarray(length); + this.bufferedBytes -= length; + return slice; + } + const result = Buffer.allocUnsafe(length); + let offset = 0; + while (offset < length) { + const head = this.readChunks[0]; + const toCopy = Math.min(head.length, length - offset); + head.copy(result, offset, 0, toCopy); + if (toCopy === head.length) { + this.readChunks.shift(); + } else { + this.readChunks[0] = head.subarray(toCopy); + } + offset += toCopy; + } + this.bufferedBytes -= length; + return result; + } + private getSocketClosedReason(): string { return this.lastSocketError ? `Debug adapter socket closed: ${this.lastSocketError.message}` diff --git a/src/javaDebugAdapterDescriptorFactory.ts b/src/javaDebugAdapterDescriptorFactory.ts index 6894e072..2e3d6e87 100644 --- a/src/javaDebugAdapterDescriptorFactory.ts +++ b/src/javaDebugAdapterDescriptorFactory.ts @@ -9,7 +9,7 @@ import { DebugAdapterServer, DebugSession, } from "vscode"; -import { AuthenticatedSocketDebugAdapter } from "./authenticatedDebugAdapter"; +import { AuthenticatedSocketDebugAdapter, normalizeLoopbackHost } from "./authenticatedDebugAdapter"; import { Type } from "./javaLogger"; import { IDebugSessionDescriptor, startDebugSession } from "./languageServerPlugin"; import { convertErrorToMessage, showErrorMessageWithTroubleshooting } from "./utility"; @@ -21,7 +21,7 @@ export class JavaDebugAdapterDescriptorFactory implements DebugAdapterDescriptor try { const sessionDescriptor = await startDebugSession(); if (isAuthenticatedSessionDescriptor(sessionDescriptor)) { - const host = sessionDescriptor.host || "127.0.0.1"; + const host = normalizeLoopbackHost(sessionDescriptor.host || "127.0.0.1"); return new DebugAdapterInlineImplementation( new AuthenticatedSocketDebugAdapter(sessionDescriptor.port, sessionDescriptor.authToken, host)); } else if (typeof sessionDescriptor === "number" && sessionDescriptor > 0) { diff --git a/test/authenticatedDebugAdapter.test.ts b/test/authenticatedDebugAdapter.test.ts index eb368fa4..ab405e5c 100644 --- a/test/authenticatedDebugAdapter.test.ts +++ b/test/authenticatedDebugAdapter.test.ts @@ -27,11 +27,15 @@ function frameDapMessage(payload: object): Buffer { } suite("AuthenticatedSocketDebugAdapter", () => { - test("rejects invalid ports and CRLF-injected tokens", () => { + test("rejects invalid ports, non-loopback hosts, and CRLF-injected tokens", () => { assert.throws(() => new AuthenticatedSocketDebugAdapter(0, VALID_TOKEN)); assert.throws(() => new AuthenticatedSocketDebugAdapter(70000, VALID_TOKEN)); assert.throws(() => new AuthenticatedSocketDebugAdapter(12345, "")); assert.throws(() => new AuthenticatedSocketDebugAdapter(12345, "abc\r\nContent-Length: 2")); + assert.throws(() => new AuthenticatedSocketDebugAdapter(12345, VALID_TOKEN, "0.0.0.0")); + assert.throws(() => new AuthenticatedSocketDebugAdapter(12345, VALID_TOKEN, "192.168.1.20")); + assert.throws(() => new AuthenticatedSocketDebugAdapter(12345, VALID_TOKEN, "remote.example.com")); + assert.throws(() => new AuthenticatedSocketDebugAdapter(12345, VALID_TOKEN, "localhost")); }); test("sends JavaDebug-Auth prelude before queued DAP frames and handles split UTF-8 responses", async () => { @@ -53,12 +57,16 @@ suite("AuthenticatedSocketDebugAdapter", () => { greeting: "こんにちは🚀", }, }); - // Split across an arbitrary multi-byte UTF-8 boundary to verify byte-accurate reassembly. - const splitIndex = responseFrame.length - 7; - socket.write(responseFrame.subarray(0, splitIndex)); + // Split across both the \r\n\r\n header terminator AND a multi-byte UTF-8 boundary. + const headerSplit = responseFrame.indexOf("\r\n\r\n") + 2; + const utf8Split = responseFrame.length - 7; + socket.write(responseFrame.subarray(0, headerSplit)); setTimeout(() => { - socket.write(responseFrame.subarray(splitIndex)); - }, 10); + socket.write(responseFrame.subarray(headerSplit, utf8Split)); + setTimeout(() => { + socket.write(responseFrame.subarray(utf8Split)); + }, 5); + }, 5); } }); }); @@ -233,7 +241,19 @@ suite("AuthenticatedSocketDebugAdapter", () => { assert.strictEqual((legacyDescriptor as DebugAdapterServer).port, port); assert.strictEqual((legacyDescriptor as DebugAdapterServer).host, "127.0.0.1"); + (languageServerPlugin as any).startDebugSession = async () => ({ + protocolVersion: 2, + host: "10.0.0.8", + port, + authToken: VALID_TOKEN, + }); + reportedError = undefined; + const nonLoopbackDescriptor = await factory.createDebugAdapterDescriptor({} as any, {} as any); + assert.strictEqual(nonLoopbackDescriptor, undefined); + assert.ok(reportedError, "Expected non-loopback descriptor host to be rejected."); + (languageServerPlugin as any).startDebugSession = async () => ({ invalid: true }); + reportedError = undefined; const invalidDescriptor = await factory.createDebugAdapterDescriptor({} as any, {} as any); assert.strictEqual(invalidDescriptor, undefined); assert.ok(reportedError); From 0a0e60aa6f25231ea836443255001956edde2e59 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 12:25:50 +0800 Subject: [PATCH 4/5] test: cover mid-codepoint UTF-8 frame splits and IPv4 loopback endpoint host Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- test/authenticatedDebugAdapter.test.ts | 6 +++-- test/noConfigDebugStorage.test.ts | 33 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/test/authenticatedDebugAdapter.test.ts b/test/authenticatedDebugAdapter.test.ts index ab405e5c..d98ae569 100644 --- a/test/authenticatedDebugAdapter.test.ts +++ b/test/authenticatedDebugAdapter.test.ts @@ -57,9 +57,11 @@ suite("AuthenticatedSocketDebugAdapter", () => { greeting: "こんにちは🚀", }, }); - // Split across both the \r\n\r\n header terminator AND a multi-byte UTF-8 boundary. + // Split across both the \r\n\r\n header terminator AND the middle of the 4-byte 🚀 UTF-8 sequence. const headerSplit = responseFrame.indexOf("\r\n\r\n") + 2; - const utf8Split = responseFrame.length - 7; + const emojiIndex = responseFrame.indexOf(Buffer.from("🚀", "utf8")); + assert.ok(emojiIndex > headerSplit, "Expected 4-byte emoji after header terminator"); + const utf8Split = emojiIndex + 2; socket.write(responseFrame.subarray(0, headerSplit)); setTimeout(() => { socket.write(responseFrame.subarray(headerSplit, utf8Split)); diff --git a/test/noConfigDebugStorage.test.ts b/test/noConfigDebugStorage.test.ts index 3e893b34..e0214a4e 100644 --- a/test/noConfigDebugStorage.test.ts +++ b/test/noConfigDebugStorage.test.ts @@ -488,4 +488,37 @@ suite("No-Config Debug workspace storage", () => { assert.strictEqual(fs.existsSync(endpoint), false); assert.strictEqual(errors.length, 0); }); + + test("forwards explicit IPv4 loopback client.host to startDebugging attach configuration", async () => { + assert.ok(await register()); + const endpoint = endpointPath(); + const configurations: (vscode.DebugConfiguration | string)[] = []; + replaceProperty(vscode.debug, "startDebugging", async ( + _folder: vscode.WorkspaceFolder | undefined, configuration: vscode.DebugConfiguration | string, + ) => { + configurations.push(configuration); + return true; + }); + const originalUnlink = fs.promises.unlink; + let finishCleanup: () => void = () => { }; + const cleanedUp = new Promise((resolve) => { finishCleanup = resolve; }); + replaceProperty(fs.promises, "unlink", async (file: fs.PathLike) => { + await originalUnlink(file); + finishCleanup(); + }); + + await fs.promises.writeFile(endpoint, JSON.stringify({ client: { host: "127.0.0.1", port: 54322 } })); + created.fire(vscode.Uri.file(endpoint)); + await cleanedUp; + + assert.deepStrictEqual(configurations, [{ + type: "java", + request: "attach", + name: "Attach to Java (No-Config)", + hostName: "127.0.0.1", + port: 54322, + }]); + assert.strictEqual(fs.existsSync(endpoint), false); + assert.strictEqual(errors.length, 0); + }); }); From 7a5314793c4df0ad150a8ed6ec8da23988c1aa9b Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Tue, 1 Dec 2026 16:31:01 +0800 Subject: [PATCH 5/5] feat: add DAP handshake and protocol version telemetry Emit a single `dapAuthHandshake` telemetry event per session from `AuthenticatedSocketDebugAdapter` with outcome, sanitized failure reason/error code, and monotonic `durationMs`, and emit `dapSessionProtocol` (`v2` vs `v1_legacy_fallback`) from `JavaDebugAdapterDescriptorFactory`. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/authenticatedDebugAdapter.ts | 96 ++++++++-- src/javaDebugAdapterDescriptorFactory.ts | 20 +- test/authenticatedDebugAdapter.test.ts | 221 +++++++++++++++++++++++ 3 files changed, 315 insertions(+), 22 deletions(-) diff --git a/src/authenticatedDebugAdapter.ts b/src/authenticatedDebugAdapter.ts index 912ebecb..89855b4b 100644 --- a/src/authenticatedDebugAdapter.ts +++ b/src/authenticatedDebugAdapter.ts @@ -3,6 +3,7 @@ import * as net from "net"; import { DebugAdapter, DebugProtocolMessage, Event, EventEmitter } from "vscode"; +import * as telemetryWrapper from "vscode-extension-telemetry-wrapper"; const AUTH_HEADER_PREFIX = "JavaDebug-Auth: "; const TWO_CRLF = "\r\n\r\n"; @@ -10,6 +11,21 @@ const TWO_CRLF_BYTES = 4; const MAX_HEADER_BYTES = 8 * 1024; const MAX_CONTENT_BYTES = 32 * 1024 * 1024; const CONTENT_LENGTH_PATTERN = /Content-Length:\s*(\d+)/i; +const ERROR_CODE_PATTERN = /^[A-Za-z0-9_]{1,64}$/; + +export type DapAuthHandshakeOutcome = "success" | "failure" | "cancelled"; +export type DapAuthHandshakeFailureReason = + | "closed_before_first_response" + | "socket_error" + | "frame_error" + | "disposed_before_first_response"; + +function sanitizeErrorCode(code: unknown): string | undefined { + if (typeof code !== "string" || code.length === 0) { + return undefined; + } + return ERROR_CODE_PATTERN.test(code) ? code : "UNKNOWN"; +} interface IDapEnvelope { seq?: number; @@ -38,12 +54,16 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { private readonly port: number; private readonly authToken: string; private readonly inFlightRequests = new Map(); + private readonly connectStartHrTime: [number, number]; private socket: net.Socket | undefined; private connected: boolean = false; private socketClosed: boolean = false; private disposed: boolean = false; private terminatedEmitted: boolean = false; + private handshakeTelemetryReported: boolean = false; + private handshakeFailureReason: DapAuthHandshakeFailureReason | undefined; + private handshakeErrorCode: string | undefined; private lastSocketError: Error | undefined; private pendingOutbound: Buffer[] = []; private readChunks: Buffer[] = []; @@ -63,6 +83,7 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { this.authToken = authToken; this.host = normalizeLoopbackHost(host); this.onDidSendMessage = this.sendMessageEmitter.event; + this.connectStartHrTime = process.hrtime(); this.connect(); } @@ -107,6 +128,13 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { return; } this.disposed = true; + if (!this.handshakeTelemetryReported) { + if (this.handshakeFailureReason) { + this.reportHandshakeOutcome("failure", this.handshakeFailureReason); + } else { + this.reportHandshakeOutcome("cancelled", "disposed_before_first_response"); + } + } this.pendingOutbound = []; this.inFlightRequests.clear(); this.readChunks = []; @@ -144,8 +172,14 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { this.handleData(chunk); }); - socket.on("error", (err: Error) => { + socket.on("error", (err: NodeJS.ErrnoException) => { this.lastSocketError = err; + if (!this.handshakeFailureReason) { + this.handshakeFailureReason = "socket_error"; + } + if (!this.handshakeErrorCode) { + this.handshakeErrorCode = sanitizeErrorCode(err && err.code); + } }); socket.on("close", () => { @@ -153,6 +187,7 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { this.socketClosed = true; this.pendingOutbound = []; if (!this.disposed) { + this.reportHandshakeOutcome("failure", this.handshakeFailureReason || "closed_before_first_response"); this.failPendingRequestsAndTerminate(); } }); @@ -179,14 +214,13 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { const parsed = JSON.parse(bodyBytes.toString("utf8")) as IDapEnvelope; if (parsed && parsed.type === "response" && typeof parsed.request_seq === "number") { this.inFlightRequests.delete(parsed.request_seq); + this.reportHandshakeOutcome("success"); } else if (parsed && parsed.type === "event" && parsed.event === "terminated") { this.terminatedEmitted = true; } this.sendMessageEmitter.fire(parsed as unknown as DebugProtocolMessage); } catch (_err) { - if (this.socket) { - this.socket.destroy(); - } + this.failWithFrameError("Debug adapter response contained invalid JSON."); break; } continue; @@ -200,19 +234,13 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { const headerEnd = headerWindow.indexOf(TWO_CRLF); if (headerEnd === -1) { if (this.bufferedBytes > MAX_HEADER_BYTES) { - this.lastSocketError = new Error("Debug adapter response header exceeded maximum length."); - if (this.socket) { - this.socket.destroy(); - } + this.failWithFrameError("Debug adapter response header exceeded maximum length."); } break; } if (headerEnd + TWO_CRLF_BYTES > MAX_HEADER_BYTES) { - this.lastSocketError = new Error("Debug adapter response header exceeded maximum length."); - if (this.socket) { - this.socket.destroy(); - } + this.failWithFrameError("Debug adapter response header exceeded maximum length."); break; } @@ -221,19 +249,13 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { const match = CONTENT_LENGTH_PATTERN.exec(header); if (!match) { - this.lastSocketError = new Error("Debug adapter response missing Content-Length header."); - if (this.socket) { - this.socket.destroy(); - } + this.failWithFrameError("Debug adapter response missing Content-Length header."); break; } const parsedLength = Number.parseInt(match[1], 10); if (!Number.isSafeInteger(parsedLength) || parsedLength < 0 || parsedLength > MAX_CONTENT_BYTES) { - this.lastSocketError = new Error(`Debug adapter Content-Length out of bounds: ${match[1]}`); - if (this.socket) { - this.socket.destroy(); - } + this.failWithFrameError(`Debug adapter Content-Length out of bounds: ${match[1]}`); break; } @@ -241,6 +263,40 @@ export class AuthenticatedSocketDebugAdapter implements DebugAdapter { } } + private failWithFrameError(errorMessage: string): void { + if (!this.handshakeFailureReason) { + this.handshakeFailureReason = "frame_error"; + } + this.lastSocketError = new Error(errorMessage); + if (this.socket) { + this.socket.destroy(); + } + } + + private reportHandshakeOutcome(outcome: DapAuthHandshakeOutcome, reason?: DapAuthHandshakeFailureReason): void { + if (this.handshakeTelemetryReported) { + return; + } + this.handshakeTelemetryReported = true; + const elapsed = process.hrtime(this.connectStartHrTime); + const durationMs = Math.max(0, Math.round(elapsed[0] * 1000 + elapsed[1] / 1e6)); + const properties: { [key: string]: string } = { + operationName: "dapAuthHandshake", + outcome, + }; + if (reason) { + properties.reason = reason; + } + if (outcome === "failure" && reason === "socket_error" && this.handshakeErrorCode) { + properties.errorCode = this.handshakeErrorCode; + } + try { + telemetryWrapper.sendInfo("", properties, { durationMs }); + } catch (_err) { + // Telemetry must never interfere with debug adapter execution. + } + } + private peekPrefix(maxBytes: number): Buffer { const targetLength = Math.min(this.bufferedBytes, maxBytes); if (targetLength === 0) { diff --git a/src/javaDebugAdapterDescriptorFactory.ts b/src/javaDebugAdapterDescriptorFactory.ts index 2e3d6e87..e787ba81 100644 --- a/src/javaDebugAdapterDescriptorFactory.ts +++ b/src/javaDebugAdapterDescriptorFactory.ts @@ -9,11 +9,14 @@ import { DebugAdapterServer, DebugSession, } from "vscode"; +import * as telemetryWrapper from "vscode-extension-telemetry-wrapper"; import { AuthenticatedSocketDebugAdapter, normalizeLoopbackHost } from "./authenticatedDebugAdapter"; import { Type } from "./javaLogger"; import { IDebugSessionDescriptor, startDebugSession } from "./languageServerPlugin"; import { convertErrorToMessage, showErrorMessageWithTroubleshooting } from "./utility"; +export type DebugSessionProtocol = "v2" | "v1_legacy_fallback"; + export class JavaDebugAdapterDescriptorFactory implements DebugAdapterDescriptorFactory { public async createDebugAdapterDescriptor(_session: DebugSession, _executable: DebugAdapterExecutable): Promise { @@ -22,9 +25,11 @@ export class JavaDebugAdapterDescriptorFactory implements DebugAdapterDescriptor const sessionDescriptor = await startDebugSession(); if (isAuthenticatedSessionDescriptor(sessionDescriptor)) { const host = normalizeLoopbackHost(sessionDescriptor.host || "127.0.0.1"); - return new DebugAdapterInlineImplementation( - new AuthenticatedSocketDebugAdapter(sessionDescriptor.port, sessionDescriptor.authToken, host)); + const adapter = new AuthenticatedSocketDebugAdapter(sessionDescriptor.port, sessionDescriptor.authToken, host); + recordSessionProtocol("v2"); + return new DebugAdapterInlineImplementation(adapter); } else if (typeof sessionDescriptor === "number" && sessionDescriptor > 0) { + recordSessionProtocol("v1_legacy_fallback"); return new DebugAdapterServer(sessionDescriptor, "127.0.0.1"); } else { // Information for diagnostic: @@ -44,6 +49,17 @@ export class JavaDebugAdapterDescriptorFactory implements DebugAdapterDescriptor } } +function recordSessionProtocol(protocol: DebugSessionProtocol): void { + try { + telemetryWrapper.sendInfo("", { + operationName: "dapSessionProtocol", + protocol, + }); + } catch (_err) { + // Telemetry must never interfere with debug session startup. + } +} + function isAuthenticatedSessionDescriptor(value: unknown): value is IDebugSessionDescriptor { if (typeof value !== "object" || value === null) { return false; diff --git a/test/authenticatedDebugAdapter.test.ts b/test/authenticatedDebugAdapter.test.ts index d98ae569..931a8d2b 100644 --- a/test/authenticatedDebugAdapter.test.ts +++ b/test/authenticatedDebugAdapter.test.ts @@ -12,6 +12,7 @@ import { DebugAdapterServer, DebugProtocolMessage, } from "vscode"; +import * as telemetryWrapper from "vscode-extension-telemetry-wrapper"; import { AuthenticatedSocketDebugAdapter } from "../src/authenticatedDebugAdapter"; import { JavaDebugAdapterDescriptorFactory } from "../src/javaDebugAdapterDescriptorFactory"; @@ -293,4 +294,224 @@ suite("AuthenticatedSocketDebugAdapter", () => { fs.rmSync(tempDir, { recursive: true, force: true }); } }); + + test("emits a single dapAuthHandshake success event with durationMs and no token or payload", async () => { + const recorded: { operationId: string; properties: any; measurements: any }[] = []; + const origSendInfo = telemetryWrapper.sendInfo; + (telemetryWrapper as any).sendInfo = (operationId: string, properties: any, measurements?: any) => { + recorded.push({ operationId, properties, measurements }); + }; + + const server = net.createServer((socket) => { + let buf = ""; + socket.on("data", (chunk: Buffer) => { + buf += chunk.toString("utf8"); + if (buf.includes("\"command\":\"initialize\"")) { + buf = ""; + socket.write(frameDapMessage({ + seq: 1, + type: "response", + request_seq: 1, + success: true, + command: "initialize", + })); + socket.write(frameDapMessage({ + seq: 2, + type: "response", + request_seq: 2, + success: true, + command: "configurationDone", + })); + } + }); + }); + + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const port = (server.address() as net.AddressInfo).port; + const adapter = new AuthenticatedSocketDebugAdapter(port, VALID_TOKEN, "127.0.0.1"); + + try { + let responsesSeen = 0; + const bothResponses = new Promise((resolve) => { + adapter.onDidSendMessage((msg: DebugProtocolMessage) => { + if ((msg as any).type === "response") { + responsesSeen++; + if (responsesSeen === 2) { + resolve(); + } + } + }); + }); + adapter.handleMessage({ + seq: 1, + type: "request", + command: "initialize", + arguments: {}, + } as unknown as DebugProtocolMessage); + await bothResponses; + + // Dispose after success must not emit a duplicate telemetry event. + adapter.dispose(); + + const handshakeEvents = recorded.filter((e) => e.properties && e.properties.operationName === "dapAuthHandshake"); + assert.strictEqual(handshakeEvents.length, 1); + assert.strictEqual(handshakeEvents[0].properties.outcome, "success"); + assert.strictEqual(handshakeEvents[0].properties.reason, undefined); + assert.strictEqual(handshakeEvents[0].properties.errorCode, undefined); + assert.strictEqual(typeof handshakeEvents[0].measurements.durationMs, "number"); + assert.ok(handshakeEvents[0].measurements.durationMs >= 0); + const serialized = JSON.stringify(handshakeEvents[0]); + assert.ok(!serialized.includes(VALID_TOKEN), "Telemetry must not contain auth token."); + } finally { + adapter.dispose(); + (telemetryWrapper as any).sendInfo = origSendInfo; + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + test("emits a single dapAuthHandshake failure event for closed_before_first_response, socket_error, and frame_error", async () => { + const recorded: { operationId: string; properties: any; measurements: any }[] = []; + const origSendInfo = telemetryWrapper.sendInfo; + (telemetryWrapper as any).sendInfo = (operationId: string, properties: any, measurements?: any) => { + recorded.push({ operationId, properties, measurements }); + }; + + try { + // 1. Clean FIN before first response -> closed_before_first_response. + const finServer = net.createServer((socket) => { + socket.resume(); + socket.end(); + }); + await new Promise((resolve) => finServer.listen(0, "127.0.0.1", () => resolve())); + const finPort = (finServer.address() as net.AddressInfo).port; + const finAdapter = new AuthenticatedSocketDebugAdapter(finPort, VALID_TOKEN, "127.0.0.1"); + try { + await new Promise((resolve) => { + finAdapter.onDidSendMessage((msg: DebugProtocolMessage) => { + if ((msg as any).type === "event" && (msg as any).event === "terminated") { + resolve(); + } + }); + }); + } finally { + finAdapter.dispose(); + await new Promise((resolve) => finServer.close(() => resolve())); + } + let events = recorded.filter((e) => e.properties && e.properties.operationName === "dapAuthHandshake"); + assert.strictEqual(events.length, 1); + assert.strictEqual(events[0].properties.outcome, "failure"); + assert.strictEqual(events[0].properties.reason, "closed_before_first_response"); + assert.strictEqual(typeof events[0].measurements.durationMs, "number"); + + // 2. Connection refused -> socket_error + ECONNREFUSED. + recorded.length = 0; + const closedServer = net.createServer(); + await new Promise((resolve) => closedServer.listen(0, "127.0.0.1", () => resolve())); + const refusedPort = (closedServer.address() as net.AddressInfo).port; + await new Promise((resolve) => closedServer.close(() => resolve())); + + const refusedAdapter = new AuthenticatedSocketDebugAdapter(refusedPort, VALID_TOKEN, "127.0.0.1"); + try { + await new Promise((resolve) => { + refusedAdapter.onDidSendMessage((msg: DebugProtocolMessage) => { + if ((msg as any).type === "event" && (msg as any).event === "terminated") { + resolve(); + } + }); + }); + } finally { + refusedAdapter.dispose(); + } + events = recorded.filter((e) => e.properties && e.properties.operationName === "dapAuthHandshake"); + assert.strictEqual(events.length, 1); + assert.strictEqual(events[0].properties.outcome, "failure"); + assert.strictEqual(events[0].properties.reason, "socket_error"); + assert.strictEqual(events[0].properties.errorCode, "ECONNREFUSED"); + assert.strictEqual(typeof events[0].measurements.durationMs, "number"); + + // 3. Invalid JSON frame before first response -> frame_error. + recorded.length = 0; + const badFrameServer = net.createServer((socket) => { + socket.once("data", () => { + const invalidJson = "{not-valid-json"; + socket.write(Buffer.from(`Content-Length: ${Buffer.byteLength(invalidJson)}\r\n\r\n${invalidJson}`, "utf8")); + }); + }); + await new Promise((resolve) => badFrameServer.listen(0, "127.0.0.1", () => resolve())); + const badFramePort = (badFrameServer.address() as net.AddressInfo).port; + const badFrameAdapter = new AuthenticatedSocketDebugAdapter(badFramePort, VALID_TOKEN, "127.0.0.1"); + try { + await new Promise((resolve) => { + badFrameAdapter.onDidSendMessage((msg: DebugProtocolMessage) => { + if ((msg as any).type === "event" && (msg as any).event === "terminated") { + resolve(); + } + }); + }); + } finally { + badFrameAdapter.dispose(); + await new Promise((resolve) => badFrameServer.close(() => resolve())); + } + events = recorded.filter((e) => e.properties && e.properties.operationName === "dapAuthHandshake"); + assert.strictEqual(events.length, 1); + assert.strictEqual(events[0].properties.outcome, "failure"); + assert.strictEqual(events[0].properties.reason, "frame_error"); + assert.strictEqual(typeof events[0].measurements.durationMs, "number"); + } finally { + (telemetryWrapper as any).sendInfo = origSendInfo; + } + }); + + test("JavaDebugAdapterDescriptorFactory records v2 and v1_legacy_fallback protocol telemetry", async () => { + const server = net.createServer((socket) => socket.destroy()); + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + const port = (server.address() as net.AddressInfo).port; + + const origStart = languageServerPlugin.startDebugSession; + const origShowErr = utility.showErrorMessageWithTroubleshooting; + const origSendInfo = telemetryWrapper.sendInfo; + const protocolEvents: string[] = []; + + try { + (utility as any).showErrorMessageWithTroubleshooting = () => { /* noop */ }; + (telemetryWrapper as any).sendInfo = (_operationId: string, properties: any) => { + if (properties && properties.operationName === "dapSessionProtocol") { + protocolEvents.push(properties.protocol); + } + }; + + const factory = new JavaDebugAdapterDescriptorFactory(); + + (languageServerPlugin as any).startDebugSession = async () => ({ + protocolVersion: 2, + host: "127.0.0.1", + port, + authToken: VALID_TOKEN, + }); + const v2Descriptor = await factory.createDebugAdapterDescriptor({} as any, {} as any); + assert.ok(v2Descriptor instanceof DebugAdapterInlineImplementation); + ((v2Descriptor as any).implementation as AuthenticatedSocketDebugAdapter).dispose(); + + (languageServerPlugin as any).startDebugSession = async () => port; + const legacyDescriptor = await factory.createDebugAdapterDescriptor({} as any, {} as any); + assert.ok(legacyDescriptor instanceof DebugAdapterServer); + + // Rejected non-loopback descriptor must not record a protocol usage event. + (languageServerPlugin as any).startDebugSession = async () => ({ + protocolVersion: 2, + host: "10.0.0.8", + port, + authToken: VALID_TOKEN, + }); + const rejectedDescriptor = await factory.createDebugAdapterDescriptor({} as any, {} as any); + assert.strictEqual(rejectedDescriptor, undefined); + + assert.deepStrictEqual(protocolEvents, ["v2", "v1_legacy_fallback"]); + } finally { + (languageServerPlugin as any).startDebugSession = origStart; + (utility as any).showErrorMessageWithTroubleshooting = origShowErr; + (telemetryWrapper as any).sendInfo = origSendInfo; + await new Promise((resolve) => server.close(() => resolve())); + } + }); });