Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@

## 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.

### Added

- A Workspaces panel is now the Coder Remote sidebar, replacing the legacy My
Expand All @@ -32,6 +38,19 @@
to `false`. No reload is needed, and **Switch to Workspaces Panel** switches
back.

### 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`.
- A window that crashed or lost power no longer shows as an ongoing
connection in the connection log for days: the workspace agent now closes the
connection once it stops answering keep-alives, on the same schedule as
`ServerAliveInterval` and `ServerAliveCountMax`. Needs an agent that supports
it.

## [v1.18.1](https://github.com/coder/vscode-coder/releases/tag/v1.18.1) 2026-11-18

### Security
Expand Down
23 changes: 16 additions & 7 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 CODER_SSH_CLIENT_ALIVE_INTERVAL CODER_SSH_CLIENT_ALIVE_COUNT_MAX
ServerAliveCountMax 3
ServerAliveInterval 10
SetEnv CODER_SSH_SESSION_TYPE=cursor
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
```
Expand All @@ -78,16 +79,24 @@ 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. `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. Any `SetEnv`
of that variable is dropped, since ssh sends it after `SendEnv`. The resolved
`ServerAliveInterval` and `ServerAliveCountMax` are forwarded the same way, as
`CODER_SSH_CLIENT_ALIVE_INTERVAL` and `CODER_SSH_CLIENT_ALIVE_COUNT_MAX`, so the
agent closes a connection whose client stopped answering on the same schedule.

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
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
56 changes: 49 additions & 7 deletions src/remote/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ import type {

import type { WatchedSetting } from "../configWatcher";

import type { SshProperties } from "./sshSupport";

export const SESSION_TYPE_ENV = "CODER_SSH_SESSION_TYPE";
export const CLIENT_ALIVE_INTERVAL_ENV = "CODER_SSH_CLIENT_ALIVE_INTERVAL";
export const CLIENT_ALIVE_COUNT_MAX_ENV = "CODER_SSH_CLIENT_ALIVE_COUNT_MAX";

type Environment = Record<string, string | undefined>;
type SshProxyEnvironment = Partial<
Record<"HTTP_PROXY" | "HTTPS_PROXY" | "NO_PROXY", string>
Expand Down Expand Up @@ -49,8 +55,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
Expand All @@ -63,22 +70,20 @@ 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);

collection.persistent = false;
// Drop stale vars from a prior connect (e.g. NO_PROXY set last time, not now).
collection.clear();
for (const [key, value] of Object.entries(values)) {
if (value) {
collection.replace(key, value);
}
}
replaceInCollection(collection, values);

return {
dispose() {
Expand All @@ -88,6 +93,43 @@ export function applySshEnvironment(
};
}

/**
* Forward the resolved `ServerAliveInterval` and `ServerAliveCountMax` through
* `SendEnv`, so the agent drops a dead connection on the same schedule.
*/
export function applyClientAliveEnvironment(
collection: Pick<GlobalEnvironmentVariableCollection, "replace" | "delete">,
properties: SshProperties,
env: Environment = process.env,
): { dispose(): void } {
const values: Environment = {
[CLIENT_ALIVE_INTERVAL_ENV]: properties.serveraliveinterval,
[CLIENT_ALIVE_COUNT_MAX_ENV]: properties.serveralivecountmax,
};
const restoreEnv = applyEnvironment(values, env);
replaceInCollection(collection, values);

return {
dispose() {
restoreEnv.dispose();
for (const key of Object.keys(values)) {
collection.delete(key);
}
},
};
}

function replaceInCollection(
collection: Pick<GlobalEnvironmentVariableCollection, "replace">,
values: Environment,
): void {
for (const [key, value] of Object.entries(values)) {
if (value) {
collection.replace(key, value);
}
}
}

/** The proxy portion of the SSH environment, derived from VS Code's settings. */
export function getSshProxyEnvironment(
cfg: Pick<WorkspaceConfiguration, "get">,
Expand Down
79 changes: 52 additions & 27 deletions src/remote/remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ 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 {
CONFIG_CHANGE_DEBOUNCE_MS,
Expand Down Expand Up @@ -55,7 +54,14 @@ import {
parseRemoteAuthority,
sshHostOf,
} from "./authority";
import { applySshEnvironment, SSH_PROXY_SETTINGS } from "./environment";
import {
applyClientAliveEnvironment,
applySshEnvironment,
CLIENT_ALIVE_COUNT_MAX_ENV,
CLIENT_ALIVE_INTERVAL_ENV,
SESSION_TYPE_ENV,
SSH_PROXY_SETTINGS,
} from "./environment";
import { migrateAuthToSecretsStorage } from "./migration";
import {
SshConfig,
Expand All @@ -64,13 +70,14 @@ import {
parseCoderSshOptions,
parseSshConfig,
validateDeploymentSshOptions,
withoutSetEnv,
} 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";
Expand Down Expand Up @@ -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 },
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -425,6 +433,12 @@ export class Remote {
}),
);
const remoteCommand = computedSshProperties.remotecommand;
disposables.push(
applyClientAliveEnvironment(
this.extensionContext.environmentVariableCollection,
computedSshProperties,
),
);

this.logger.info("Modifying settings...");
const overrides = buildSshOverrides(
Expand Down Expand Up @@ -884,11 +898,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({
Expand All @@ -901,8 +910,13 @@ export class Remote {
}: SshConfigOptions): Promise<SshProperties> {
// 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(
Expand Down Expand Up @@ -949,9 +963,13 @@ export class Remote {
// 2. coder config-ssh --ssh-option flags from the CLI block
// 3. Deployment SSH config from the coderd API
// Only 3 is deny listed; 1 and 2 are the user's own options.
const sshConfigOverrides = mergeSshConfigValues(
mergeSshConfigValues(deploymentSshConfig, configSshOptions),
userConfig,
// SetEnv is sent after SendEnv, so it would replace the session type.
const sshConfigOverrides = withoutSetEnv(
mergeSshConfigValues(
mergeSshConfigValues(deploymentSshConfig, configSshOptions),
userConfig,
),
SESSION_TYPE_ENV,
);

const proxyCommand = buildSshProxyCommand({
Expand All @@ -969,13 +987,12 @@ export class Remote {
ConnectTimeout: "0",
StrictHostKeyChecking: "no",
UserKnownHostsFile: "/dev/null",
PermitLocalCommand: "no",
LogLevel: "ERROR",
ServerAliveInterval: "10",
ServerAliveCountMax: "3",
SendEnv: `${SESSION_TYPE_ENV} ${CLIENT_ALIVE_INTERVAL_ENV} ${CLIENT_ALIVE_COUNT_MAX_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);
Expand All @@ -984,11 +1001,19 @@ 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()}`,
);
}
}

private watchSettings(
Expand Down
Loading