Skip to content

Commit a0152be

Browse files
authored
fix(ssh): include the Coder SSH config on Windows when HOME differs (#1211)
On Windows the shared SSH Include was written as `~/AppData/...`. Both Win32-OpenSSH and Git for Windows ssh expand `~` from HOME when it is set, so with HOME on another drive (e.g. a network home `H:\`) the include matched nothing, the workspace host lost its ProxyCommand, and the connection failed. Regression since #1061. - Keep the `~/...` Include when ssh expands `~` to the profile (HOME unset or equal to it, compared by real path). Output is unchanged for almost everyone. - Otherwise write the absolute path in both spellings Windows builds read: `C:/...` (Win32-OpenSSH 8.1+) and `/c/...` (MSYS builds like Git for Windows). Each build skips the one it can't match, so nothing is included twice. UNC data dirs stay a single `//server/share/...` argument. - Also write the include block to `HOME/.ssh/config` when HOME is a drive or UNC path, since Git ssh without `-F` reads it. Failures only warn. - Write `%` in Include paths as the glob `?`, since OpenSSH 9.9+ expands `%` tokens and older builds don't. Such paths used to throw. - Run the post-write `ssh -G` check with `-v` so a missing ProxyCommand error lists the files ssh read and the includes that matched nothing. Closes VSC-58 Refs VSC-8, #1197
1 parent ae685e9 commit a0152be

9 files changed

Lines changed: 383 additions & 46 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
- The session type now reaches the workspace with every OpenSSH version.
2424
- On Devin 3.12.32 and later, workspace hosts go into the file set in
2525
`remote.devinSSH.configFile`.
26+
- On Windows, workspaces connect again when `HOME` points somewhere other than
27+
your user profile, with both Windows OpenSSH and Git for Windows ssh.
28+
- SSH config paths containing `%` no longer stop workspaces from connecting.
2629

2730
## [v1.18.2](https://github.com/coder/vscode-coder/releases/tag/v1.18.2) (Pre-release) 2026-11-20
2831

‎docs/ARCHITECTURE.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ Include "~/.local/share/coder.coder-remote/ssh/*.conf"
5555
# --- END CODER INCLUDE CODER-REMOTE ---
5656
```
5757

58+
On Windows, ssh expands `~` from `HOME` when it is set, else from the profile,
59+
and the include is relative to that directory. When the data directory is
60+
outside it, Windows gets the absolute path twice instead: `C:/...` for Windows
61+
OpenSSH and `/c/...` for Git for Windows ssh. Each build skips the spelling it
62+
cannot match. Without `-F`, Git for Windows ssh reads `$HOME/.ssh/config`, so
63+
that file gains the include block too. A `%` in the path is written as the glob `?`, since OpenSSH
64+
9.9 and later expand `%` tokens in `Include` and older versions don't.
65+
5866
Each generated file contains only its own editor's host entries for one
5967
deployment, with keys sorted. The extension rewrites the whole file on every
6068
connection:

‎src/remote/remote.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ import {
6565
} from "./environment";
6666
import { migrateAuthToSecretsStorage } from "./migration";
6767
import {
68+
getHomeSshConfigPath,
69+
getSshHomeDir,
6870
SshConfig,
6971
type SshValues,
7072
mergeSshConfigValues,
@@ -991,10 +993,26 @@ export class Remote {
991993

992994
// Write our file before including it, so the include never dangles.
993995
await coderConfig.update(sshValues, sshConfigOverrides);
994-
await sshConfig.updateInclude(
995-
this.pathResolver.getSshConfigDir(),
996-
safeHostname,
997-
);
996+
const includeDir = this.pathResolver.getSshConfigDir();
997+
const sshHomeDir = await getSshHomeDir();
998+
await sshConfig.updateInclude(includeDir, sshHomeDir, safeHostname);
999+
// Without -F, Git for Windows ssh reads HOME's config, not the profile's.
1000+
const homeConfigPath = getHomeSshConfigPath(sshHomeDir);
1001+
if (!configFile && homeConfigPath) {
1002+
try {
1003+
await new SshConfig(homeConfigPath, this.logger).updateInclude(
1004+
includeDir,
1005+
sshHomeDir,
1006+
safeHostname,
1007+
);
1008+
} catch (error) {
1009+
this.logger.warn(
1010+
"Failed to include the Coder SSH config in",
1011+
homeConfigPath,
1012+
error,
1013+
);
1014+
}
1015+
}
9981016

9991017
try {
10001018
return await resolveSshProperties(

‎src/remote/sshConfig.ts‎

Lines changed: 92 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
mkdir,
33
readFile,
44
readdir,
5+
realpath,
56
rename,
67
stat,
78
unlink,
@@ -78,6 +79,12 @@ const KEY_ONLY_REGEX = /^[a-zA-Z0-9-]+$/;
7879
/** Characters that would break a value out of its config line. */
7980
const UNSAFE_CHARS_REGEX = /[\r\n\0]/;
8081

82+
/** A drive (`C:\`) or UNC (`\\server`) path, unlike MSYS `/c/...`. */
83+
const DRIVE_OR_UNC_PATH_REGEX = /^([a-z]:[\\/]|[\\/]{2}[^\\/])/i;
84+
85+
/** The drive of a forward-slashed Windows path, such as `C:/`. */
86+
const DRIVE_PREFIX_REGEX = /^([a-z]):\//i;
87+
8188
interface BlockMarkers {
8289
start: string;
8390
end: string;
@@ -101,6 +108,53 @@ const INCLUDE_MARKERS: BlockMarkers = {
101108
end: "# --- END CODER INCLUDE CODER-REMOTE ---",
102109
};
103110

111+
/**
112+
* The directory ssh expands `~` from: `HOME` on Windows, where every build
113+
* reads it, unless it is the profile under another spelling. Otherwise
114+
* exactly `os.homedir()`.
115+
*/
116+
export async function getSshHomeDir(): Promise<string> {
117+
const home = process.env.HOME;
118+
const profile = os.homedir();
119+
if (process.platform !== "win32" || !home) {
120+
return profile;
121+
}
122+
const key = (dir: string) => path.resolve(dir).toLowerCase();
123+
if (key(home) === key(profile)) {
124+
return profile;
125+
}
126+
// The real path sees through 8.3 names, junctions and subst drives.
127+
const realKey = (dir: string) => realpath(dir).then(key, () => key(dir));
128+
const [realHome, realProfile] = await Promise.all([
129+
realKey(home),
130+
realKey(profile),
131+
]);
132+
return realHome === realProfile ? profile : home;
133+
}
134+
135+
/**
136+
* The config Git for Windows ssh reads without `-F` when ssh's home is not
137+
* the profile. Undefined for the profile, which is already included, and for
138+
* MSYS homes like `/c/home`, which only MSYS can map to a Windows path.
139+
*/
140+
export function getHomeSshConfigPath(sshHomeDir: string): string | undefined {
141+
if (
142+
sshHomeDir === os.homedir() ||
143+
!DRIVE_OR_UNC_PATH_REGEX.test(sshHomeDir)
144+
) {
145+
return undefined;
146+
}
147+
return path.join(sshHomeDir, ".ssh", "config");
148+
}
149+
150+
/** `C:/Users/...` as MSYS builds such as Git for Windows spell it: `/c/Users/...`. */
151+
function toMsysPath(dir: string): string {
152+
return dir.replace(
153+
DRIVE_PREFIX_REGEX,
154+
(_, drive: string) => `/${drive.toLowerCase()}/`,
155+
);
156+
}
157+
104158
/** Header of the generated per-deployment file. */
105159
const CODER_SSH_CONFIG_HEADER = `# Coder workspace hosts. Do not edit; the Coder extension rewrites this file
106160
# on every connection. Override options with the "coder.sshConfig" setting.`;
@@ -371,8 +425,14 @@ export class SshConfig {
371425
* blocks. Read-modify-write with no locking, like the CLI's config-ssh;
372426
* when the include is already in place nothing is written.
373427
*/
374-
async updateInclude(includeDir: string, safeHostname: string) {
375-
const block = this.renderIncludeBlock(includeDir);
428+
async updateInclude(
429+
includeDir: string,
430+
sshHomeDir: string,
431+
safeHostname: string,
432+
) {
433+
const block = this.renderIncludeBlock(
434+
this.includeArguments(includeDir, sshHomeDir),
435+
);
376436
const raw = await this.read();
377437
this.raw = this.mergeInclude(raw, block, safeHostname);
378438
if (this.raw !== raw) {
@@ -435,32 +495,47 @@ export class SshConfig {
435495
return { start, end: endMarkerStart + markers.end.length };
436496
}
437497

438-
private renderIncludeBlock(includeDir: string): string {
498+
private renderIncludeBlock(includeArguments: string[]): string {
439499
return [
440500
INCLUDE_MARKERS.start,
441501
"# Managed by the Coder extension for VS Code and its forks.",
442502
"# Moves back to the top on connect; override options via coder.sshConfig.",
443-
`Include "${this.escapeIncludePath(includeDir)}/*${SSH_CONFIG_EXT}"`,
503+
`Include ${includeArguments
504+
.map((dir) => `"${this.escapeIncludePath(dir)}/*${SSH_CONFIG_EXT}"`)
505+
.join(" ")}`,
444506
INCLUDE_MARKERS.end,
445507
].join("\n");
446508
}
447509

448-
private escapeIncludePath(includePath: string): string {
449-
// Emit ~/... so home-path quirks (spaces, %, glob chars) never reach ssh.
450-
const relative = path.relative(os.homedir(), includePath);
451-
const argument =
452-
relative && !relative.startsWith("..") && !path.isAbsolute(relative)
453-
? `~/${relative}`
454-
: includePath;
455-
// No escape exists for '"' in quoted arguments; OpenSSH 9.9+ fatals on
456-
// unknown %-tokens in Include arguments.
457-
if (/[\r\n\0"%]/.test(argument)) {
510+
/**
511+
* `~/...` under ssh's home. Otherwise the absolute path, which Windows gets
512+
* in both builds' spellings since each skips the one it cannot match.
513+
*/
514+
private includeArguments(includeDir: string, sshHomeDir: string): string[] {
515+
const relative = path.relative(sshHomeDir, includeDir);
516+
if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) {
517+
return [`~/${relative}`];
518+
}
519+
if (process.platform !== "win32") {
520+
return [includeDir];
521+
}
522+
const dir = includeDir.replaceAll("\\", "/");
523+
return [...new Set([dir, toMsysPath(dir)])];
524+
}
525+
526+
private escapeIncludePath(argument: string): string {
527+
// No escape exists for '"' in quoted arguments.
528+
if (/[\r\n\0"]/.test(argument)) {
458529
throw new Error(
459-
"SSH include path must not contain CR, LF, NUL, %, or double-quote characters.",
530+
"SSH include path must not contain CR, LF, NUL, or double-quote characters.",
460531
);
461532
}
462-
// Bracket classes, since OpenSSH for Windows can't backslash-escape.
463-
return argument.replaceAll("\\", "/").replace(/[*?[]/g, "[$&]");
533+
// Bracket classes, since OpenSSH for Windows can't backslash-escape. `?`
534+
// stands in for `%`, which only OpenSSH 9.9+ expands as a token.
535+
return argument
536+
.replaceAll("\\", "/")
537+
.replace(/[*?[]/g, "[$&]")
538+
.replaceAll("%", "?");
464539
}
465540

466541
private mergeInclude(

‎src/remote/sshSupport.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ export async function resolveSshProperties(
4242
throw new Error(`${ssh} is a batch file, which needs a shell to run`);
4343
}
4444
const configArgs = configFile ? ["-F", configFile] : [];
45-
const { stdout } = await execFile(ssh, ["-G", ...configArgs, "--", host], {
45+
// -v logs the version and every file read to stderr, never to stdout.
46+
const args = ["-v", "-G", ...configArgs, "--", host];
47+
const { stdout, stderr } = await execFile(ssh, args, {
4648
env: getCliProcessEnv(),
4749
timeout: RESOLVE_TIMEOUT_MS,
4850
});
@@ -55,7 +57,7 @@ export async function resolveSshProperties(
5557
}
5658
}
5759
if (!properties.proxycommand) {
58-
throw new Error("ssh -G resolved no ProxyCommand");
60+
throw new Error(`ssh -G resolved no ProxyCommand\n${stderr.trim()}`);
5961
}
6062
return properties;
6163
}

‎test/unit/remote/remote.test.ts‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
Remote,
1515
workspaceLabelSuffix,
1616
} from "@/remote/remote";
17+
import { getHomeSshConfigPath } from "@/remote/sshConfig";
1718
import { resolveSshProperties } from "@/remote/sshSupport";
1819
import { MementoManager } from "@/storage/mementoManager";
1920
import { PathResolver } from "@/storage/pathResolver";
@@ -82,6 +83,10 @@ vi.mock(import("@/remote/sshSupport"), async (importOriginal) => ({
8283
...(await importOriginal()),
8384
resolveSshProperties: vi.fn(),
8485
}));
86+
vi.mock(import("@/remote/sshConfig"), async (importOriginal) => ({
87+
...(await importOriginal()),
88+
getHomeSshConfigPath: vi.fn(),
89+
}));
8590

8691
const SAFE_HOSTNAME = "coder.example.com";
8792
const REMOTE_AUTHORITY =
@@ -103,7 +108,7 @@ const CLI_AUTH: CliAuth = {
103108
};
104109

105110
function createRemote(logger: Logger = createMockLogger()) {
106-
new MockConfigurationProvider();
111+
const config = new MockConfigurationProvider();
107112
const userInteraction = new MockUserInteraction();
108113
const pathResolver = new PathResolver("/mock/global", "/mock/log");
109114
vol.fromJSON({
@@ -143,6 +148,7 @@ function createRemote(logger: Logger = createMockLogger()) {
143148
{} as Commands,
144149
{} as vscode.ExtensionContext,
145150
),
151+
config,
146152
ensureLoggedInWithDialog,
147153
mementoManager,
148154
secretsManager,
@@ -614,6 +620,45 @@ describe("Remote", () => {
614620
expect.stringContaining(": SendEnv, User."),
615621
]);
616622
});
623+
624+
describe("HOME ssh config on Windows", () => {
625+
const homeConfig = "/h/.ssh/config";
626+
627+
/** Connects while Git for Windows ssh would read `homeConfig`. */
628+
async function writeWithHomeConfig(configFile?: string) {
629+
vi.mocked(getHomeSshConfigPath).mockReturnValue(homeConfig);
630+
const logger = createMockLogger();
631+
const context = createRemote(logger);
632+
context.config.set("remote.SSH.configFile", configFile);
633+
await writeConfig(undefined, context);
634+
return logger;
635+
}
636+
637+
interface HomeConfigCase {
638+
configFile?: string;
639+
included: boolean;
640+
}
641+
it.each<HomeConfigCase>([
642+
{ included: true },
643+
{ configFile: "/mock/ssh/config", included: false },
644+
])(
645+
"includes the Coder config: $included with -F $configFile",
646+
async ({ configFile, included }) => {
647+
await writeWithHomeConfig(configFile);
648+
expect(vol.existsSync(homeConfig)).toBe(included);
649+
},
650+
);
651+
652+
it("warns and still connects when it cannot be written", async () => {
653+
vol.fromJSON({ "/h": "not a directory" });
654+
const logger = await writeWithHomeConfig();
655+
expect(logger.warn).toHaveBeenCalledWith(
656+
"Failed to include the Coder SSH config in",
657+
homeConfig,
658+
expect.any(Error),
659+
);
660+
});
661+
});
617662
});
618663

619664
describe("ProxyCommand", () => {

0 commit comments

Comments
 (0)