diff --git a/CHANGELOG.md b/CHANGELOG.md index e69c2f1521..6d9590063b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,25 @@ from published versions since it shows up in the VS Code extension changelog tab and is confusing to users. Add it back between releases if needed. --> +## Unreleased + +### Security + +- Workspace hosts now set `PermitLocalCommand no`, so a `LocalCommand` in your + SSH config no longer runs for workspaces. Add `PermitLocalCommand yes` to + `coder.sshConfig` to allow it. +- The deployment's SSH config options can no longer send your local + environment variables or sockets to the workspace: `SendEnv`, `SetEnv`, + `User` and `RemoteForward` from the deployment are ignored, with a warning. Set them in `coder.sshConfig` instead. + +### Fixed + +- `RemoteCommand` set through an SSH config `Include` or `Match` block is now + detected. +- The session type now reaches the workspace with every OpenSSH version. +- On Devin 3.12.32 and later, workspace hosts go into the file set in + `remote.devinSSH.configFile`. + ## [v1.18.2](https://github.com/coder/vscode-coder/releases/tag/v1.18.2) (Pre-release) 2026-11-20 ### Added diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 16916a0224..d164df590e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -66,10 +66,11 @@ connection: Host coder-cursor.dev.coder.com--* ConnectTimeout 0 LogLevel ERROR + PermitLocalCommand no ProxyCommand /tmp/coder --global-config /home/kyle/.config/Cursor/User/globalStorage/coder.coder-remote/dev.coder.com ssh --stdio --usage-app=cursor --network-info-dir /home/kyle/.config/Cursor/User/globalStorage/coder.coder-remote/net --ssh-host-prefix coder-cursor.dev.coder.com-- %h + SendEnv CODER_SSH_SESSION_TYPE ServerAliveCountMax 3 ServerAliveInterval 10 - SetEnv CODER_SSH_SESSION_TYPE=cursor StrictHostKeyChecking no UserKnownHostsFile /dev/null ``` @@ -78,16 +79,23 @@ Options merge from three sources, highest priority first: the `coder.sshConfig` setting, `--ssh-option` flags from a `coder config-ssh` block, and the deployment's SSH config. Only the deployment's options are deny-listed (`DENIED_DEPLOYMENT_KEYS` in `src/remote/sshConfig.ts`), since the -other two are the user's own. `SetEnv` is written only when the local ssh -supports it, and `--usage-app` only when both the CLI and the deployment -accept custom session app names; otherwise the session reports as `vscode`. +other two are the user's own. Deployment options that send local environment +variables or sockets to the workspace are ignored with a warning +(`IGNORED_DEPLOYMENT_KEYS`). The user's +`SetEnv` and `SendEnv` values accumulate across sources. The session app goes +to the CLI as `--usage-app` and to the agent as `CODER_SSH_SESSION_TYPE`, set in the +environment ssh inherits and forwarded with `SendEnv`. It is the editor's URI +scheme when both the CLI and the deployment accept custom session app names, +and `vscode` otherwise. + +After writing, `ssh -G` resolves the host with the Remote - SSH extension's ssh +executable, falling back to a built-in parser, to detect a `RemoteCommand`. Which main file gains the include depends on the Remote - SSH extension. Microsoft's and Cursor's pass `remote.SSH.configFile` to ssh with `-F`, and VSCodium's parses the file itself instead of running ssh, so all three connect -through it. Antigravity and Windsurf/Devin renamed the setting but spawn ssh -without `-F`, so ssh reads `~/.ssh/config` regardless; we ignore the renamed -setting there rather than add the include where the connection never looks. +through it. Devin passes `remote.devinSSH.configFile` from 3.12.32. Antigravity +spawns ssh without `-F`, so we ignore its renamed setting. If any step fails, we show an error message. Once the error message is closed we close the remote so the Remote - SSH connection does not continue to diff --git a/package.json b/package.json index ead870b336..3ab6f43ac4 100644 --- a/package.json +++ b/package.json @@ -61,7 +61,7 @@ "title": "Coder", "properties": { "coder.sshConfig": { - "markdownDescription": "These values will be included in the ssh config file. Eg: `'ConnectTimeout=10'` will set the timeout to 10 seconds. Any values included here will override anything provided by default or by the deployment. To unset a value that is written by default, set the value to the empty string, Eg: `'ConnectTimeout='` will unset it.\n\nNote: `SetEnv` values are accumulated across multiple entries and cannot be unset.", + "markdownDescription": "These values will be included in the ssh config file. Eg: `'ConnectTimeout=10'` will set the timeout to 10 seconds. Any values included here will override anything provided by default or by the deployment. To unset a value that is written by default, set the value to the empty string, Eg: `'ConnectTimeout='` will unset it.\n\nNote: `SetEnv` and `SendEnv` values are accumulated across multiple entries and cannot be unset.", "type": "array", "items": { "title": "SSH Config Value", diff --git a/src/remote/environment.ts b/src/remote/environment.ts index 696b455a4b..4d40b39da3 100644 --- a/src/remote/environment.ts +++ b/src/remote/environment.ts @@ -11,6 +11,8 @@ import type { import type { WatchedSetting } from "../configWatcher"; +export const SESSION_TYPE_ENV = "CODER_SSH_SESSION_TYPE"; + type Environment = Record; type SshProxyEnvironment = Partial< Record<"HTTP_PROXY" | "HTTPS_PROXY" | "NO_PROXY", string> @@ -49,8 +51,9 @@ export const SSH_PROXY_SETTINGS: ReadonlyArray< /** * Apply the SSH environment that the spawned `coder ssh` ProxyCommand inherits. * Includes the proxy config (HTTP_PROXY/HTTPS_PROXY/NO_PROXY), read by the coder - * CLI like any Go HTTP client, and the session ID via CODER_TRACE_SESSION_ID so - * the CLI reuses the plugin's session ID instead of generating its own. Applied + * CLI like any Go HTTP client, the session ID via CODER_TRACE_SESSION_ID so + * the CLI reuses the plugin's session ID instead of generating its own, and + * CODER_SSH_SESSION_TYPE, which ssh forwards to the agent through `SendEnv`. Applied * via both process.env (ssh spawned as a child, `remote.SSH.useLocalServer=true`) * and the terminal env collection (ssh spawned in a terminal, * `useLocalServer=false`, which can't see process.env), since the mode isn't @@ -63,11 +66,13 @@ export function applySshEnvironment( GlobalEnvironmentVariableCollection, "persistent" | "replace" | "clear" >, + sessionApp: string, env: Environment = process.env, ): { dispose(): void } { const values: Environment = { ...getSshProxyEnvironment(cfg), CODER_TRACE_SESSION_ID: sessionId, + [SESSION_TYPE_ENV]: sessionApp, }; const restoreEnv = applyEnvironment(values, env); diff --git a/src/remote/remote.ts b/src/remote/remote.ts index e17a0bb955..6058c19214 100644 --- a/src/remote/remote.ts +++ b/src/remote/remote.ts @@ -16,8 +16,11 @@ import { CoderApi } from "../api/coderApi"; import { HttpStatusCode } from "../api/httpStatusCode"; import { extractAgents } from "../api/models"; import { version as cliVersion } from "../cli/cliExec"; -import { expandPath } from "../common/fs"; -import { escapeCommandArg, escapeProxyCommandPath } from "../common/strings"; +import { + escapeCommandArg, + escapeProxyCommandPath, + lowercase, +} from "../common/strings"; import { CONFIG_CHANGE_DEBOUNCE_MS, watchConfigurationChanges, @@ -55,7 +58,11 @@ import { parseRemoteAuthority, sshHostOf, } from "./authority"; -import { applySshEnvironment, SSH_PROXY_SETTINGS } from "./environment"; +import { + applySshEnvironment, + SESSION_TYPE_ENV, + SSH_PROXY_SETTINGS, +} from "./environment"; import { migrateAuthToSecretsStorage } from "./migration"; import { SshConfig, @@ -65,12 +72,12 @@ import { parseSshConfig, validateDeploymentSshOptions, } from "./sshConfig"; -import { getRemoteSshConfigFile } from "./sshExtension"; +import { getRemoteSshConfigFile, getRemoteSshPath } from "./sshExtension"; import { applySettingOverrides, buildSshOverrides } from "./sshOverrides"; import { SshProcessMonitor } from "./sshProcess"; import { computeSshProperties, - sshSupportsSetEnv, + resolveSshProperties, type SshProperties, } from "./sshSupport"; import { createManagedPermissions } from "./windowsAcl"; @@ -264,12 +271,6 @@ export class Remote { const { args, parts, workspaceName, baseUrl, token, disposables } = context; try { - disposables.push( - applySshEnvironment( - vscode.workspace.getConfiguration(), - this.extensionContext.environmentVariableCollection, - ), - ); // Create OAuth session manager for this remote deployment const remoteOAuthManager = OAuthSessionManager.create( { url: baseUrl, safeHostname: parts.safeHostname }, @@ -325,6 +326,13 @@ export class Remote { safeHostname: parts.safeHostname, }), ); + disposables.push( + applySshEnvironment( + vscode.workspace.getConfiguration(), + this.extensionContext.environmentVariableCollection, + sessionApp, + ), + ); // Write token to keyring or file if (baseUrl && token !== undefined) { @@ -884,11 +892,6 @@ export class Remote { return ["--log-dir", escapeProxyCommandPath(logDir), "-v"]; } - private getMainSshConfigPath(): string { - const configured = getRemoteSshConfigFile(); - return expandPath(configured || path.join("~", ".ssh", "config")); - } - // updateSSHConfig updates the SSH configuration with a wildcard that handles // all Coder entries. private async updateSSHConfig({ @@ -901,8 +904,13 @@ export class Remote { }: SshConfigOptions): Promise { // Taken from the authority, so a legacy host keeps working. const { hostPrefix, safeHostname, sshHost } = parts; + // -F skips /etc/ssh/ssh_config, so use it only when Remote-SSH does. + const configFile = getRemoteSshConfigFile(); // One file per (host prefix, deployment); the user's config gains one shared include. - const sshConfig = new SshConfig(this.getMainSshConfigPath(), this.logger); + const sshConfig = new SshConfig( + configFile ?? path.join(os.homedir(), ".ssh", "config"), + this.logger, + ); await sshConfig.load(); // Never loaded: update() regenerates it without reading the old content. const coderConfig = new SshConfig( @@ -925,10 +933,15 @@ export class Remote { let deploymentSshConfig = {}; try { const deploymentConfig = await workspaceClient.getDeploymentSSHConfig(); - deploymentSshConfig = validateDeploymentSshOptions( + const { options, ignored } = validateDeploymentSshOptions( deploymentConfig.ssh_config_options, { ...configSshOptions, ...userConfig }, ); + deploymentSshConfig = options; + if (ignored.length > 0) { + this.logger.warn("Ignoring deployment SSH options", ignored); + this.warnIgnoredSshOptions(safeHostname, ignored); + } } catch (error) { if (!isAxiosError(error)) { throw error; @@ -969,13 +982,12 @@ export class Remote { ConnectTimeout: "0", StrictHostKeyChecking: "no", UserKnownHostsFile: "/dev/null", + PermitLocalCommand: "no", LogLevel: "ERROR", ServerAliveInterval: "10", ServerAliveCountMax: "3", + SendEnv: SESSION_TYPE_ENV, }; - if (sshSupportsSetEnv()) { - sshValues.SetEnv = `CODER_SSH_SESSION_TYPE=${sessionApp}`; - } // Write our file before including it, so the include never dangles. await coderConfig.update(sshValues, sshConfigOverrides); @@ -984,11 +996,40 @@ export class Remote { safeHostname, ); - // Mirror SSH's parse order; RemoteCommand can come from the user's config. - return computeSshProperties( - parts.sshHost, - `${coderConfig.getRaw()}\n${sshConfig.getRaw()}`, - ); + try { + return await resolveSshProperties( + getRemoteSshPath(), + parts.sshHost, + configFile, + ); + } catch (error) { + this.logger.warn("ssh -G failed, parsing the SSH config instead", error); + return computeSshProperties( + parts.sshHost, + `${coderConfig.getRaw()}\n${sshConfig.getRaw()}`, + ); + } + } + + /** Stays hidden while every ignored option was already dismissed. */ + private warnIgnoredSshOptions(safeHostname: string, ignored: string[]): void { + const memento = this.serviceContainer.getMementoManager(); + const dismissed = new Set(memento.getDismissedSshOptions(safeHostname)); + const keys = ignored.map(lowercase); + if (keys.every((key) => dismissed.has(key))) { + return; + } + const dontShow = "Don't Show Again"; + void vscode.window + .showWarningMessage( + `Ignored SSH options from the Coder deployment that could expose your machine: ${ignored.join(", ")}. To use them, add them to the "coder.sshConfig" setting.`, + dontShow, + ) + .then((choice) => + choice === dontShow + ? memento.addDismissedSshOptions(safeHostname, keys) + : undefined, + ); } private watchSettings( diff --git a/src/remote/sshConfig.ts b/src/remote/sshConfig.ts index 337387cf3b..d0fd48fd96 100644 --- a/src/remote/sshConfig.ts +++ b/src/remote/sshConfig.ts @@ -29,10 +29,11 @@ export interface SshValues { ConnectTimeout: string; StrictHostKeyChecking: string; UserKnownHostsFile: string; + PermitLocalCommand: string; LogLevel: string; ServerAliveInterval: string; ServerAliveCountMax: string; - SetEnv?: string; + SendEnv: string; } /** @@ -129,6 +130,18 @@ const DENIED_DEPLOYMENT_KEYS: ReadonlySet> = new Set([ "proxyjump", ]); +/** + * Options that send local environment variables (directly or through `${VAR}` + * expansion) or local sockets to the workspace. Ignored rather than rejected, + * since the server accepts them. + */ +const IGNORED_DEPLOYMENT_KEYS: ReadonlySet> = new Set([ + "sendenv", + "setenv", + "user", + "remoteforward", +]); + /** * Connection-critical options Coder always writes itself, so the error must * not suggest overriding them in coder.sshConfig. @@ -140,15 +153,15 @@ const PINNED_KEYS: ReadonlySet> = new Set([ ]); /** - * Validate SSH options sent by the Coder deployment. Keys in `userOverrides` - * are exempt from the deny list: the user's value wins the merge, so the - * deployment's value is never written. + * Validate SSH options sent by the Coder deployment, removing the ignored ones. + * Keys in `userOverrides` are exempt from the deny list: the user's value wins + * the merge, so the deployment's value is never written. * @throws {Error} when an option is malformed or denied. */ export function validateDeploymentSshOptions( options: Record, userOverrides: Record, -): Record { +): { options: Record; ignored: string[] } { validateSshConfigOptions(options); const overridden = new Set(Object.keys(userOverrides).map(lowercase)); const denied = Object.keys(options).filter((key) => { @@ -169,7 +182,15 @@ export function validateDeploymentSshOptions( } throw new Error(message); } - return options; + const ignored = Object.keys(options).filter((key) => + IGNORED_DEPLOYMENT_KEYS.has(lowercase(key)), + ); + return { + options: Object.fromEntries( + Object.entries(options).filter(([key]) => !ignored.includes(key)), + ), + ignored, + }; } /** Validate the key and value of every option in the record. */ @@ -220,7 +241,17 @@ export function parseCoderSshOptions(raw: string): Record { return parseSshConfig(sshOptionLines); } -/** Parse "Key value" or "Key=value" lines, accumulating SetEnv values. */ +/** Directives ssh accumulates across lines, so merged values extend them. */ +const ACCUMULATED_KEYS: Readonly> = { + setenv: "SetEnv", + sendenv: "SendEnv", +}; + +function accumulate(existing: string | undefined, value: string): string { + return [existing, value].filter(Boolean).join(" "); +} + +/** Parse "Key value" or "Key=value" lines, accumulating SetEnv and SendEnv. */ export function parseSshConfig(lines: string[]): Record { return lines.reduce( (acc, line) => { @@ -237,10 +268,10 @@ export function parseSshConfig(lines: string[]): Record { const value = line.slice(key.length + 1); - if (key.toLowerCase() === "setenv") { + const accumulated = ACCUMULATED_KEYS[key.toLowerCase()]; + if (accumulated) { if (value !== "") { - const existing = acc["SetEnv"]; - acc["SetEnv"] = existing ? `${existing} ${value}` : value; + acc[accumulated] = accumulate(acc[accumulated], value); } } else { acc[key] = value; @@ -270,13 +301,9 @@ export function mergeSshConfigValues( const value = overrides[correctCaseKey]; delete caseInsensitiveOverrides[lower]; - // SetEnv concatenates instead of replacing. - if (lower === "setenv") { - if (value === "") { - merged["SetEnv"] = config[key]; - } else { - merged["SetEnv"] = `${config[key]} ${value}`; - } + const accumulated = ACCUMULATED_KEYS[lower]; + if (accumulated) { + merged[accumulated] = accumulate(config[key], value); return; } @@ -296,8 +323,9 @@ export function mergeSshConfigValues( const correctCaseKey = caseInsensitiveOverrides[lower]; const value = overrides[correctCaseKey]; - if (lower === "setenv" && merged["SetEnv"]) { - merged["SetEnv"] = `${merged["SetEnv"]} ${value}`; + const accumulated = ACCUMULATED_KEYS[lower]; + if (accumulated && merged[accumulated]) { + merged[accumulated] = accumulate(merged[accumulated], value); } else { merged[correctCaseKey] = value; } diff --git a/src/remote/sshExtension.ts b/src/remote/sshExtension.ts index 5aca747b81..1d182e9e34 100644 --- a/src/remote/sshExtension.ts +++ b/src/remote/sshExtension.ts @@ -1,5 +1,12 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; +import * as semver from "semver"; import * as vscode from "vscode"; +import { expandPath } from "../common/fs"; + +import type { WorkspaceConfiguration } from "vscode"; + export const REMOTE_SSH_EXTENSION_IDS = [ "jeanp413.open-remote-ssh", "codeium.windsurf-remote-openssh", @@ -11,32 +18,70 @@ export const REMOTE_SSH_EXTENSION_IDS = [ export type RemoteSshExtensionId = (typeof REMOTE_SSH_EXTENSION_IDS)[number]; /** - * Extensions that spawn ssh without `-F`, so it always reads ~/.ssh/config - * and their renamed configFile setting never applies. + * VS Code Remote-SSH log layout, shared by the live SSH monitor and the + * support-bundle collector so a future layout change updates one place. */ -const IGNORED_CONFIG_FILE: readonly RemoteSshExtensionId[] = [ - "google.antigravity-remote-openssh", - "codeium.windsurf-remote-openssh", -]; +const OUTPUT_LOGGING_DIR_PREFIX = "output_logging_"; +const REMOTE_SSH_LOG_NAME_FRAGMENT = "Remote - SSH"; + +const DEVIN_CONFIG_FILE_VERSION = "3.12.32"; -/** The SSH config file the active extension connects through, if configured. */ +/** + * The SSH config file the active extension passes to ssh with `-F`, if any. + * Antigravity reads its own setting but never passes it. + */ export function getRemoteSshConfigFile(): string | undefined { - const id = getRemoteSshExtension()?.id; - if (id && IGNORED_CONFIG_FILE.includes(id)) { - return undefined; + const config = vscode.workspace.getConfiguration(); + switch (getRemoteSshExtension()?.id) { + case "google.antigravity-remote-openssh": + return undefined; + case "codeium.windsurf-remote-openssh": + return devinPassesConfigFile() + ? getPath( + config, + devinOrWindsurfKey(config, "remote.devinSSH.configFile"), + ) + : undefined; + default: + return getPath(config, "remote.SSH.configFile"); } - return ( - vscode.workspace.getConfiguration("remote.SSH").get("configFile") || - undefined - ); } -/** - * VS Code Remote-SSH log layout, shared by the live SSH monitor and the - * support-bundle collector so a future layout change updates one place. - */ -const OUTPUT_LOGGING_DIR_PREFIX = "output_logging_"; -const REMOTE_SSH_LOG_NAME_FRAGMENT = "Remote - SSH"; +/** The ssh executable the active extension launches, if one is configured. */ +export function getRemoteSshPath(): string | undefined { + const config = vscode.workspace.getConfiguration(); + switch (getRemoteSshExtension()?.id) { + case "google.antigravity-remote-openssh": + return getPath(config, "remote.antigravitySSH.path"); + case "codeium.windsurf-remote-openssh": + return getPath( + config, + devinOrWindsurfKey(config, "remote.devinSSH.path"), + ); + case "jeanp413.open-remote-ssh": + // Its default `ssh2` backend is a JavaScript client with no ssh binary. + return config.get("remote.SSH.connectionBackend") === "native" + ? getPath(config, "remote.SSH.path") + : undefined; + default: + return getPath(config, "remote.SSH.path"); + } +} + +/** Devin reads deprecated Windsurf values only when its own key is unset. */ +export function devinOrWindsurfKey( + config: Pick, + key: string, +): string { + if ( + !key.startsWith("remote.devinSSH.") || + hasExplicitValue(config.inspect(key)) + ) { + return key; + } + const fallbackKey = key.replace("remote.devinSSH.", "remote.windsurfSSH."); + return hasExplicitValue(config.inspect(fallbackKey)) ? fallbackKey : key; +} /** True if `dirName` is the exthost dir of a known Remote-SSH extension. */ export function isRemoteSshExtensionDir(dirName: string): boolean { @@ -66,3 +111,44 @@ export function getRemoteSshExtension(): RemoteSshExtension | undefined { } return undefined; } + +function getPath( + config: Pick, + key: string, +): string | undefined { + const value = config.get(key); + return value ? expandPath(value) : undefined; +} + +/** + * Its extension is always 0.0.1, so check the editor's version. + * https://docs.devin.ai/desktop/changelog#v3-12-32 + */ +function devinPassesConfigFile(): boolean { + try { + const product = fs.readFileSync( + path.join(vscode.env.appRoot, "product.json"), + "utf8", + ); + const { windsurfVersion } = JSON.parse(product) as { + windsurfVersion?: unknown; + }; + return ( + typeof windsurfVersion === "string" && + semver.gte(windsurfVersion, DEVIN_CONFIG_FILE_VERSION) + ); + } catch { + return false; + } +} + +function hasExplicitValue( + setting: ReturnType, +): boolean { + return ( + setting !== undefined && + (setting.globalValue !== undefined || + setting.workspaceValue !== undefined || + setting.workspaceFolderValue !== undefined) + ); +} diff --git a/src/remote/sshOverrides.ts b/src/remote/sshOverrides.ts index ccfb8a062c..6a9b5951f2 100644 --- a/src/remote/sshOverrides.ts +++ b/src/remote/sshOverrides.ts @@ -3,6 +3,7 @@ import * as jsonc from "jsonc-parser"; import * as fs from "node:fs/promises"; import { + devinOrWindsurfKey, getRemoteSshExtension, type RemoteSshExtensionId, } from "./sshExtension"; @@ -123,7 +124,7 @@ export function buildSshOverrides( } for (const { name, key } of getSshSettings(config)) { - const effectiveKey = effectiveSettingKey(config, key); + const effectiveKey = devinOrWindsurfKey(config, key); if (name === "connectTimeout") { // Default 15s is too short for startup scripts; enforce a minimum. const timeout = config.get(effectiveKey); @@ -206,32 +207,6 @@ function getSshSettings(config: Pick) { ); } -/** Devin reads deprecated Windsurf values only when its own key is unset. */ -function effectiveSettingKey( - config: Pick, - key: string, -): string { - if ( - !key.startsWith("remote.devinSSH.") || - hasExplicitValue(config.inspect(key)) - ) { - return key; - } - const fallbackKey = key.replace("remote.devinSSH.", "remote.windsurfSSH."); - return hasExplicitValue(config.inspect(fallbackKey)) ? fallbackKey : key; -} - -function hasExplicitValue( - setting: ReturnType, -): boolean { - return ( - setting !== undefined && - (setting.globalValue !== undefined || - setting.workspaceValue !== undefined || - setting.workspaceFolderValue !== undefined) - ); -} - /** * Whether the given RemoteCommand value represents an active command * (i.e. present, non-empty, and not the SSH default "none"). diff --git a/src/remote/sshSupport.ts b/src/remote/sshSupport.ts index 74053bbbeb..d1f119348f 100644 --- a/src/remote/sshSupport.ts +++ b/src/remote/sshSupport.ts @@ -1,50 +1,12 @@ import * as childProcess from "child_process"; +import { promisify } from "node:util"; import { escapeRegExp, lowercase } from "../common/strings"; +import { getCliProcessEnv } from "../settings/cli"; -/** - * Matches the OpenSSH version number from `ssh -V` output. - * [^,]* prevents greedy matching across comma-separated components. - */ -const openSSHVersionRegex = /OpenSSH[^,]*_([\d.]+)/; - -/** Check if the local SSH installation supports the `SetEnv` directive. */ -export function sshSupportsSetEnv(): boolean { - try { - // Run `ssh -V` to get the version string. - const spawned = childProcess.spawnSync("ssh", ["-V"]); - // The version string outputs to stderr. - return sshVersionSupportsSetEnv(spawned.stderr.toString().trim()); - } catch { - return false; - } -} +const execFile = promisify(childProcess.execFile); -/** - * Check if an SSH version string supports the `SetEnv` directive. - * Requires OpenSSH 7.8 or later. - */ -export function sshVersionSupportsSetEnv(sshVersionString: string): boolean { - const match = openSSHVersionRegex.exec(sshVersionString); - if (match?.[1]) { - const installedVersion = match[1]; - const parts = installedVersion.split("."); - if (parts.length < 2) { - return false; - } - // 7.8 is the first version that supports SetEnv - const major = Number.parseInt(parts[0], 10); - const minor = Number.parseInt(parts[1], 10); - if (major < 7) { - return false; - } - if (major === 7 && minor < 8) { - return false; - } - return true; - } - return false; -} +const RESOLVE_TIMEOUT_MS = 5_000; /** OpenSSH `Host` pattern: `*` matches any run of characters, `?` exactly one. */ function matchesHostPattern(host: string, pattern: string): boolean { @@ -63,6 +25,41 @@ function matchesHostPattern(host: string, pattern: string): boolean { /** Keyed by lowercase directive name, so wrong-cased lookups fail to compile. */ export type SshProperties = Record, string>; +/** + * Effective SSH properties for a host as OpenSSH resolves them (`ssh -G`), + * following Include and Match. Runs `sshPath`, or `ssh` on PATH when unset. + * @throws {Error} when ssh is a Windows batch file (which needs a shell), + * fails, times out, or resolves no ProxyCommand, meaning it never read the + * Coder config (a different ssh build or home directory). + */ +export async function resolveSshProperties( + sshPath: string | undefined, + host: string, + configFile: string | undefined, +): Promise { + const ssh = sshPath || "ssh"; + if (process.platform === "win32" && /\.(bat|cmd)$/i.test(ssh)) { + throw new Error(`${ssh} is a batch file, which needs a shell to run`); + } + const configArgs = configFile ? ["-F", configFile] : []; + const { stdout } = await execFile(ssh, ["-G", ...configArgs, "--", host], { + env: getCliProcessEnv(), + timeout: RESOLVE_TIMEOUT_MS, + }); + + const properties: SshProperties = {}; + for (const line of stdout.split(/\r?\n/)) { + const space = line.indexOf(" "); + if (space > 0) { + properties[lowercase(line.slice(0, space))] ??= line.slice(space + 1); + } + } + if (!properties.proxycommand) { + throw new Error("ssh -G resolved no ProxyCommand"); + } + return properties; +} + interface HostBlock { host: string; properties: Array<[key: Lowercase, value: string]>; diff --git a/src/storage/mementoManager.ts b/src/storage/mementoManager.ts index e479654ea7..59a3e12bf6 100644 --- a/src/storage/mementoManager.ts +++ b/src/storage/mementoManager.ts @@ -9,8 +9,9 @@ const MAX_URLS = 10; const DEPLOYMENT_ACCESS_PREFIX = "coder.access."; const SURFACED_BANNERS_PREFIX = "coder.surfacedBanners."; +const DISMISSED_SSH_OPTIONS_PREFIX = "coder.dismissedSshOptions."; -const SurfacedBannersSchema = z.array(z.string()); +const KeysSchema = z.array(z.string()); /** Pending values expire after this duration to guard against stale * state from crashes or interrupted reloads. */ @@ -108,42 +109,53 @@ export class MementoManager { } public getSurfacedBanners(safeHostname: string): string[] { - const raw = this.memento.get( - `${SURFACED_BANNERS_PREFIX}${safeHostname}`, - ); - const result = SurfacedBannersSchema.safeParse(raw); - return result.success ? result.data : []; + return this.getKeys(SURFACED_BANNERS_PREFIX + safeHostname); } - /** - * Merge banner keys into the surfaced set. The read-modify-write lives - * here so a future atomic Memento update can be adopted in one place. - */ - public async addSurfacedBanners( + public addSurfacedBanners( safeHostname: string, bannerKeys: readonly string[], ): Promise { - const existing = this.getSurfacedBanners(safeHostname); - const merged = new Set([...existing, ...bannerKeys]); - if (merged.size > existing.length) { - await this.memento.update(`${SURFACED_BANNERS_PREFIX}${safeHostname}`, [ - ...merged, - ]); - } + return this.addKeys(SURFACED_BANNERS_PREFIX + safeHostname, bannerKeys); + } + + public getDismissedSshOptions(safeHostname: string): string[] { + return this.getKeys(DISMISSED_SSH_OPTIONS_PREFIX + safeHostname); + } + + public addDismissedSshOptions( + safeHostname: string, + options: readonly string[], + ): Promise { + return this.addKeys(DISMISSED_SSH_OPTIONS_PREFIX + safeHostname, options); } - /** Clear all per-deployment state (access timestamp, surfaced banners). */ + /** Clear all per-deployment state (access timestamp, stored key sets). */ public async clearDeploymentData(safeHostname: string): Promise { - await Promise.all([ - this.memento.update( - `${DEPLOYMENT_ACCESS_PREFIX}${safeHostname}`, - undefined, - ), - this.memento.update( - `${SURFACED_BANNERS_PREFIX}${safeHostname}`, - undefined, - ), - ]); + await Promise.all( + [ + DEPLOYMENT_ACCESS_PREFIX, + SURFACED_BANNERS_PREFIX, + DISMISSED_SSH_OPTIONS_PREFIX, + ].map((prefix) => this.memento.update(prefix + safeHostname, undefined)), + ); + } + + private getKeys(key: string): string[] { + const result = KeysSchema.safeParse(this.memento.get(key)); + return result.success ? result.data : []; + } + + /** + * Merge keys into a stored set. The read-modify-write lives here so a + * future atomic Memento update can be adopted in one place. + */ + private async addKeys(key: string, keys: readonly string[]): Promise { + const existing = this.getKeys(key); + const merged = new Set([...existing, ...keys]); + if (merged.size > existing.length) { + await this.memento.update(key, [...merged]); + } } private async setStamped(key: string, value: T): Promise { diff --git a/test/integration/proxy.test.ts b/test/integration/proxy.test.ts index 7c5c4fb98d..60657e7849 100644 --- a/test/integration/proxy.test.ts +++ b/test/integration/proxy.test.ts @@ -24,6 +24,7 @@ suite("Proxy", () => { const sshEnvironment = applySshEnvironment( vscode.workspace.getConfiguration(), envCollection, + "vscode", ); try { diff --git a/test/unit/remote/environment.test.ts b/test/unit/remote/environment.test.ts index 56122c4ee1..70bb8b230b 100644 --- a/test/unit/remote/environment.test.ts +++ b/test/unit/remote/environment.test.ts @@ -17,7 +17,10 @@ import { } from "../../mocks/testHelpers"; const proxyEnv = { HTTP_PROXY: proxy, HTTPS_PROXY: proxy }; -const sessionEnv = { CODER_TRACE_SESSION_ID: sessionId }; +const sessionEnv = { + CODER_TRACE_SESSION_ID: sessionId, + CODER_SSH_SESSION_TYPE: "vscode", +}; type Environment = Record; beforeEach(() => { @@ -121,6 +124,7 @@ describe("applySshEnvironment", () => { const applied = applySshEnvironment( config(withProxy({ "coder.proxyBypass": "internal.example.com" })), collection, + "vscode", env, ); @@ -133,11 +137,11 @@ describe("applySshEnvironment", () => { expect(collection.vars).toEqual({}); }); - it("sets the session ID even when no proxy is configured", () => { + it("sets the session ID and type even when no proxy is configured", () => { const env: Environment = {}; const collection = fakeEnvCollection(); - applySshEnvironment(config(), collection, env); + applySshEnvironment(config(), collection, "vscode", env); expect(env).toEqual(sessionEnv); expect(collection.vars).toEqual(sessionEnv); @@ -154,6 +158,7 @@ describe("applySshEnvironment", () => { applySshEnvironment( config(withProxy({ "http.proxySupport": "off" })), collection, + "vscode", env, ); @@ -171,6 +176,7 @@ describe("applySshEnvironment", () => { const applied = applySshEnvironment( config(withProxy()), fakeEnvCollection(), + "vscode", env, ); @@ -187,6 +193,7 @@ describe("applySshEnvironment", () => { const applied = applySshEnvironment( config(withProxy()), fakeEnvCollection(), + "vscode", env, ); expect(env.HTTP_PROXY).toBe(proxy); @@ -201,6 +208,7 @@ describe("applySshEnvironment", () => { const applied = applySshEnvironment( config(withProxy()), fakeEnvCollection(), + "vscode", ); try { @@ -215,6 +223,7 @@ describe("applySshEnvironment", () => { const applied = applySshEnvironment( config(withProxy()), fakeEnvCollection(), + "vscode", ); try { diff --git a/test/unit/remote/remote.test.ts b/test/unit/remote/remote.test.ts index e8ae00cf34..f86706f48a 100644 --- a/test/unit/remote/remote.test.ts +++ b/test/unit/remote/remote.test.ts @@ -14,7 +14,7 @@ import { Remote, workspaceLabelSuffix, } from "@/remote/remote"; -import { sshSupportsSetEnv } from "@/remote/sshSupport"; +import { resolveSshProperties } from "@/remote/sshSupport"; import { MementoManager } from "@/storage/mementoManager"; import { PathResolver } from "@/storage/pathResolver"; import { SecretsManager } from "@/storage/secretsManager"; @@ -80,7 +80,7 @@ vi.mock(import("@/cli/cliExec"), async (importOriginal) => ({ })); vi.mock(import("@/remote/sshSupport"), async (importOriginal) => ({ ...(await importOriginal()), - sshSupportsSetEnv: vi.fn(), + resolveSshProperties: vi.fn(), })); const SAFE_HOSTNAME = "coder.example.com"; @@ -493,7 +493,10 @@ describe("Remote", () => { command.replace(/--network-info-dir \S+/, "--network-info-dir "); describe("session app", () => { - function mockClient(version = "2.38.0") { + function mockClient( + version = "2.38.0", + sshConfigOptions: Record = {}, + ) { const client = new Api(); vi.spyOn(client, "getBuildInfo").mockResolvedValue({ version, @@ -509,7 +512,7 @@ describe("Remote", () => { vi.spyOn(client, "getDeploymentSSHConfig").mockResolvedValue({ hostname_prefix: "", hostname_suffix: "", - ssh_config_options: {}, + ssh_config_options: sshConfigOptions, }); return client; } @@ -566,13 +569,15 @@ describe("Remote", () => { }, ); - async function writeConfig(setEnv = true) { - const { remote } = createRemote(); + async function writeConfig( + sshConfigOptions?: Record, + { remote } = createRemote(), + ) { useEditor("cursor"); - vi.mocked(sshSupportsSetEnv).mockReturnValue(setEnv); + vi.mocked(resolveSshProperties).mockRejectedValue(new Error("no ssh")); const method = "writeRemoteSshConfig"; return remote[method]({ - workspaceClient: mockClient(), + workspaceClient: mockClient(undefined, sshConfigOptions), parts: parseRemoteAuthority(REMOTE_AUTHORITY)!, binaryPath: "/mock/coder", logDir: "/mock/log", @@ -581,14 +586,33 @@ describe("Remote", () => { }); } - it("writes the same verbatim app name to both SSH mechanisms", async () => { + it("writes the app name and forwards the session type", async () => { const config = await writeConfig(); expect(config.proxycommand).toContain("--usage-app=future-editor-next "); - expect(config.setenv).toBe("CODER_SSH_SESSION_TYPE=future-editor-next"); + expect(config.sendenv).toBe("CODER_SSH_SESSION_TYPE"); + expect(config.permitlocalcommand).toBe("no"); }); - it("omits SetEnv when unsupported by OpenSSH", async () => { - expect((await writeConfig(false)).setenv).toBeUndefined(); + it("ignores deployment SetEnv and SendEnv, warning until dismissed", async () => { + const context = createRemote(); + context.userInteraction.setResponse(/^Ignored SSH/, "Don't Show Again"); + const config = await writeConfig( + { SetEnv: "CODER_SSH_SESSION_TYPE=spoofed", SendEnv: "SECRET" }, + context, + ); + expect(config.setenv).toBeUndefined(); + expect(config.sendenv).toBe("CODER_SSH_SESSION_TYPE"); + await flush(); + + // A dismissed subset stays hidden; a new option warns again. + await writeConfig({ sendenv: "SECRET" }, context); + await writeConfig({ SendEnv: "SECRET", User: "x" }, context); + expect( + context.userInteraction.getMessageCalls().map((call) => call.message), + ).toEqual([ + expect.stringContaining(": SetEnv, SendEnv."), + expect.stringContaining(": SendEnv, User."), + ]); }); }); diff --git a/test/unit/remote/sshConfig.openssh.test.ts b/test/unit/remote/sshConfig.openssh.test.ts index b8ffaf7d11..a0984b8b98 100644 --- a/test/unit/remote/sshConfig.openssh.test.ts +++ b/test/unit/remote/sshConfig.openssh.test.ts @@ -24,9 +24,11 @@ const sshValues = ( ConnectTimeout: "0", StrictHostKeyChecking: "no", UserKnownHostsFile: "/dev/null", + PermitLocalCommand: "no", LogLevel: "ERROR", ServerAliveInterval: "10", ServerAliveCountMax: "3", + SendEnv: "CODER_SSH_SESSION_TYPE", }); let tempDir: string | undefined; diff --git a/test/unit/remote/sshConfig.test.ts b/test/unit/remote/sshConfig.test.ts index 80e9348d21..622a1aa336 100644 --- a/test/unit/remote/sshConfig.test.ts +++ b/test/unit/remote/sshConfig.test.ts @@ -42,9 +42,11 @@ const BASE_SSH_VALUES = { ConnectTimeout: "0", StrictHostKeyChecking: "no", UserKnownHostsFile: "/dev/null", + PermitLocalCommand: "no", LogLevel: "ERROR", ServerAliveInterval: "10", ServerAliveCountMax: "3", + SendEnv: "CODER_SSH_SESSION_TYPE", } as const satisfies SshValues; const USER_OVERRIDES = { @@ -55,14 +57,15 @@ const USER_OVERRIDES = { const BENIGN_DEPLOYMENT_OPTIONS = { ConnectTimeout: "30", IdentityFile: "~/.ssh/coder identity", - SetEnv: "CODER_SSH_SESSION_TYPE=vscode", serveraliveinterval: "5", } as const; const deploymentBlock = `Host coder-vscode.dev.coder.com--* ConnectTimeout 0 LogLevel ERROR + PermitLocalCommand no ProxyCommand some-command-here + SendEnv CODER_SSH_SESSION_TYPE ServerAliveCountMax 3 ServerAliveInterval 10 StrictHostKeyChecking no @@ -178,7 +181,9 @@ describe("SshConfig.update", () => { Host coder-vscode.dev.coder.com--* ConnectTimeout 500 ExtraKey ExtraValue + PermitLocalCommand no ProxyCommand some-command-here + SendEnv CODER_SSH_SESSION_TYPE ServerAliveCountMax 3 ServerAliveInterval 10 UserKnownHostsFile /dev/null @@ -611,9 +616,15 @@ describe("parseSshConfig", () => { expected: { ConnectTimeout: "10", LogLevel: "DEBUG" }, }, { - name: "accumulates non-empty SetEnv values", - input: ["SetEnv A=1", "setenv=B=2 C=3", "SetEnv="], - expected: { SetEnv: "A=1 B=2 C=3" }, + name: "accumulates non-empty SetEnv and SendEnv values", + input: [ + "SetEnv A=1", + "setenv=B=2 C=3", + "SetEnv=", + "SendEnv X", + "sendenv Y", + ], + expected: { SetEnv: "A=1 B=2 C=3", SendEnv: "X Y" }, }, { name: "skips malformed lines", @@ -646,10 +657,10 @@ describe("mergeSshConfigValues", () => { expected: { Add: "value" }, }, { - name: "combines SetEnv and ignores an empty override", - config: { SetEnv: "A=1" }, - overrides: { setenv: "B=2" }, - expected: { SetEnv: "A=1 B=2" }, + name: "combines SetEnv and SendEnv overrides", + config: { SetEnv: "A=1", SendEnv: "X" }, + overrides: { setenv: "B=2", sendenv: "Y" }, + expected: { SetEnv: "A=1 B=2", SendEnv: "X Y" }, }, { name: "keeps SetEnv for an empty override", @@ -768,6 +779,22 @@ describe("validateDeploymentSshOptions", () => { ).not.toThrow(); }); + it("ignores options that expose the client even when the user sets them", () => { + const ignored = { + setenv: "A=1", + SENDENV: "SECRET", + User: "${SECRET}", + RemoteForward: "/tmp/d /var/run/docker.sock", + }; + const kept = { ConnectTimeout: "30", LocalForward: "8080 localhost:80" }; + expect( + validateDeploymentSshOptions( + { ...ignored, ...kept }, + { SetEnv: "B=2", User: "me" }, + ), + ).toEqual({ options: kept, ignored: Object.keys(ignored) }); + }); + it("collects every denied option into one error", () => { expect(() => validateDeploymentSshOptions( diff --git a/test/unit/remote/sshExtension.test.ts b/test/unit/remote/sshExtension.test.ts index a59fc2211c..6dce3bf7fc 100644 --- a/test/unit/remote/sshExtension.test.ts +++ b/test/unit/remote/sshExtension.test.ts @@ -1,53 +1,106 @@ -import { describe, expect, it, vi } from "vitest"; +import { vol } from "memfs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { expect, it, vi } from "vitest"; import * as vscode from "vscode"; -import { getRemoteSshConfigFile } from "@/remote/sshExtension"; +import { + getRemoteSshConfigFile, + getRemoteSshPath, +} from "@/remote/sshExtension"; import { config, type Settings } from "../../mocks/testHelpers"; -/** Activate `extensionId`, or no Remote-SSH extension when empty. */ -function setup(extensionId: string, settings: Settings = {}): void { +vi.mock("node:fs", async () => (await import("memfs")).fs); + +const ANTIGRAVITY = "google.antigravity-remote-openssh"; +const DEVIN = "codeium.windsurf-remote-openssh"; +const OPEN_REMOTE_SSH = "jeanp413.open-remote-ssh"; + +/** Activate `id` (none when empty), inside a Devin build when versioned. */ +function setup(id: string, settings: Settings, windsurfVersion?: string) { config(settings); - vi.mocked(vscode.extensions.getExtension).mockImplementation((id) => - id === extensionId ? ({ id } as vscode.Extension) : undefined, + vol.reset(); + if (windsurfVersion) { + const product = path.join(vscode.env.appRoot, "product.json"); + vol.fromJSON({ [product]: JSON.stringify({ windsurfVersion }) }); + } + vi.mocked(vscode.extensions.getExtension).mockImplementation((extId) => + extId === id ? ({ id } as vscode.Extension) : undefined, ); } -describe("getRemoteSshConfigFile", () => { - it.each([ - "ms-vscode-remote.remote-ssh", - "anysphere.remote-ssh", - "jeanp413.open-remote-ssh", - ])("reads the configured file for %s", (extensionId) => { - setup(extensionId, { "remote.SSH.configFile": "/custom/config" }); - - expect(getRemoteSshConfigFile()).toBe("/custom/config"); - }); - - it.each([ - ["google.antigravity-remote-openssh", "remote.antigravitySSH.configFile"], - ["codeium.windsurf-remote-openssh", "remote.devinSSH.configFile"], - ])( - "ignores the file %s never connects through", - (extensionId, settingKey) => { - setup(extensionId, { - [settingKey]: "/custom/config", - "remote.SSH.configFile": "/stale/config", - }); - - expect(getRemoteSshConfigFile()).toBeUndefined(); - }, - ); - - it("reads remote.SSH when no extension is installed", () => { - setup("", { "remote.SSH.configFile": "/custom/config" }); +it.each(["ms-vscode-remote.remote-ssh", "anysphere.remote-ssh", ""])( + "reads and expands remote.SSH settings for '%s'", + (id) => { + setup(id, { + "remote.SSH.configFile": "~/cfg", + "remote.SSH.path": "/ssh", + }); - expect(getRemoteSshConfigFile()).toBe("/custom/config"); - }); + expect(getRemoteSshConfigFile()).toBe(`${os.homedir()}/cfg`); + expect(getRemoteSshPath()).toBe("/ssh"); + }, +); - it("returns undefined when nothing is configured", () => { - setup("ms-vscode-remote.remote-ssh"); +it.each<[string, string, Settings, string | undefined, string?]>([ + [ + "open-remote-ssh", + OPEN_REMOTE_SSH, + { "remote.SSH.configFile": "/cfg" }, + "/cfg", + ], + [ + "Antigravity", + ANTIGRAVITY, + { "remote.antigravitySSH.configFile": "/cfg" }, + undefined, + ], + [ + "Devin before 3.12.32", + DEVIN, + { "remote.devinSSH.configFile": "/cfg" }, + undefined, + "3.11.238", + ], + [ + "Devin of unknown version", + DEVIN, + { "remote.devinSSH.configFile": "/cfg" }, + undefined, + ], + [ + "Devin from 3.12.32", + DEVIN, + { "remote.devinSSH.configFile": "/cfg" }, + "/cfg", + "3.12.32", + ], +])("config file for %s", (_name, id, settings, expected, windsurfVersion) => { + setup( + id, + { "remote.SSH.configFile": "/stale", ...settings }, + windsurfVersion, + ); + expect(getRemoteSshConfigFile()).toBe(expected); +}); - expect(getRemoteSshConfigFile()).toBeUndefined(); - }); +it.each<[string, string, Settings, string | undefined]>([ + [ + "Antigravity", + ANTIGRAVITY, + { "remote.antigravitySSH.path": "/ssh" }, + "/ssh", + ], + ["Devin", DEVIN, { "remote.devinSSH.path": "/ssh" }, "/ssh"], + ["open-remote-ssh's ssh2 backend", OPEN_REMOTE_SSH, {}, undefined], + [ + "open-remote-ssh's native backend", + OPEN_REMOTE_SSH, + { "remote.SSH.path": "/ssh", "remote.SSH.connectionBackend": "native" }, + "/ssh", + ], +])("ssh path for %s", (_name, id, settings, expected) => { + setup(id, { "remote.SSH.path": "/stale", ...settings }); + expect(getRemoteSshPath()).toBe(expected); }); diff --git a/test/unit/remote/sshSupport.test.ts b/test/unit/remote/sshSupport.test.ts index 6157f5695c..ce000f5a8b 100644 --- a/test/unit/remote/sshSupport.test.ts +++ b/test/unit/remote/sshSupport.test.ts @@ -1,38 +1,75 @@ -import { describe, it, expect } from "vitest"; +import { spawnSync } from "node:child_process"; +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { describe, it, expect, onTestFinished } from "vitest"; import { computeSshProperties, - sshSupportsSetEnv, - sshVersionSupportsSetEnv, + resolveSshProperties, } from "@/remote/sshSupport"; -const supports = { - "OpenSSH_8.9p1 Ubuntu-3ubuntu0.1, OpenSSL 3.0.2 15 Mar 2022": true, - "OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2": true, - "OpenSSH_9.0p1, LibreSSL 3.3.6": true, - // Version extracted from OpenSSH, not from LibreSSL after the comma - "OpenSSH_7.4p1, LibreSSL_8.1.0": false, - "OpenSSH_7.6p1 Ubuntu-4ubuntu0.7, OpenSSL 1.0.2n 7 Dec 2017": false, - "OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017": false, -}; - -Object.entries(supports).forEach(([version, expected]) => { - it(version, () => { - expect(sshVersionSupportsSetEnv(version)).toBe(expected); - }); -}); - -/** - * Spawning real `ssh` is slow on Windows CI runners, so allow a larger budget there. - */ -it( - "current shell supports ssh", - { timeout: process.platform === "win32" ? 30_000 : undefined }, +describe.skipIf(spawnSync("ssh", ["-V"]).error)( + "resolveSshProperties", + { timeout: 30_000 }, () => { - expect(sshSupportsSetEnv()).toBeTruthy(); + it("follows Include and Match with ssh on PATH", async () => { + // Windows OpenSSH reads only ~/ include paths as absolute. + const dir = await fs.mkdtemp(path.join(os.homedir(), "coder-ssh-g-")); + onTestFinished(() => fs.rm(dir, { recursive: true, force: true })); + const config = path.join(dir, "config"); + const included = path.join(dir, "included"); + const includePath = path + .relative(os.homedir(), included) + .replaceAll("\\", "/"); + await fs.writeFile( + config, + `Host coder-*\n ProxyCommand coder ssh %h\n PermitLocalCommand no\nMatch all\n Include "~/${includePath}"\n`, + ); + await fs.writeFile( + included, + "Host *\n RemoteCommand tmux attach\n PermitLocalCommand yes\n", + ); + + const properties = await resolveSshProperties( + undefined, + "coder-ws", + config, + ); + expect(properties.remotecommand).toBe("tmux attach"); + expect(properties.permitlocalcommand).toBe("no"); + }); + + it("rejects a broken config", async () => { + const missing = path.join(os.tmpdir(), "coder-ssh-g-missing", "config"); + await expect( + resolveSshProperties(undefined, "coder-ws", missing), + ).rejects.toThrow(); + }); + + it("rejects a config without the Coder ProxyCommand", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "coder-ssh-g-")); + onTestFinished(() => fs.rm(dir, { recursive: true, force: true })); + const config = path.join(dir, "config"); + await fs.writeFile(config, "Host other\n ProxyCommand coder ssh %h\n"); + await expect( + resolveSshProperties(undefined, "coder-ws", config), + ).rejects.toThrow("ProxyCommand"); + }); }, ); +it("rejects a Windows batch file without running it", async () => { + const realPlatform = process.platform; + Object.defineProperty(process, "platform", { value: "win32" }); + onTestFinished(() => { + Object.defineProperty(process, "platform", { value: realPlatform }); + }); + await expect( + resolveSshProperties("C:\\wrappers\\ssh.BAT", "coder-ws", undefined), + ).rejects.toThrow("batch"); +}); + describe("computeSshProperties", () => { it("computes the config for a host", () => { const properties = computeSshProperties( diff --git a/test/unit/remote/windowsAcl.native.test.ts b/test/unit/remote/windowsAcl.native.test.ts index 5a48f5ea06..025819a3e2 100644 --- a/test/unit/remote/windowsAcl.native.test.ts +++ b/test/unit/remote/windowsAcl.native.test.ts @@ -182,9 +182,11 @@ function sshValues(host: string, proxyCommand: string): SshValues { ConnectTimeout: "0", StrictHostKeyChecking: "no", UserKnownHostsFile: "NUL", + PermitLocalCommand: "no", LogLevel: "ERROR", ServerAliveInterval: "10", ServerAliveCountMax: "3", + SendEnv: "CODER_SSH_SESSION_TYPE", }; } diff --git a/test/unit/storage/mementoManager.test.ts b/test/unit/storage/mementoManager.test.ts index a411de04ef..5c728eac38 100644 --- a/test/unit/storage/mementoManager.test.ts +++ b/test/unit/storage/mementoManager.test.ts @@ -123,16 +123,29 @@ describe("MementoManager", () => { }); }); + it("stores dismissed SSH options apart from surfaced banners", async () => { + await mementoManager.addDismissedSshOptions("example.com", ["sendenv"]); + await mementoManager.addDismissedSshOptions("example.com", ["user"]); + + expect(mementoManager.getDismissedSshOptions("example.com")).toEqual([ + "sendenv", + "user", + ]); + expect(mementoManager.getSurfacedBanners("example.com")).toEqual([]); + }); + describe("deployment data", () => { - it("clears access timestamp and surfaced banners together", async () => { + it("clears access timestamp and stored key sets together", async () => { await mementoManager.updateDeploymentAccess("example.com"); await mementoManager.addSurfacedBanners("example.com", ["one"]); + await mementoManager.addDismissedSshOptions("example.com", ["user"]); expect(mementoManager.getDeploymentAccess("example.com")).toBeDefined(); await mementoManager.clearDeploymentData("example.com"); expect(mementoManager.getDeploymentAccess("example.com")).toBeUndefined(); expect(mementoManager.getSurfacedBanners("example.com")).toEqual([]); + expect(mementoManager.getDismissedSshOptions("example.com")).toEqual([]); }); });