diff --git a/src/vs/code/electron-main/main.ts b/src/vs/code/electron-main/main.ts index 93527ec8a9ebb1..1558e83e7528d0 100644 --- a/src/vs/code/electron-main/main.ts +++ b/src/vs/code/electron-main/main.ts @@ -6,6 +6,7 @@ import '../../platform/update/common/update.config.contribution.js'; import { app, dialog } from 'electron'; +import { RemoteConnectionTokenError } from '../../platform/remote/node/remoteConnectionToken.js'; import { unlinkSync, promises } from 'fs'; import { URI } from '../../base/common/uri.js'; import { coalesce, distinct } from '../../base/common/arrays.js'; @@ -92,12 +93,15 @@ import { LINUX_SYSTEM_POLICY_FILE_PATH } from '../../base/common/policy.js'; class CodeMain { main(): void { - try { - this.startup(); - } catch (error) { + this.startup().catch(async error => { + if (!(error instanceof RemoteConnectionTokenError)) { + throw error; + } console.error(error.message); + await app.whenReady(); + dialog.showErrorBox(product.nameLong, error.message); app.exit(1); - } + }); } private async startup(): Promise { diff --git a/src/vs/code/node/cli.ts b/src/vs/code/node/cli.ts index 994f6c38d99bbc..d85abdbc1d8c9d 100644 --- a/src/vs/code/node/cli.ts +++ b/src/vs/code/node/cli.ts @@ -21,6 +21,7 @@ import { combineUriFlags } from './cliArgs.js'; import { getStdinFilePath, hasStdinWithoutTty, readFromStdin, stdinDataListener } from '../../platform/environment/node/stdin.js'; import { createWaitMarkerFileSync } from '../../platform/environment/node/wait.js'; import product from '../../platform/product/common/product.js'; +import { RemoteConnectionTokenFile, RemoteConnectionTokenError } from '../../platform/remote/node/remoteConnectionToken.js'; import { CancellationTokenSource } from '../../base/common/cancellation.js'; import { isUNC, randomPath } from '../../base/common/extpath.js'; import { Utils } from '../../platform/profiling/common/profiling.js'; @@ -46,7 +47,13 @@ export async function main(argv: string[]): Promise { try { args = parseCLIProcessArgv(argv); + if (!args.help && !args.version) { + await RemoteConnectionTokenFile.read(args); + } } catch (err) { + if (err instanceof RemoteConnectionTokenError) { + throw err; + } console.error(err.message); return; } diff --git a/src/vs/platform/environment/common/argv.ts b/src/vs/platform/environment/common/argv.ts index cb471c169f24de..562664eef33f34 100644 --- a/src/vs/platform/environment/common/argv.ts +++ b/src/vs/platform/environment/common/argv.ts @@ -133,6 +133,7 @@ export interface NativeParsedArgs { 'enable-smoke-test-driver'?: boolean; 'skip-sessions-welcome'?: boolean; 'remote'?: string; + 'remote-token-file'?: string; 'force'?: boolean; 'do-not-sync'?: boolean; 'preserve-env'?: boolean; diff --git a/src/vs/platform/environment/node/argv.ts b/src/vs/platform/environment/node/argv.ts index d47b595bcf6f2b..955dd75ec81247 100644 --- a/src/vs/platform/environment/node/argv.ts +++ b/src/vs/platform/environment/node/argv.ts @@ -160,6 +160,7 @@ export const OPTIONS: OptionDescriptions> = { 'telemetry': { type: 'boolean', cat: 't', description: localize('telemetry', "Shows all telemetry events which VS code collects.") }, 'remote': { type: 'string', allowEmptyValue: true }, + 'remote-token-file': { type: 'string', allowEmptyValue: true, cat: 'o', args: 'path', description: localize('remoteConnectionTokenFile', "Read the authentication token for a direct --remote host:port connection from an absolute local file path.") }, 'folder-uri': { type: 'string[]', cat: 'o', args: 'uri' }, 'file-uri': { type: 'string[]', cat: 'o', args: 'uri' }, diff --git a/src/vs/platform/environment/node/argvHelper.ts b/src/vs/platform/environment/node/argvHelper.ts index 8927472c2bdf38..963592e6727fd6 100644 --- a/src/vs/platform/environment/node/argvHelper.ts +++ b/src/vs/platform/environment/node/argvHelper.ts @@ -8,6 +8,7 @@ import { dirname, resolve } from '../../../base/common/path.js'; import { IProcessEnvironment, isWindows } from '../../../base/common/platform.js'; import { localize } from '../../../nls.js'; import { NativeParsedArgs } from '../common/argv.js'; +import { validateRemoteConnectionTokenArguments } from '../../remote/node/remoteConnectionToken.js'; import { ErrorReporter, NATIVE_CLI_COMMANDS, OPTIONS, parseArgs } from './argv.js'; function parseAndValidate(cmdLineArgs: string[], reportWarnings: boolean): NativeParsedArgs { @@ -46,6 +47,7 @@ function parseAndValidate(cmdLineArgs: string[], reportWarnings: boolean): Nativ args._.forEach(arg => assert(/^(\w:)?[^:]+(:\d*){0,2}:?$/.test(arg), localize('gotoValidation', "Arguments in `--goto` mode should be in the format of `FILE(:LINE(:CHARACTER))`."))); } + validateRemoteConnectionTokenArguments(args); return args; } @@ -116,3 +118,33 @@ export function addArg(argv: string[], ...args: string[]): string[] { export function isLaunchedFromCli(env: IProcessEnvironment): boolean { return env['VSCODE_CLI'] === '1'; } + +/** On relaunch, restore the session rather than replaying a launcher's transient remote target. */ +export function stripRemoteConnectionTokenLaunchArgs(argv: string[], isDevelopment: boolean): string[] { + const appIndex = isDevelopment ? argv.findIndex(arg => !arg.startsWith('-')) : -1; + const launchArgs = argv.filter((_arg, index) => index !== appIndex); + // Parse once with the same option definitions as the CLI. Never infer whether an + // unknown Chromium switch consumes the remote path that follows it. + const endOfOptions = launchArgs.indexOf('--'); + const parsed = parseArgs(endOfOptions === -1 ? launchArgs : launchArgs.slice(0, endOfOptions), OPTIONS); + if (parsed['remote-token-file'] === undefined) { + return argv; + } + + const result = appIndex === -1 ? [] : [argv[appIndex]]; + const launchOptions = new Set(['_', 'remote', 'remote-token-file', 'new-window', 'reuse-window', 'wait', 'waitMarkerFilePath', 'diff', 'merge', 'goto', 'profile', 'profile-temp']); + for (const key of Object.keys(OPTIONS) as (keyof NativeParsedArgs)[]) { + if (launchOptions.has(key)) { + continue; + } + const value = parsed[key]; + if (typeof value === 'string') { + result.push(`--${key}=${value}`); + } else if (value === true) { + result.push(`--${key}`); + } else if (Array.isArray(value)) { + result.push(...value.map(value => `--${key}=${value}`)); + } + } + return result; +} diff --git a/src/vs/platform/environment/test/node/argv.test.ts b/src/vs/platform/environment/test/node/argv.test.ts index 7f1bd2ae106f0a..fe2143b2336647 100644 --- a/src/vs/platform/environment/test/node/argv.test.ts +++ b/src/vs/platform/environment/test/node/argv.test.ts @@ -6,7 +6,7 @@ import assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; import { formatOptions, Option, OptionDescriptions, Subcommand, parseArgs, ErrorReporter } from '../../node/argv.js'; -import { addArg } from '../../node/argvHelper.js'; +import { addArg, stripRemoteConnectionTokenLaunchArgs } from '../../node/argvHelper.js'; function o(description: string, type: 'boolean' | 'string' | 'string[]' = 'string'): Option { return { @@ -220,3 +220,54 @@ suite('parseArgs', () => { ensureNoDisposablesAreLeakedInTestSuite(); }); + + +suite('Remote token relaunch arguments', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('unrelated launches are unchanged', () => { + const args = ['--remote', 'ssh-remote+host', '-r', '/project']; + assert.strictEqual(stripRemoteConnectionTokenLaunchArgs(args, false), args); + }); + + test('drops transient target and window flags, retaining application options and their values', () => { + assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([ + '--user-data-dir', '/profile', '--remote', 'localhost:8000', '--remote-token-file', '/token', + '-r', '-w', '--waitMarkerFilePath', '/wait', '--log', 'trace', '/remote/project', '--locale=fr' + ], false), ['--locale=fr', '--user-data-dir=/profile', '--log=trace']); + }); + + test('handles equals syntax and end of options without converting remote paths to local paths', () => { + assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([ + '--remote=localhost:8000', '--remote-token-file=/token', '--profile', 'Work', '--locale=fr', '--', '-remote-path' + ], false), ['--locale=fr']); + }); + + test('removes grouped short window flags', () => { + assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([ + '-nr', '--remote=localhost:8000', '--remote-token-file=/token', '/project' + ], false), []); + }); + + test('does not retain remote paths consumed by unknown Chromium switches', () => { + for (const option of ['--some-chromium-switch', '--some-chromium-switch=value']) { + assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([ + '--remote', '127.0.0.1:9000', '--remote-token-file', '/t', option, '/remote/project' + ], false), []); + } + }); + + test('preserves declared Chromium switches and repeated option values', () => { + assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([ + '--remote=localhost:8000', '--remote-token-file=/token', '--no-sandbox', + '--proxy-server=http://localhost:8080', '--disable-extension=a', '--disable-extension=b', + '--', '--disable-gpu' + ], false), ['--disable-extension=a', '--disable-extension=b', '--no-sandbox', '--proxy-server=http://localhost:8080']); + }); + + test('preserves the development application path', () => { + assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([ + '.', '--remote', 'localhost:8000', '--remote-token-file', '/token', '/remote/project', '--verbose' + ], true), ['.', '--verbose']); + }); +}); diff --git a/src/vs/platform/launch/electron-main/launchMainService.ts b/src/vs/platform/launch/electron-main/launchMainService.ts index 4fe6a02db846f2..b43768570ac681 100644 --- a/src/vs/platform/launch/electron-main/launchMainService.ts +++ b/src/vs/platform/launch/electron-main/launchMainService.ts @@ -181,11 +181,12 @@ export class LaunchMainService implements ILaunchMainService { } } - // Open new Window - if (openNewWindow) { + // Token-bearing launches must load the target, even when an existing window can be reused. + if (openNewWindow || args['remote-token-file'] !== undefined) { usedWindows = await this.windowsMainService.open({ ...baseConfig, - forceNewWindow: true, + forceNewWindow: openNewWindow || !args['reuse-window'], + forceReuseWindow: openNewWindow ? undefined : args['reuse-window'], forceEmpty: true }); } diff --git a/src/vs/platform/lifecycle/electron-main/lifecycleMainService.ts b/src/vs/platform/lifecycle/electron-main/lifecycleMainService.ts index f039180c9d116b..10eab2bfcfd8b8 100644 --- a/src/vs/platform/lifecycle/electron-main/lifecycleMainService.ts +++ b/src/vs/platform/lifecycle/electron-main/lifecycleMainService.ts @@ -11,6 +11,7 @@ import { Disposable, DisposableStore } from '../../../base/common/lifecycle.js'; import { isMacintosh, isWindows } from '../../../base/common/platform.js'; import { cwd } from '../../../base/common/process.js'; import { assertReturnsDefined } from '../../../base/common/types.js'; +import { stripRemoteConnectionTokenLaunchArgs } from '../../environment/node/argvHelper.js'; import { NativeParsedArgs } from '../../environment/common/argv.js'; import { createDecorator } from '../../instantiation/common/instantiation.js'; import { ILogService } from '../../log/common/log.js'; @@ -681,7 +682,8 @@ export class LifecycleMainService extends Disposable implements ILifecycleMainSe async relaunch(options?: IRelaunchOptions): Promise { this.trace('Lifecycle#relaunch()'); - const args = process.argv.slice(1); + const originalArgs = process.argv.slice(1); + const args = stripRemoteConnectionTokenLaunchArgs(originalArgs, !this.environmentMainService.isBuilt); if (options?.addArgs) { args.push(...options.addArgs); } @@ -696,7 +698,8 @@ export class LifecycleMainService extends Disposable implements ILifecycleMainSe } const quitListener = () => { - if (!this.relaunchHandler?.handleRelaunch(options)) { + // Update handlers cannot honor rewritten launch arguments. + if (args !== originalArgs || !this.relaunchHandler?.handleRelaunch(options)) { this.trace('Lifecycle#relaunch() - calling app.relaunch()'); electron.app.relaunch({ args }); } diff --git a/src/vs/platform/native/common/native.ts b/src/vs/platform/native/common/native.ts index 1d3db80842650c..0be4d5ac9d7bd3 100644 --- a/src/vs/platform/native/common/native.ts +++ b/src/vs/platform/native/common/native.ts @@ -555,6 +555,8 @@ export interface ICommonNativeHostService { startTracing(categories: string, options?: IStartTracingOptions): Promise; // Connectivity + /** Returns only the calling window's credential for its current remote address. */ + getRemoteConnectionToken(authority: string): Promise; resolveProxy(url: string): Promise; resolveProxyWithPackage(url: string): Promise; readProxyConfigWithPackage(): Promise; diff --git a/src/vs/platform/native/electron-main/nativeHostMainService.ts b/src/vs/platform/native/electron-main/nativeHostMainService.ts index 191c073bc1072b..d659ec6f16ca11 100644 --- a/src/vs/platform/native/electron-main/nativeHostMainService.ts +++ b/src/vs/platform/native/electron-main/nativeHostMainService.ts @@ -1430,6 +1430,13 @@ export class NativeHostMainService extends Disposable implements INativeHostMain //#region Connectivity + async getRemoteConnectionToken(windowId: number | undefined, authority: string): Promise { + if (windowId === undefined) { + throw new Error(localize('remoteTokenWindow', "A remote connection token requires a window.")); + } + return this.windowsMainService.getRemoteConnectionToken(windowId, authority); + } + async resolveProxy(windowId: number | undefined, url: string): Promise { const window = this.codeWindowById(windowId); const session = window?.win?.webContents?.session; diff --git a/src/vs/platform/remote/README.md b/src/vs/platform/remote/README.md new file mode 100644 index 00000000000000..dadfe4c928d984 --- /dev/null +++ b/src/vs/platform/remote/README.md @@ -0,0 +1,41 @@ + + +# Direct desktop remote connections + +External launchers can connect the desktop editor to a compatible VS Code server without a resolver extension: + +```sh +code --remote 127.0.0.1:PORT --remote-token-file /absolute/path/to/token /remote/project +``` + +The launcher owns server installation and version matching, server authentication, transport security (for example, an SSH tunnel), and the local token file. Configure the server to require the same token. Protect the local file from other users. VS Code neither creates nor deletes it. + +The option requires an absolute local file path and a direct `host:port` authority, including bracketed IPv6 addresses. The token must be non-empty and contain only `0-9`, `a-z`, `A-Z`, `_`, or `-`, with at most one trailing LF or CRLF, matching the server's token-file format. Spaces, a byte-order mark, additional lines, and an empty file are rejected. Missing, unreadable, or invalid files fail the CLI’s initial validation or, when encountered during authority resolution, produce a connection error in the target window. VS Code does not retry without authentication. + +Resolver-extension authorities (such as `ssh-remote+host`), URI arguments, add/remove-folder operations, extension development, chat, and command-line-only operations cannot be combined with this option. Existing non-loopback host confirmation and remote-host security checks still apply. Authentication does not encrypt the direct connection; the launcher must provide any required secure transport. + +## Credential lifetime + +The CLI validates the file locally. When a launch is forwarded to a running editor process, only the file path is forwarded. The target window reads and validates the file during authority resolution. Keep the protected file available for initial authority resolution and any window reloads. A late read failure is reported as a connection error in the target window; it does not abort application startup or close unrelated windows. The normal detached CLI exit does not acknowledge that the window has connected. + +The main process retains the file path in memory, scoped to the target window and remote authority (using the same case-insensitive authority comparison as window lookup). It reads the current token during authority resolution, including on window reload. Ordinary network reconnections reuse the resolved token for the session. Reopening a target with the same file path does not force a reload if no file-resolution failure was recorded. A different file path, a missing binding, or recovery from a file-resolution failure loads the target again, subject to the usual unload veto. Replacing the contents of the file takes effect the next time the authority is resolved, such as on window reload. After repairing a server authentication failure, reload the window to retry. Reusing the window for a different remote destination or a local workspace drops the credential. Other windows do not inherit it. A token-bearing launch opens only its requested targets; it does not also restore unrelated session windows. Without a project path it opens a new empty remote window unless `--reuse-window` is explicitly requested. + +Session state stores only a non-secret indication that a window requires a token. After exiting and starting without the option, such a restored window refuses to connect and asks for another launch with the token file. Reusing that address and workspace for a server without authentication does not automatically clear this requirement; an explicit reset policy remains a maintainer decision. Neither the token nor the file path is stored in workspace settings, recent history, or window session state. A built-in application relaunch removes the original token-file and remote-address options, remote project paths, and launch-only window flags, allowing normal session restoration. Remaining arguments are rebuilt from the desktop CLI’s declared options; unknown Chromium switches are not retained. Relaunches that rewrite these arguments bypass pending-update handlers that cannot honor the changed arguments. Restored authenticated windows require a new launch with the token file; unrelated windows restore according to the existing settings. Launches forwarded to an existing process are not added to its original command line. External launchers should always pass both options when restarting their environment. + +The direct connection supplies the token through the existing remote authentication handshake. It is not embedded in the remote authority or workspace URI. Wrong-token rejection comes from the server's existing authentication mechanism. When the option is absent, connections that have no saved authentication requirement and resolver extensions retain their existing behavior. + +## Tests + +Token-file parsing, window credential bindings, restart arguments, and direct authority resolution are covered by the existing unit runners: + +```sh +npm run test-node -- --run src/vs/platform/remote/test/node/remoteConnectionToken.test.ts --run src/vs/platform/remote/test/common/connectionToken.test.ts --run src/vs/platform/environment/test/node/argv.test.ts --run src/vs/server/test/node/serverConnectionToken.test.ts --run src/vs/workbench/services/extensions/test/common/directRemoteAuthority.test.ts +scripts/test.sh --run src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts +``` + +These helper tests do not exercise the complete desktop launch, IPC, window-reuse, or application-restart flow. Those flows still need manual integration validation. + +On headless Linux, run the Electron tests under `xvfb-run -a`. If `ELECTRON_RUN_AS_NODE` is set in the shell, unset it for the test runner. Containers with limited shared memory may also need `--disable-dev-shm-usage`. diff --git a/src/vs/platform/remote/common/connectionToken.ts b/src/vs/platform/remote/common/connectionToken.ts new file mode 100644 index 00000000000000..57d97fa911a66e --- /dev/null +++ b/src/vs/platform/remote/common/connectionToken.ts @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** Whether a value is a non-empty token in the remote protocol's ASCII alphabet. */ +export function isValidConnectionToken(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && !/[^0-9A-Za-z_-]/.test(value); +} + +/** Parse a token file, allowing exactly one optional trailing LF or CRLF. */ +export function parseConnectionTokenFile(contents: string): string | undefined { + const token = contents.replace(/\r?\n$/, ''); + return isValidConnectionToken(token) ? token : undefined; +} diff --git a/src/vs/platform/remote/node/remoteConnectionToken.ts b/src/vs/platform/remote/node/remoteConnectionToken.ts new file mode 100644 index 00000000000000..9cb9c627113270 --- /dev/null +++ b/src/vs/platform/remote/node/remoteConnectionToken.ts @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { promises as fs } from 'fs'; +import { isEqualAuthority } from '../../../base/common/resources.js'; +import { isAbsolute } from '../../../base/common/path.js'; +import { localize } from '../../../nls.js'; +import { parseConnectionTokenFile } from '../common/connectionToken.js'; +import { NativeParsedArgs } from '../../environment/common/argv.js'; + +/** A launch or connection failure that must never fall back to an unauthenticated connection. */ +export class RemoteConnectionTokenError extends Error { } + +/** Validate before dispatching to window, URL or command-line-only handlers. */ +export function validateRemoteConnectionTokenArguments(args: NativeParsedArgs): void { + const file = args['remote-token-file']; + if (file === undefined) { + return; + } + const authority = args.remote; + const match = authority?.match(/^(?:\[[0-9a-fA-F:]+\]|[a-zA-Z0-9._-]+):(?[0-9]+)$/); + if (!file || !isAbsolute(file) || !match || Number(match.groups!.port) < 1 || Number(match.groups!.port) > 65535) { + throw new RemoteConnectionTokenError(localize('remoteTokenArguments', "--remote-token-file requires an absolute local file path and --remote host:port (port 1-65535).")); + } + const incompatibleOptions: (keyof NativeParsedArgs)[] = [ + 'open-url', 'add', 'remove', 'folder-uri', 'file-uri', 'extensionDevelopmentPath', 'extensionTestsPath', + 'chat', 'tunnel', 'serve-web', 'agents', 'agent', 'install-source', 'install-builtin-extension', 'file-write', + 'locate-shell-integration-path', 'status', 'install-extension', 'uninstall-extension', 'list-extensions', + 'update-extensions', 'locate-extension', 'add-mcp', 'telemetry' + ]; + if (incompatibleOptions.some(option => args[option])) { + throw new RemoteConnectionTokenError(localize('remoteTokenIncompatibleArguments', "--remote-token-file cannot be combined with URL, folder modification, extension development, chat, agents, or command-line-only operations.")); + } +} + +/** A local credential source. Only its path is retained; each resolution reads the current token. */ +export class RemoteConnectionTokenFile { + private constructor(readonly authority: string, private readonly path: string) { } + + static fromArgs(args: NativeParsedArgs): RemoteConnectionTokenFile | undefined { + validateRemoteConnectionTokenArguments(args); + const file = args['remote-token-file']; + return file === undefined ? undefined : new RemoteConnectionTokenFile(args.remote!, file); + } + + static async read(args: NativeParsedArgs): Promise { + const source = RemoteConnectionTokenFile.fromArgs(args); + await source?.getValue(source.authority); + return source; + } + + validateAuthority(authority: string): void { + if (!isEqualAuthority(authority, this.authority)) { + throw new RemoteConnectionTokenError(localize('remoteTokenDestination', "The remote connection token file does not belong to this remote address.")); + } + } + + isSameSource(other: RemoteConnectionTokenFile): boolean { + return isEqualAuthority(this.authority, other.authority) && this.path === other.path; + } + + async getValue(authority: string): Promise { + this.validateAuthority(authority); + let token: string | undefined; + try { + token = parseConnectionTokenFile(await fs.readFile(this.path, 'utf8')); + } catch { + throw new RemoteConnectionTokenError(localize('remoteTokenRead', "Unable to read the local remote connection token file. Keep the file available for the duration of the remote session.")); + } + if (token === undefined) { + throw new RemoteConnectionTokenError(localize('remoteTokenInvalid', "The remote connection token file must contain a non-empty token using only 0-9, a-z, A-Z, _, or -, optionally followed by one newline.")); + } + return token; + } +} + +/** Main-process credential sources scoped to a window and destination, never persisted. */ +export class WindowRemoteConnectionTokens { + readonly #windows = new WeakMap(); + + bind(window: T, authority: string | undefined, source?: RemoteConnectionTokenFile, required = false): boolean { + const previous = this.#windows.get(window); + if (source) { + source.validateAuthority(authority ?? ''); + } else if (previous && isEqualAuthority(previous.authority, authority)) { + source = previous.source; + required ||= previous.required; + } + required ||= !!source; + this.#windows.set(window, { authority, source, required, failed: false }); + return required; + } + + canReuse(window: T, authority: string, source: RemoteConnectionTokenFile): boolean { + const binding = this.#windows.get(window); + return !!binding && !binding.failed && isEqualAuthority(binding.authority, authority) && !!binding.source?.isSameSource(source); + } + + async get(window: T, authority: string): Promise { + const binding = this.#windows.get(window); + if (!binding) { + return undefined; + } + if (!isEqualAuthority(binding.authority, authority)) { + throw new RemoteConnectionTokenError(localize('remoteTokenWindowAuthority', "The remote connection token file does not belong to this window or remote address.")); + } + if (!binding.source && binding.required) { + throw new RemoteConnectionTokenError(localize('remoteTokenRestore', "This window requires a remote connection token. Launch it again with --remote and --remote-token-file.")); + } + try { + const token = await binding.source?.getValue(authority); + // A read can finish after the window has navigated or received a different source. + if (this.#windows.get(window) !== binding) { + throw new RemoteConnectionTokenError(localize('remoteTokenChanged', "The remote connection changed while reading its token file. Try connecting again.")); + } + binding.failed = false; + return token; + } catch (error) { + binding.failed = true; + throw error; + } + } +} diff --git a/src/vs/platform/remote/test/common/connectionToken.test.ts b/src/vs/platform/remote/test/common/connectionToken.test.ts new file mode 100644 index 00000000000000..c1950866598ac3 --- /dev/null +++ b/src/vs/platform/remote/test/common/connectionToken.test.ts @@ -0,0 +1,26 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; +import { isValidConnectionToken, parseConnectionTokenFile } from '../../common/connectionToken.js'; + +suite('Connection token format', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('accepts the protocol alphabet and one optional file line ending', () => { + const token = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-'; + assert.deepStrictEqual(['', '\n', '\r\n'].map(ending => parseConnectionTokenFile(token + ending)), [token, token, token]); + }); + + test('rejects empty tokens and characters outside the protocol alphabet', () => { + assert.deepStrictEqual([undefined, null, 123, '', 'a b', 'a!', 'a\n', 'a\r\n', '\uFEFFa'].map(isValidConnectionToken), Array(9).fill(false)); + }); + + test('does not trim whitespace, a BOM, or additional lines', () => { + const invalid = ['', '\n', '\r\n', ' a', 'a ', '\uFEFFa', 'a\r', 'a\n\n', 'a\r\n\r\n', 'a\nb']; + assert.deepStrictEqual(invalid.map(parseConnectionTokenFile), invalid.map(() => undefined)); + }); +}); diff --git a/src/vs/platform/remote/test/node/fixtures/remoteConnectionTokenProcess.ts b/src/vs/platform/remote/test/node/fixtures/remoteConnectionTokenProcess.ts new file mode 100644 index 00000000000000..b7dcff7bb750b4 --- /dev/null +++ b/src/vs/platform/remote/test/node/fixtures/remoteConnectionTokenProcess.ts @@ -0,0 +1,20 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { NativeParsedArgs } from '../../../../environment/common/argv.js'; +import { RemoteConnectionTokenFile, WindowRemoteConnectionTokens } from '../../../node/remoteConnectionToken.js'; + +const tokens = new WindowRemoteConnectionTokens(); +const window = {}; + +process.on('message', async (args: NativeParsedArgs) => { + try { + const token = await RemoteConnectionTokenFile.read(args); + tokens.bind(window, args.remote, token); + process.send?.({ authenticated: (await tokens.get(window, args.remote!)) !== undefined, isolated: (await tokens.get({}, args.remote!)) === undefined }); + } catch { + process.send?.({ rejected: true }); + } +}); diff --git a/src/vs/platform/remote/test/node/remoteConnectionToken.test.ts b/src/vs/platform/remote/test/node/remoteConnectionToken.test.ts new file mode 100644 index 00000000000000..76d573d7a31bd9 --- /dev/null +++ b/src/vs/platform/remote/test/node/remoteConnectionToken.test.ts @@ -0,0 +1,381 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { fork } from 'child_process'; +import { once } from 'events'; +import { fileURLToPath } from 'url'; +import { promises as fs } from 'fs'; +import { tmpdir } from 'os'; +import { inspect } from 'util'; +import { VSBuffer } from '../../../../base/common/buffer.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { DisposableStore } from '../../../../base/common/lifecycle.js'; +import { join } from '../../../../base/common/path.js'; +import { ISocket, PersistentProtocol, SocketCloseEvent, SocketDiagnosticsEventType } from '../../../../base/parts/ipc/common/ipc.net.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; +import { NativeParsedArgs } from '../../../environment/common/argv.js'; +import { OPTIONS, parseArgs } from '../../../environment/node/argv.js'; +import { NullLogService } from '../../../log/common/log.js'; +import product from '../../../product/common/product.js'; +import { IProductService } from '../../../product/common/productService.js'; +import { IMessage, ISignService } from '../../../sign/common/sign.js'; +import { ConnectionType, IConnectionOptions, PersistentConnection, PersistentConnectionEventType } from '../../common/remoteAgentConnection.js'; +// This integration test verifies credential snapshot retention across the remote resolver and connection lifecycle. +// eslint-disable-next-line local/code-layering, local/code-import-patterns +import { RemoteAuthorityResolverService } from '../../electron-browser/remoteAuthorityResolverService.js'; +import { RemoteConnectionTokenFile, validateRemoteConnectionTokenArguments, WindowRemoteConnectionTokens } from '../../node/remoteConnectionToken.js'; +import { RemoteSocketFactoryService } from '../../common/remoteSocketFactoryService.js'; +// eslint-disable-next-line local/code-import-patterns +import { DirectRemoteAuthorityResolver } from '../../../../workbench/services/extensions/common/directRemoteAuthority.js'; + +class ReconnectTestSocket implements ISocket { + private readonly _onData = new Emitter(); + public readonly onData: Event = this._onData.event; + private readonly _onClose = new Emitter(); + public readonly onClose: Event = this._onClose.event; + private readonly _onEnd = new Emitter(); + public readonly onEnd: Event = this._onEnd.event; + + write(buffer: VSBuffer): void { } + end(): void { } + async drain(): Promise { } + traceSocketEvent(type: SocketDiagnosticsEventType, data?: unknown): void { } + + dispose(): void { + this._onData.dispose(); + this._onClose.dispose(); + this._onEnd.dispose(); + } + + public fireClose(): void { + this._onClose.fire(undefined); + } +} + +class ReconnectTestPersistentConnection extends PersistentConnection { + public readonly reconnectedTokens: (string | undefined)[] = []; + + constructor(options: IConnectionOptions, protocol: PersistentProtocol) { + super(ConnectionType.Management, options, 'test-reconnection-token', protocol, /* reconnectionFailureIsFatal */ false); + } + + protected override async _reconnect(options: Parameters[0]): Promise { + this.reconnectedTokens.push(options.connectionToken); + } +} + +class ReconnectTestSignService implements ISignService { + declare readonly _serviceBrand: undefined; + + createNewMessage(value: string): Promise { + return Promise.resolve({ id: '', data: value }); + } + + validate(): Promise { + return Promise.resolve(true); + } + + sign(value: string): Promise { + return Promise.resolve(value); + } +} + +suite('Remote connection token file', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + let directory: string; + let file: string; + const authority = '127.0.0.1:8000'; + const secret = 'test_TOKEN-0123456789'; + + setup(async () => { + directory = await fs.mkdtemp(join(tmpdir(), 'vscode-remote-token-')); + file = join(directory, 'token'); + }); + + teardown(async () => { + await fs.rm(directory, { recursive: true, force: true }); + }); + + function args(): NativeParsedArgs { + return { _: ['/project'], remote: authority, 'remote-token-file': file }; + } + + async function credential(): Promise { + await fs.writeFile(file, secret, { mode: 0o600 }); + return (await RemoteConnectionTokenFile.read(args()))!; + } + + test('absent option preserves unauthenticated and resolver launches', async () => { + assert.deepStrictEqual(await Promise.all([ + RemoteConnectionTokenFile.read({ _: [] }), + RemoteConnectionTokenFile.read({ _: [], remote: authority }), + RemoteConnectionTokenFile.read({ _: [], remote: 'ssh-remote+host' }) + ]), [undefined, undefined, undefined]); + }); + + test('server token alphabet and optional final LF or CRLF', async () => { + for (const ending of ['', '\n', '\r\n']) { + await fs.writeFile(file, secret + ending); + assert.strictEqual(await (await RemoteConnectionTokenFile.read(args()))!.getValue(authority), secret); + } + }); + + test('rejects empty, whitespace, multiple lines and invalid characters without disclosing input', async () => { + for (const value of ['', '\n', ' ', secret + '\n\n', secret + '\r', secret + '!', '\uFEFF' + secret, secret + '\nother']) { + await fs.writeFile(file, value); + await assert.rejects(RemoteConnectionTokenFile.read(args()), error => { + assert.ok(error instanceof Error); + assert.ok(!error.message.includes(secret)); + return /non-empty token/.test(error.message); + }); + } + }); + + test('missing file and directory fail without exposing filesystem errors', async () => { + await assert.rejects(RemoteConnectionTokenFile.read(args()), /Unable to read the local remote connection token file/); + await fs.mkdir(file); + await assert.rejects(RemoteConnectionTokenFile.read(args()), /Unable to read the local remote connection token file/); + }); + + test('rejects missing, resolver and malformed destinations', () => { + for (const remote of [undefined, '', 'ssh-remote+host', 'host', 'host:0', 'host:65536', 'host:12/path', 'user@host:22', ':22', 'host:22\n']) { + assert.throws(() => validateRemoteConnectionTokenArguments({ ...args(), remote }), /requires an absolute local file path and --remote host:port/); + } + validateRemoteConnectionTokenArguments({ ...args(), remote: '[::1]:8000' }); + }); + + test('rejects empty and relative file arguments, including an empty CLI value', () => { + for (const value of ['', 'relative/token']) { + assert.throws(() => validateRemoteConnectionTokenArguments({ ...args(), 'remote-token-file': value })); + } + const parsed = parseArgs(['--remote', authority, '--remote-token-file'], OPTIONS); + assert.throws(() => validateRemoteConnectionTokenArguments(parsed)); + }); + + test('rejects incompatible arguments before opening any window', () => { + const incompatible: Partial[] = [ + { add: true }, { remove: true }, { 'open-url': true }, { 'folder-uri': ['file:///project'] }, + { 'file-uri': ['vscode-remote://other:8000/file'] }, { extensionDevelopmentPath: ['/extension'] }, + { status: true }, { 'install-extension': ['publisher.extension'] }, { 'serve-web': {} } + ]; + for (const option of incompatible) { + assert.throws(() => validateRemoteConnectionTokenArguments({ ...args(), ...option }), /cannot be combined/); + } + }); + + test('serialized launch arguments contain only the path and are revalidated', async () => { + await credential(); + const serialized = JSON.stringify(parseArgs(['--remote', authority, '--remote-token-file', file, '/project'], OPTIONS)); + assert.ok(!serialized.includes(secret)); + assert.strictEqual(await (await RemoteConnectionTokenFile.read(JSON.parse(serialized)))!.getValue(authority), secret); + await fs.unlink(file); + await assert.rejects(RemoteConnectionTokenFile.read(JSON.parse(serialized)), /Unable to read/); + }); + + test('a running process retains the forwarded path and rejects a file removed before reload', async () => { + await credential(); + const child = fork(fileURLToPath(new URL('./fixtures/remoteConnectionTokenProcess.js', import.meta.url)), [], { + env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, stdio: ['ignore', 'ignore', 'pipe', 'ipc'] + }); + const exited = once(child, 'exit'); + try { + const loaded = once(child, 'message'); + child.send(args()); + assert.deepStrictEqual((await loaded)[0], { authenticated: true, isolated: true }); + await fs.unlink(file); + const reloaded = once(child, 'message'); + child.send({ _: [], remote: authority }); + assert.deepStrictEqual((await reloaded)[0], { rejected: true }); + const rejected = once(child, 'message'); + child.send(args()); + assert.deepStrictEqual((await rejected)[0], { rejected: true }); + } finally { + child.kill(); + await exited; + } + }); + + test('token cannot appear in JSON or ordinary diagnostic inspection', async () => { + const token = await credential(); + assert.ok(!JSON.stringify(token).includes(secret)); + assert.ok(!inspect(token).includes(secret)); + await assert.rejects(token.getValue('127.0.0.1:8001'), /does not belong/); + }); + + test('reading a retained window binding observes file replacement and deletion', async () => { + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + tokens.bind(window, authority, await credential()); + assert.strictEqual(await tokens.get(window, authority), secret); + await fs.writeFile(file, 'replacement'); + assert.strictEqual(tokens.bind(window, authority), true); + assert.strictEqual(await tokens.get(window, authority), 'replacement'); + await fs.unlink(file); + await assert.rejects(tokens.get(window, authority), /Unable to read/); + }); + + test('a late file failure occurs during resolution, not while creating the window source', async () => { + const source = RemoteConnectionTokenFile.fromArgs(args())!; + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + assert.strictEqual(tokens.bind(window, authority, source), true); + await assert.rejects(tokens.get(window, authority), /Unable to read/); + await fs.writeFile(file, 'valid'); + assert.strictEqual(await tokens.get(window, authority), 'valid'); + await fs.writeFile(file, 'invalid token'); + await assert.rejects(tokens.get(window, authority), /non-empty token/); + }); + + test('host casing follows existing window lookup without accepting a different port', async () => { + await credential(); + const source = RemoteConnectionTokenFile.fromArgs({ ...args(), remote: 'LOCALHOST:8000' })!; + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + tokens.bind(window, 'localhost:8000', source); + assert.strictEqual(await tokens.get(window, 'localhost:8000'), secret); + await assert.rejects(tokens.get(window, 'localhost:8001'), /does not belong/); + }); + + test('same source can reuse a window, but a failed read or different source requires recovery', async () => { + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + const source = await credential(); + tokens.bind(window, authority, source); + assert.strictEqual(tokens.canReuse(window, authority, source), true); + const otherFile = join(directory, 'other-token'); + await fs.writeFile(otherFile, secret); + const other = (await RemoteConnectionTokenFile.read({ ...args(), 'remote-token-file': otherFile }))!; + assert.strictEqual(tokens.canReuse(window, authority, other), false); + await fs.unlink(file); + await assert.rejects(tokens.get(window, authority)); + assert.strictEqual(tokens.canReuse(window, authority, source), false); + }); + + test('a token read cannot complete for a window that has since changed destination', async () => { + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + tokens.bind(window, authority, await credential()); + const pending = tokens.get(window, authority); + tokens.bind(window, 'other:8000'); + await assert.rejects(pending, /changed while reading/); + }); + + test('credentials are isolated by window and destination and dropped on window reuse', async () => { + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + tokens.bind(window, authority, await credential()); + assert.strictEqual(await tokens.get({}, authority), undefined); + await assert.rejects(tokens.get(window, '127.0.0.1:8001'), /does not belong/); + tokens.bind(window, '127.0.0.1:8001'); + tokens.bind(window, authority); + assert.strictEqual(await tokens.get(window, authority), undefined); + tokens.bind(window, authority, await credential()); + tokens.bind(window, undefined); + await assert.rejects(tokens.get(window, authority), /does not belong/); + }); + + test('restored windows fail closed until a new launch supplies a credential', async () => { + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + tokens.bind(window, authority, undefined, true); + await assert.rejects(tokens.get(window, authority), /Launch it again/); + tokens.bind(window, authority); // Reload must not clear the requirement. + await assert.rejects(tokens.get(window, authority), /Launch it again/); + tokens.bind(window, authority, await credential()); + assert.strictEqual(await tokens.get(window, authority), secret); + }); + + test('a new launch can replace a credential only for its exact destination', async () => { + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + const token = await credential(); + assert.throws(() => tokens.bind(window, 'other:8000', token), /does not belong/); + assert.strictEqual(await tokens.get(window, authority), undefined); + tokens.bind(window, authority, token); + await fs.writeFile(file, 'replacement'); + tokens.bind(window, authority, (await RemoteConnectionTokenFile.read(args()))!); + assert.strictEqual(await tokens.get(window, authority), 'replacement'); + }); + + test('ordinary reconnection retains the original resolved token when the token file changes', async () => { + const disposables = new DisposableStore(); + try { + const initialToken = 'synthetic_INITIAL_token-12345'; + await fs.writeFile(file, initialToken); + + const source = (await RemoteConnectionTokenFile.read(args()))!; + const tokens = new WindowRemoteConnectionTokens(); + const window = {}; + tokens.bind(window, authority, source); + + const directResolver = new DirectRemoteAuthorityResolver( + a => tokens.get(window, a), + async () => { } + ); + const resolvedAuthorityResult = await directResolver.resolve(authority); + + assert.strictEqual(resolvedAuthorityResult.authority.connectionToken, initialToken); + + const productService: IProductService = { _serviceBrand: undefined, ...product }; + // eslint-disable-next-line local/code-no-any-casts + const resolverService = disposables.add(new RemoteAuthorityResolverService(productService, undefined as any)); + const resolvePromise = resolverService.resolveAuthority(authority); + resolverService._setResolvedAuthority(resolvedAuthorityResult.authority, resolvedAuthorityResult.options); + const resolvedFromService = await resolvePromise; + + assert.strictEqual(resolvedFromService.authority.connectionToken, initialToken); + assert.strictEqual(resolverService.getConnectionData(authority)?.connectionToken, initialToken); + + const options: IConnectionOptions = { + commit: undefined, + quality: undefined, + addressProvider: { + getAddress: async () => { + // Desktop reconnection clears and resolves the authority again before reading it. + resolverService._clearResolvedAuthority(authority); + const address = resolverService.resolveAuthority(authority); + try { + const result = await directResolver.resolve(authority); + resolverService._setResolvedAuthority(result.authority, result.options); + } catch (error) { + resolverService._setResolvedAuthorityError(authority, error); + } + const { authority: resolved } = await address; + return { connectTo: resolved.connectTo, connectionToken: resolved.connectionToken }; + } + }, + remoteSocketFactoryService: new RemoteSocketFactoryService(), + signService: new ReconnectTestSignService(), + logService: new NullLogService(), + ipcLogger: null + }; + + const socket = disposables.add(new ReconnectTestSocket()); + const protocol = disposables.add(new PersistentProtocol({ socket, sendKeepAlive: false })); + const connection = disposables.add(new ReconnectTestPersistentConnection(options, protocol)); + assert.strictEqual(connection.isConnected, true); + + const mutatedToken = 'synthetic_MUTATED_token-67890'; + await fs.writeFile(file, mutatedToken); + + assert.strictEqual(await tokens.get(window, authority), mutatedToken); + + const reconnectedPromise = Event.toPromise(Event.filter(connection.onDidStateChange, event => event.type === PersistentConnectionEventType.ConnectionGain)); + socket.fireClose(); + await reconnectedPromise; + + assert.strictEqual(connection.reconnectedTokens.length, 1); + assert.strictEqual(connection.reconnectedTokens[0], initialToken); + assert.strictEqual(resolverService.getConnectionData(authority)?.connectionToken, initialToken); + + const reloadedResolver = new DirectRemoteAuthorityResolver(a => tokens.get(window, a), async () => { }); + assert.strictEqual((await reloadedResolver.resolve(authority)).authority.connectionToken, mutatedToken); + } finally { + disposables.dispose(); + } + }); +}); diff --git a/src/vs/platform/window/common/window.ts b/src/vs/platform/window/common/window.ts index 0a1f60415ffb35..9bcb8bdeacdbaf 100644 --- a/src/vs/platform/window/common/window.ts +++ b/src/vs/platform/window/common/window.ts @@ -626,6 +626,10 @@ export interface IWindowFolderLocation { } export interface INativeWindowConfiguration extends IWindowConfiguration, NativeParsedArgs, ISandboxConfiguration { + + /** Non-secret restore marker. The credential is never serialized into this configuration. */ + remoteConnectionTokenRequired?: boolean; + mainPid: number; handle?: VSBuffer; diff --git a/src/vs/platform/windows/electron-main/windows.ts b/src/vs/platform/windows/electron-main/windows.ts index 76e9f5f68a4369..8473461e593eb9 100644 --- a/src/vs/platform/windows/electron-main/windows.ts +++ b/src/vs/platform/windows/electron-main/windows.ts @@ -11,6 +11,7 @@ import { IProcessEnvironment, isLinux, isMacintosh, isWindows } from '../../../b import { URI } from '../../../base/common/uri.js'; import { IAuxiliaryWindow } from '../../auxiliaryWindow/electron-main/auxiliaryWindow.js'; import { IConfigurationService } from '../../configuration/common/configuration.js'; +import { RemoteConnectionTokenFile } from '../../remote/node/remoteConnectionToken.js'; import { NativeParsedArgs } from '../../environment/common/argv.js'; import { IEnvironmentMainService } from '../../environment/electron-main/environmentMainService.js'; import { ServicesAccessor, createDecorator } from '../../instantiation/common/instantiation.js'; @@ -37,6 +38,8 @@ export interface IWindowsMainService { readonly onDidTriggerSystemContextMenu: Event<{ readonly window: ICodeWindow; readonly x: number; readonly y: number }>; readonly onDidDestroyWindow: Event; + getRemoteConnectionToken(windowId: number, authority: string): Promise; + open(openConfig: IOpenConfiguration): Promise; openEmptyWindow(openConfig: IOpenEmptyConfiguration, options?: IOpenEmptyWindowOptions): Promise; openExtensionDevelopmentHostWindow(extensionDevelopmentPath: string[], openConfig: IOpenConfiguration): Promise; @@ -100,6 +103,8 @@ export interface IBaseOpenConfiguration { } export interface IOpenConfiguration extends IBaseOpenConfiguration { + /** Main-process-only source; never copied into INativeWindowConfiguration. */ + readonly remoteConnectionTokenFile?: RemoteConnectionTokenFile; readonly cli: NativeParsedArgs; readonly userEnv?: IProcessEnvironment; readonly urisToOpen?: IWindowOpenable[]; diff --git a/src/vs/platform/windows/electron-main/windowsMainService.ts b/src/vs/platform/windows/electron-main/windowsMainService.ts index 7f13d2134fc15c..8f1589a2acab82 100644 --- a/src/vs/platform/windows/electron-main/windowsMainService.ts +++ b/src/vs/platform/windows/electron-main/windowsMainService.ts @@ -60,6 +60,7 @@ import { IAuxiliaryWindow } from '../../auxiliaryWindow/electron-main/auxiliaryW import { ICSSDevelopmentService } from '../../cssDev/node/cssDevService.js'; import { ResourceSet } from '../../../base/common/map.js'; import { VSBuffer } from '../../../base/common/buffer.js'; +import { RemoteConnectionTokenFile, WindowRemoteConnectionTokens } from '../../remote/node/remoteConnectionToken.js'; import { resolveAgentsWindowFolder, sendAgentsWindowOpenIntent } from './agentsWindow.js'; //#region Helper Interfaces @@ -67,6 +68,7 @@ import { resolveAgentsWindowFolder, sendAgentsWindowOpenIntent } from './agentsW type RestoreWindowsSetting = 'preserve' | 'all' | 'folders' | 'one' | 'none'; interface IOpenBrowserWindowOptions { + readonly remoteConnectionTokenFile?: RemoteConnectionTokenFile; readonly userEnv?: IProcessEnvironment; readonly cli?: NativeParsedArgs; @@ -217,6 +219,8 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic private readonly _onDidTriggerSystemContextMenu = this._register(new Emitter<{ window: ICodeWindow; x: number; y: number }>()); readonly onDidTriggerSystemContextMenu = this._onDidTriggerSystemContextMenu.event; + private readonly windowConnectionTokens = new WindowRemoteConnectionTokens(); + private readonly windows = new Map(); private readonly windowsStateHandler: WindowsStateHandler; @@ -334,6 +338,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic urisToOpen: [{ workspaceUri: agentSessionsWorkspaceUri }], userEnv: openConfig.userEnv, cli: openConfig.cli, + remoteConnectionTokenFile: openConfig.remoteConnectionTokenFile, noRecentEntry: true, context: openConfig.context, contextWindowId: openConfig.contextWindowId, @@ -342,9 +347,26 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic }; } + async getRemoteConnectionToken(windowId: number, authority: string): Promise { + const window = this.getWindowById(windowId); + if (!window) { + throw new Error(localize('remoteTokenUnknownWindow', "The window requesting a remote connection token no longer exists.")); + } + return this.windowConnectionTokens.get(window, authority); + } + async open(openConfig: IOpenConfiguration): Promise { this.logService.trace('windowsManager#open'); + // Consume this launch's option before inheriting environment arguments in other windows. + const launchArgs = { ...openConfig.cli }; + delete openConfig.cli['remote-token-file']; + // File I/O belongs to authority resolution so a late failure affects only this window. + const connectionToken = RemoteConnectionTokenFile.fromArgs(launchArgs) ?? openConfig.remoteConnectionTokenFile; + if (connectionToken) { + openConfig = { ...openConfig, remoteConnectionTokenFile: connectionToken, forceEmpty: openConfig.forceEmpty || openConfig.cli._.length === 0 }; + } + // Make sure addMode/removeMode is only enabled if we have an active window if ((openConfig.addMode || openConfig.removeMode) && (openConfig.initialStartup || !this.getLastActiveWindow())) { openConfig.addMode = false; @@ -413,7 +435,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic } // These are windows to restore because of hot-exit or from previous session (only performed once on startup!) - if (openConfig.initialStartup) { + if (openConfig.initialStartup && !connectionToken) { // Untitled workspaces are always restored untitledWorkspacesToRestore.push(...this.workspacesManagementMainService.getUntitledWorkspaces()); @@ -652,7 +674,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic // Window is empty else { - addUsedWindow(this.doOpenFilesInExistingWindow(openConfig, windowToUseForFiles, filesToOpen), true); + addUsedWindow(await this.doOpenFilesInExistingWindow(openConfig, windowToUseForFiles, filesToOpen), true); } } @@ -661,6 +683,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic addUsedWindow(await this.openInBrowserWindow({ userEnv: openConfig.userEnv, cli: openConfig.cli, + remoteConnectionTokenFile: openConfig.remoteConnectionTokenFile, initialStartup: openConfig.initialStartup, filesToOpen, forceNewWindow: true, @@ -683,7 +706,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic const filesToOpenInWindow = isEqualAuthority(filesToOpen?.remoteAuthority, windowOnWorkspace.remoteAuthority) ? filesToOpen : undefined; // Do open files - addUsedWindow(this.doOpenFilesInExistingWindow(openConfig, windowOnWorkspace, filesToOpenInWindow), !!filesToOpenInWindow); + addUsedWindow(await this.doOpenFilesInExistingWindow(openConfig, windowOnWorkspace, filesToOpenInWindow), !!filesToOpenInWindow); openFolderInNewWindow = true; // any other folders to open must open in new window then } @@ -715,7 +738,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic const filesToOpenInWindow = isEqualAuthority(filesToOpen?.remoteAuthority, windowOnFolderPath.remoteAuthority) ? filesToOpen : undefined; // Do open files - addUsedWindow(this.doOpenFilesInExistingWindow(openConfig, windowOnFolderPath, filesToOpenInWindow), !!filesToOpenInWindow); + addUsedWindow(await this.doOpenFilesInExistingWindow(openConfig, windowOnFolderPath, filesToOpenInWindow), !!filesToOpenInWindow); openFolderInNewWindow = true; // any other folders to open must open in new window then } @@ -762,9 +785,28 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic return { windows: distinct(usedWindows), filesOpenedInWindow }; } - private doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, filesToOpen?: IFilesToOpen): ICodeWindow { + private async doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, filesToOpen?: IFilesToOpen): Promise { this.logService.trace('windowsManager#doOpenFilesInExistingWindow', { filesToOpen }); + if (configuration.remoteConnectionTokenFile && !this.windowConnectionTokens.canReuse(window, window.remoteAuthority ?? '', configuration.remoteConnectionTokenFile)) { + return this.openInBrowserWindow({ + cli: configuration.cli, + remoteConnectionTokenFile: configuration.remoteConnectionTokenFile, + windowToUse: window, + workspace: window.openedWorkspace, + remoteAuthority: window.remoteAuthority, + filesToOpen, + userEnv: configuration.userEnv, + forceProfile: configuration.forceProfile, + forceTempProfile: configuration.forceTempProfile, + // This is a reload of the same empty workspace, not a new workspace. + emptyWindowBackupInfo: !window.openedWorkspace && window.backupPath ? { + backupFolder: basename(window.backupPath), + remoteAuthority: window.remoteAuthority + } : undefined + }); + } + this.focusMainOrChildWindow(window); // make sure window or any of the children has focus const params: INativeOpenFileRequest = { @@ -823,6 +865,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic return this.openInBrowserWindow({ userEnv: openConfig.userEnv, cli: openConfig.cli, + remoteConnectionTokenFile: openConfig.remoteConnectionTokenFile, initialStartup: openConfig.initialStartup, remoteAuthority, forceNewWindow: resolved.forceNewWindow, @@ -878,6 +921,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic ...folderLocation, userEnv: openConfig.userEnv, cli: openConfig.cli, + remoteConnectionTokenFile: openConfig.remoteConnectionTokenFile, initialStartup: openConfig.initialStartup, remoteAuthority: folderOrWorkspace.remoteAuthority, forceNewWindow, @@ -958,7 +1002,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic // not restored windows already otherwise. // Use `unshift` to ensure any new window to open comes last for proper // focus treatment. - if (openConfig.initialStartup && !isRestoringPaths && this.configurationService.getValue('window')?.restoreWindows === 'preserve') { + if (openConfig.initialStartup && !openConfig.remoteConnectionTokenFile && !isRestoringPaths && this.configurationService.getValue('window')?.restoreWindows === 'preserve') { const lastSessionPaths = await this.doGetPathsFromLastSession(); pathsToOpen.unshift(...lastSessionPaths.filter(path => isWorkspacePathToOpen(path) || isSingleFolderWorkspacePathToOpen(path) || path.backupPath)); } @@ -1565,6 +1609,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic const openArgs: IOpenConfiguration = { context: openConfig.context, cli: openConfig.cli, + remoteConnectionTokenFile: openConfig.remoteConnectionTokenFile, forceNewWindow: true, forceEmpty: !cliArgs.length && !folderUris.length && !fileUris.length, userEnv: openConfig.userEnv, @@ -1579,6 +1624,10 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic } private async openInBrowserWindow(options: IOpenBrowserWindowOptions): Promise { + const connectionToken = options.remoteConnectionTokenFile; + if (connectionToken) { + connectionToken.validateAuthority(options.remoteAuthority ?? ''); // Validate before creating or unloading a window. + } const windowConfig = this.configurationService.getValue('window'); const lastActiveWindow = this.getLastActiveWindow(); @@ -1812,6 +1861,11 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic } } + // Keep credentials outside the serializable configuration. Reload retains this binding; + // loading a different destination drops it, even when reusing the BrowserWindow. + const connectionToken = options.remoteConnectionTokenFile; + configuration.remoteConnectionTokenRequired = this.windowConnectionTokens.bind(window, configuration.remoteAuthority, connectionToken, this.windowsStateHandler.requiresRemoteConnectionToken(configuration)); + // Load it window.load(configuration); } diff --git a/src/vs/platform/windows/electron-main/windowsStateHandler.ts b/src/vs/platform/windows/electron-main/windowsStateHandler.ts index 859e84e4856efc..4e4d4df57dddc3 100644 --- a/src/vs/platform/windows/electron-main/windowsStateHandler.ts +++ b/src/vs/platform/windows/electron-main/windowsStateHandler.ts @@ -7,7 +7,7 @@ import electron from 'electron'; import { Event } from '../../../base/common/event.js'; import { Disposable } from '../../../base/common/lifecycle.js'; import { isMacintosh } from '../../../base/common/platform.js'; -import { extUriBiasedIgnorePathCase } from '../../../base/common/resources.js'; +import { extUriBiasedIgnorePathCase, isEqualAuthority } from '../../../base/common/resources.js'; import { URI } from '../../../base/common/uri.js'; import { IConfigurationService } from '../../configuration/common/configuration.js'; import { ILifecycleMainService } from '../../lifecycle/electron-main/lifecycleMainService.js'; @@ -24,6 +24,7 @@ export interface IWindowState { folderUri?: URI; backupPath?: string; remoteAuthority?: string; + remoteConnectionTokenRequired?: boolean; uiState: IWindowUIState; } @@ -48,6 +49,7 @@ interface ISerializedWindowState { readonly folder?: string; readonly backupPath?: string; readonly remoteAuthority?: string; + readonly remoteConnectionTokenRequired?: boolean; readonly uiState: IWindowUIState; } @@ -321,10 +323,27 @@ export class WindowsStateHandler extends Disposable { folderUri: isSingleFolderWorkspaceIdentifier(window.openedWorkspace) ? window.openedWorkspace.uri : undefined, backupPath: window.backupPath, remoteAuthority: window.remoteAuthority, + ...(window.config?.remoteConnectionTokenRequired ? { remoteConnectionTokenRequired: true } : {}), uiState: window.serializeWindowState({ exact }) }; } + requiresRemoteConnectionToken(configuration: INativeWindowConfiguration): boolean { + const states = [...this._state.openedWindows, this._state.lastActiveWindow, this.lastClosedState]; + return states.some(state => { + if (!state?.remoteConnectionTokenRequired || !isEqualAuthority(state.remoteAuthority, configuration.remoteAuthority)) { + return false; + } + if (isWorkspaceIdentifier(configuration.workspace)) { + return state.workspace?.id === configuration.workspace.id; + } + if (isSingleFolderWorkspaceIdentifier(configuration.workspace)) { + return !!state.folderUri && extUriBiasedIgnorePathCase.isEqual(state.folderUri, configuration.workspace.uri); + } + return !!configuration.backupPath && state.backupPath === configuration.backupPath; + }); + } + getNewWindowState(configuration: INativeWindowConfiguration): INewWindowState { const state = this.doGetNewWindowState(configuration); const windowConfig = this.configurationService.getValue('window'); @@ -512,6 +531,10 @@ function restoreWindowState(windowState: ISerializedWindowState): IWindowState { result.backupPath = windowState.backupPath; } + if (windowState.remoteConnectionTokenRequired) { + result.remoteConnectionTokenRequired = true; + } + if (windowState.remoteAuthority) { result.remoteAuthority = windowState.remoteAuthority; } @@ -541,6 +564,7 @@ function serializeWindowState(windowState: IWindowState): ISerializedWindowState folder: windowState.folderUri?.toString(), backupPath: windowState.backupPath, remoteAuthority: windowState.remoteAuthority, + ...(windowState.remoteConnectionTokenRequired ? { remoteConnectionTokenRequired: true } : {}), uiState: windowState.uiState }; } diff --git a/src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts b/src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts index a5b1efb4402ecb..4d81992fb03919 100644 --- a/src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts +++ b/src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts @@ -61,6 +61,7 @@ suite('Windows State Storing', () => { assert.strictEqual(expected.backupPath, actual.backupPath, message); assertEqualURI(expected.folderUri, actual.folderUri, message); assert.strictEqual(expected.remoteAuthority, actual.remoteAuthority, message); + assert.strictEqual(expected.remoteConnectionTokenRequired, actual.remoteConnectionTokenRequired, message); assertEqualWorkspace(expected.workspace, actual.workspace, message); assert.deepStrictEqual(expected.uiState, actual.uiState, message); } @@ -88,6 +89,21 @@ suite('Windows State Storing', () => { const testRemoteFolderURI = URI.parse('foo://bar/c/d'); + test('stores only a non-secret authentication requirement for restoration', () => { + const state: IWindowsState = { + openedWindows: [{ + folderUri: URI.parse('vscode-remote://127.0.0.1:8000/project'), + remoteAuthority: '127.0.0.1:8000', + remoteConnectionTokenRequired: true, + uiState: getUIState() + }] + }; + assertRestoring(state); + assert.deepStrictEqual(Object.keys(getWindowsStateStoreData(state).openedWindows[0]).sort(), [ + 'backupPath', 'folder', 'remoteAuthority', 'remoteConnectionTokenRequired', 'uiState', 'workspaceIdentifier' + ]); + }); + test('storing and restoring', () => { let windowState: IWindowsState; windowState = { diff --git a/src/vs/server/node/serverConnectionToken.ts b/src/vs/server/node/serverConnectionToken.ts index bb2bff034aba8b..950e51d6d5f4c0 100644 --- a/src/vs/server/node/serverConnectionToken.ts +++ b/src/vs/server/node/serverConnectionToken.ts @@ -11,8 +11,7 @@ import { generateUuid } from '../../base/common/uuid.js'; import { connectionTokenCookieName, connectionTokenQueryName } from '../../base/common/network.js'; import { ServerParsedArgs } from './serverEnvironmentService.js'; import { Promises } from '../../base/node/pfs.js'; - -const connectionTokenRegex = /^[0-9A-Za-z_-]+$/; +import { isValidConnectionToken, parseConnectionTokenFile } from '../../platform/remote/common/connectionToken.js'; export const enum ServerConnectionTokenType { None, @@ -64,14 +63,14 @@ export async function parseServerConnectionToken(args: ServerParsedArgs, default return new ServerConnectionTokenParseError(`Please do not use the argument '--connection-token' at the same time as '--connection-token-file'.`); } - let rawConnectionToken: string; + let rawConnectionToken: string | undefined; try { - rawConnectionToken = (await fs.promises.readFile(connectionTokenFile, 'utf8')).replace(/\r?\n$/, ''); + rawConnectionToken = parseConnectionTokenFile(await fs.promises.readFile(connectionTokenFile, 'utf8')); } catch (e) { return new ServerConnectionTokenParseError(`Unable to read the connection token file at '${connectionTokenFile}'.`); } - if (!connectionTokenRegex.test(rawConnectionToken)) { + if (rawConnectionToken === undefined) { return new ServerConnectionTokenParseError(`The connection token defined in '${connectionTokenFile} does not adhere to the characters 0-9, a-z, A-Z, _, or -.`); } @@ -79,7 +78,7 @@ export async function parseServerConnectionToken(args: ServerParsedArgs, default } if (typeof connectionToken !== 'undefined') { - if (!connectionTokenRegex.test(connectionToken)) { + if (!isValidConnectionToken(connectionToken)) { return new ServerConnectionTokenParseError(`The connection token '${connectionToken} does not adhere to the characters 0-9, a-z, A-Z or -.`); } @@ -100,8 +99,8 @@ export async function determineServerConnectionToken(args: ServerParsedArgs): Pr // First try to find a connection token try { const fileContents = await fs.promises.readFile(storageLocation); - const connectionToken = fileContents.toString().replace(/\r?\n$/, ''); - if (connectionTokenRegex.test(connectionToken)) { + const connectionToken = parseConnectionTokenFile(fileContents.toString()); + if (connectionToken !== undefined) { return connectionToken; } } catch (err) { } diff --git a/src/vs/server/test/node/serverConnectionToken.test.ts b/src/vs/server/test/node/serverConnectionToken.test.ts index b0de52968d51a3..51f5b3272f3475 100644 --- a/src/vs/server/test/node/serverConnectionToken.test.ts +++ b/src/vs/server/test/node/serverConnectionToken.test.ts @@ -11,6 +11,7 @@ import { connectionTokenCookieName, connectionTokenQueryName } from '../../../ba import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; import { getRandomTestPath } from '../../../base/test/node/testUtils.js'; import { MandatoryServerConnectionToken, parseServerConnectionToken, requestHasValidConnectionToken, ServerConnectionToken, ServerConnectionTokenParseError, ServerConnectionTokenType } from '../../node/serverConnectionToken.js'; +import { RemoteConnectionTokenFile } from '../../../platform/remote/node/remoteConnectionToken.js'; import { getRedactedServerParsedArgs, ServerParsedArgs } from '../../node/serverEnvironmentService.js'; suite('parseServerConnectionToken', () => { @@ -48,6 +49,23 @@ suite('parseServerConnectionToken', () => { assertIsError(await parseServerConnectionToken({ 'connection-token-file': '0', 'connection-token': '0' } as ServerParsedArgs, async () => 'defaultTokenValue')); }); + test('desktop token files authenticate with the server and wrong tokens are rejected', async () => { + const directory = await fs.promises.mkdtemp(join(os.tmpdir(), 'vscode-desktop-server-token-')); + try { + const file = join(directory, 'token'); + const authority = '127.0.0.1:8000'; + for (const ending of ['', '\n', '\r\n']) { + await fs.promises.writeFile(file, `shared_TOKEN-123${ending}`); + const server = await parseServerConnectionToken({ 'connection-token-file': file } as ServerParsedArgs, async () => 'unused'); + assert.ok(server instanceof MandatoryServerConnectionToken); + const desktop = await RemoteConnectionTokenFile.read({ _: [], remote: authority, 'remote-token-file': file }); + assert.deepStrictEqual([server.validate(await desktop!.getValue(authority)), server.validate('wrong-token'), server.validate(undefined)], [true, false, false]); + } + } finally { + await fs.promises.rm(directory, { recursive: true, force: true }); + } + }); + test('--connection-token-file', async function () { this.timeout(10000); const testDir = getRandomTestPath(os.tmpdir(), 'vsctests', 'server-connection-token'); @@ -69,7 +87,7 @@ suite('parseServerConnectionToken', () => { const filename = join(directory, 'token'); try { const results: (ServerConnectionToken | ServerConnectionTokenParseError)[] = []; - for (const contents of ['valid-token\n', 'valid-token\r\n', 'invalid token\n']) { + for (const contents of ['valid-token\n', 'valid-token\r\n', 'invalid token\n', '', 'valid-token\n\n']) { await fs.promises.writeFile(filename, contents); results.push(await parseServerConnectionToken({ 'connection-token-file': filename } as ServerParsedArgs, async () => 'defaultTokenValue')); } @@ -77,6 +95,8 @@ suite('parseServerConnectionToken', () => { new MandatoryServerConnectionToken('valid-token'), new MandatoryServerConnectionToken('valid-token'), new ServerConnectionTokenParseError(`The connection token defined in '${filename} does not adhere to the characters 0-9, a-z, A-Z, _, or -.`), + new ServerConnectionTokenParseError(`The connection token defined in '${filename} does not adhere to the characters 0-9, a-z, A-Z, _, or -.`), + new ServerConnectionTokenParseError(`The connection token defined in '${filename} does not adhere to the characters 0-9, a-z, A-Z, _, or -.`), ]); } finally { await fs.promises.rm(directory, { recursive: true, force: true }); diff --git a/src/vs/workbench/services/extensions/common/directRemoteAuthority.ts b/src/vs/workbench/services/extensions/common/directRemoteAuthority.ts new file mode 100644 index 00000000000000..6ff99b20641952 --- /dev/null +++ b/src/vs/workbench/services/extensions/common/directRemoteAuthority.ts @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { toErrorMessage } from '../../../../base/common/errorMessage.js'; +import { RemoteAuthorityResolverError, RemoteAuthorityResolverErrorCode, RemoteConnectionType, ResolverResult } from '../../../../platform/remote/common/remoteAuthorityResolver.js'; +import { isLoopbackHost, parseAuthorityWithPort } from '../../../../platform/remote/common/remoteHosts.js'; + +/** Resolve a direct desktop connection only after confirming its destination. */ +export async function resolveDirectRemoteAuthority( + authority: string, + getConnectionToken: (authority: string) => Promise, + confirmConnection: (host: string, port: number) => Promise +): Promise { + const { host, port } = parseAuthorityWithPort(authority); + // Direct authorities can originate in untrusted workspace files. Preserve the + // host confirmation before requesting credentials or connecting to the server. + if (!isLoopbackHost(host)) { + await confirmConnection(host, port); + } + + let connectionToken: string | undefined; + try { + connectionToken = await getConnectionToken(authority); + } catch (error) { + // IPC does not preserve the main process's credential error class. + throw new RemoteAuthorityResolverError(toErrorMessage(error), RemoteAuthorityResolverErrorCode.NotAvailable); + } + + return { authority: { authority, connectTo: { type: RemoteConnectionType.WebSocket, host, port }, connectionToken } }; +} + +/** Keep the resolved token across reconnects for the lifetime of the workbench. */ +export class DirectRemoteAuthorityResolver { + private readonly _connectionTokens = new Map>(); + + constructor( + private readonly _getConnectionToken: (authority: string) => Promise, + private readonly _confirmConnection: (host: string, port: number) => Promise, + ) { } + + resolve(authority: string): Promise { + return resolveDirectRemoteAuthority(authority, async authority => { + let token = this._connectionTokens.get(authority); + if (!token) { + token = this._getConnectionToken(authority).catch(error => { + this._connectionTokens.delete(authority); + throw error; + }); + this._connectionTokens.set(authority, token); + } + return token; + }, this._confirmConnection); + } +} diff --git a/src/vs/workbench/services/extensions/electron-browser/nativeExtensionService.ts b/src/vs/workbench/services/extensions/electron-browser/nativeExtensionService.ts index dcd36612cc6b59..4a5441e6ccb4c4 100644 --- a/src/vs/workbench/services/extensions/electron-browser/nativeExtensionService.ts +++ b/src/vs/workbench/services/extensions/electron-browser/nativeExtensionService.ts @@ -30,9 +30,10 @@ import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { IProductService } from '../../../../platform/product/common/productService.js'; import { PersistentConnectionEventType } from '../../../../platform/remote/common/remoteAgentConnection.js'; import { IRemoteAgentEnvironment } from '../../../../platform/remote/common/remoteAgentEnvironment.js'; -import { IRemoteAuthorityResolverService, RemoteAuthorityResolverError, RemoteAuthorityResolverErrorCode, RemoteConnectionType, ResolverResult, getRemoteAuthorityPrefix } from '../../../../platform/remote/common/remoteAuthorityResolver.js'; +import { IRemoteAuthorityResolverService, RemoteAuthorityResolverError, RemoteAuthorityResolverErrorCode, ResolverResult, getRemoteAuthorityPrefix } from '../../../../platform/remote/common/remoteAuthorityResolver.js'; import { IRemoteExtensionsScannerService } from '../../../../platform/remote/common/remoteExtensionsScanner.js'; -import { getRemoteName, isLoopbackHost, parseAuthorityWithPort } from '../../../../platform/remote/common/remoteHosts.js'; +import { DirectRemoteAuthorityResolver } from '../common/directRemoteAuthority.js'; +import { getRemoteName } from '../../../../platform/remote/common/remoteHosts.js'; import { updateProxyConfigurationsScope } from '../../../../platform/request/common/request.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.js'; @@ -63,6 +64,7 @@ import { AsyncIterableEmitter, AsyncIterableProducer } from '../../../../base/co export class NativeExtensionService extends AbstractExtensionService implements IExtensionService { private readonly _extensionScanner: CachedExtensionScanner; + private readonly _directRemoteAuthorityResolver: DirectRemoteAuthorityResolver; private readonly _localCrashTracker = new ExtensionHostCrashTracker(); constructor( @@ -128,6 +130,10 @@ export class NativeExtensionService extends AbstractExtensionService implements ); this._extensionScanner = extensionScanner; + this._directRemoteAuthorityResolver = new DirectRemoteAuthorityResolver( + authority => this._nativeHostService.getRemoteConnectionToken(authority), + (host, port) => this._confirmDirectRemoteConnection(host, port) + ); // delay extension host creation and extension scanning // until the workbench is running. we cannot defer the @@ -276,30 +282,7 @@ export class NativeExtensionService extends AbstractExtensionService implements const authorityPlusIndex = remoteAuthority.indexOf('+'); if (authorityPlusIndex === -1) { - // This authority does not need to be resolved, simply parse the port number - const { host, port } = parseAuthorityWithPort(remoteAuthority); - - // A direct `:` authority bypasses resolver extensions and connects - // straight to the given server. This form can originate from untrusted sources - // (e.g. the `remoteAuthority` of a `.code-workspace` file), so before connecting - // to anything that is not the local loopback interface we ask the user to confirm. - // This prevents a crafted workspace from silently pointing the window's backend at - // an attacker controlled server. - if (!isLoopbackHost(host)) { - await this._confirmDirectRemoteConnection(host, port); - } - - return { - authority: { - authority: remoteAuthority, - connectTo: { - type: RemoteConnectionType.WebSocket, - host, - port - }, - connectionToken: undefined - } - }; + return this._directRemoteAuthorityResolver.resolve(remoteAuthority); } return this._resolveAuthorityOnExtensionHosts(ExtensionHostKind.LocalProcess, remoteAuthority); diff --git a/src/vs/workbench/services/extensions/test/common/directRemoteAuthority.test.ts b/src/vs/workbench/services/extensions/test/common/directRemoteAuthority.test.ts new file mode 100644 index 00000000000000..b841fc254a907e --- /dev/null +++ b/src/vs/workbench/services/extensions/test/common/directRemoteAuthority.test.ts @@ -0,0 +1,46 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { RemoteAuthorityResolverError, RemoteAuthorityResolverErrorCode, RemoteConnectionType } from '../../../../../platform/remote/common/remoteAuthorityResolver.js'; +import { resolveDirectRemoteAuthority } from '../../common/directRemoteAuthority.js'; + +suite('Direct remote authority', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('supplies the token for the exact authority without prompting for loopback', async () => { + const result = await resolveDirectRemoteAuthority('127.0.0.1:8000', async authority => { + assert.strictEqual(authority, '127.0.0.1:8000'); + return 'test-token'; + }, async () => assert.fail('Unexpected host confirmation')); + assert.deepStrictEqual(result, { authority: { authority: '127.0.0.1:8000', connectTo: { type: RemoteConnectionType.WebSocket, host: '127.0.0.1', port: 8000 }, connectionToken: 'test-token' } }); + }); + + test('preserves an absent token', async () => { + const result = await resolveDirectRemoteAuthority('localhost:8000', async () => undefined, async () => assert.fail('Unexpected host confirmation')); + assert.strictEqual(result.authority.connectionToken, undefined); + }); + + test('classifies IPC credential failures as unavailable without falling back', async () => { + await assert.rejects(resolveDirectRemoteAuthority('localhost:8000', async () => { + throw new Error('Token file unavailable'); + }, async () => { }), error => error instanceof RemoteAuthorityResolverError && error._code === RemoteAuthorityResolverErrorCode.NotAvailable && error.message === 'Token file unavailable'); + }); + + test('confirms non-loopback hosts before requesting credentials', async () => { + const calls: string[] = []; + await resolveDirectRemoteAuthority('remote.example:8000', async authority => { + calls.push(`token:${authority}`); + return 'test-token'; + }, async (host, port) => { calls.push(`confirm:${host}:${port}`); }); + assert.deepStrictEqual(calls, ['confirm:remote.example:8000', 'token:remote.example:8000']); + }); + + test('rejecting the host prevents credential lookup', async () => { + const rejection = new Error('Host rejected'); + await assert.rejects(resolveDirectRemoteAuthority('remote.example:8000', async () => assert.fail('Unexpected credential lookup'), async () => { throw rejection; }), error => error === rejection); + }); +}); diff --git a/src/vs/workbench/test/electron-browser/workbenchTestServices.ts b/src/vs/workbench/test/electron-browser/workbenchTestServices.ts index 02709b417baef8..bc3f1fb0724ab9 100644 --- a/src/vs/workbench/test/electron-browser/workbenchTestServices.ts +++ b/src/vs/workbench/test/electron-browser/workbenchTestServices.ts @@ -193,6 +193,7 @@ export class TestNativeHostService implements INativeHostService { async openDevToolsWindow(url: string): Promise { } async openGPUInfoWindow(): Promise { } async openContentTracingWindow(): Promise { } + async getRemoteConnectionToken(_authority: string): Promise { return undefined; } async resolveProxy(url: string): Promise { return undefined; } async resolveProxyWithPackage() { return []; } async readProxyConfigWithPackage() {