Skip to content

Commit 96a19c0

Browse files
committed
fix(ssh): address review of the Git for Windows include
- Keep the ~/ include when HOME is unset and every build's home is the profile: Windows OpenSSH reads /c/... as \c\... on the current drive, which any local user can create. - Bound the Git config write with a 5 second timeout, since a domain home may be on an unreachable share. - Warn when Remote-SSH's ssh resolves no ProxyCommand, naming the include directory and the config files ssh read. - Trim leading whitespace in mergeInclude so a second include is a no-op. - Rename getGitSshConfigPath to getGitForWindowsSshConfigPath and DRIVE_PREFIX_REGEX to FORWARD_SLASH_DRIVE_REGEX. - Run the Windows path tests on every platform, share the home env test helpers, and fix docs, comments and the changelog.
1 parent 697c4a1 commit 96a19c0

10 files changed

Lines changed: 345 additions & 157 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,11 @@
99

1010
### Fixed
1111

12-
- On Windows, workspaces connect again with Git for Windows ssh when your home
13-
folder is a network drive such as `H:\` and `HOME` is not set.
12+
- On Windows, workspaces connect with Git for Windows ssh when your home folder
13+
is a network drive such as `H:\` or a UNC path and `HOME` is not set, and
14+
when `HOME` is in MSYS form such as `/h`.
15+
- When Remote-SSH's ssh does not read the Coder SSH config, a warning names the
16+
config files it read instead of leaving a generic connection error.
1417
- On Windows, workspaces connect with Windows OpenSSH 7.x, such as the one built
1518
into Windows Server 2019, when `HOME` points somewhere other than your user
1619
profile, and with every Windows OpenSSH version when `HOME` contains

‎docs/ARCHITECTURE.md‎

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

58-
On Windows, each ssh build expands `~` from a different home, so the include
59-
gets the absolute path instead, in two spellings: `/C:/...` for Windows
60-
OpenSSH (before 8.0 it reads no other absolute spelling) and `/c/...` for Git
61-
for Windows ssh. Each build skips the spelling it cannot match. Without `-F`,
62-
Git for Windows ssh reads `.ssh/config` in its own home: `HOME`, else
63-
`HOMEDRIVE` and `HOMEPATH`, which a domain home folder sets, else the profile.
64-
That file gains the include block too.
58+
On Windows, Windows OpenSSH expands `~` from `HOME`, else the profile. Git for
59+
Windows ssh uses `HOME`, else `HOMEDRIVE` and `HOMEPATH`, which Windows sets
60+
at logon: the profile by default, a network drive such as `H:\` for a domain
61+
home folder. The include keeps `~/...` when `HOME` is unset and both homes are
62+
the profile. Otherwise a drive path gets `/C:/...` for Windows OpenSSH (before
63+
8.0 its only absolute spelling) and `/c/...` for Git for Windows ssh, and each
64+
build skips the other; a UNC path gets `//server/...`. The default setup
65+
avoids `/c/...` because Windows OpenSSH reads it as `\c\...` on the current
66+
drive, a folder any local user can create.
67+
68+
Without `-F`, Git for Windows ssh reads `.ssh/config` in its own home, so that
69+
file gains the include block too. The extension waits at most 5 seconds for
70+
it, since a domain home may be on an unreachable share.
6571

6672
The extension writes a `%` left in the include path as `?` because OpenSSH
6773
9.9 and later expand `%` tokens in `Include` and older versions don't. The

‎src/remote/remote.ts‎

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { extractAgents } from "../api/models";
1818
import { version as cliVersion } from "../cli/cliExec";
1919
import {
2020
escapeCommandArg,
21+
escapeNotificationLinks,
2122
escapeProxyCommandPath,
2223
lowercase,
2324
} from "../common/strings";
@@ -65,7 +66,7 @@ import {
6566
} from "./environment";
6667
import { migrateAuthToSecretsStorage } from "./migration";
6768
import {
68-
getGitSshConfigPath,
69+
getGitForWindowsSshConfigPath,
6970
SshConfig,
7071
type SshValues,
7172
mergeSshConfigValues,
@@ -79,6 +80,7 @@ import { SshProcessMonitor } from "./sshProcess";
7980
import {
8081
computeSshProperties,
8182
resolveSshProperties,
83+
SshProxyCommandMissingError,
8284
type SshProperties,
8385
} from "./sshSupport";
8486
import { createManagedPermissions } from "./windowsAcl";
@@ -100,6 +102,9 @@ import type { PathResolver } from "../storage/pathResolver";
100102
import type { SecretsManager, SessionAuth } from "../storage/secretsManager";
101103
import type { ContextManager } from "../vscode/contextManager";
102104

105+
/** Git's home may be an unreachable share; don't stall the connect on it. */
106+
const GIT_SSH_CONFIG_TIMEOUT_MS = 5_000;
107+
103108
export interface RemoteDetails extends vscode.Disposable {
104109
safeHostname: string;
105110
url: string;
@@ -994,20 +999,21 @@ export class Remote {
994999
await coderConfig.update(sshValues, sshConfigOverrides);
9951000
const includeDir = this.pathResolver.getSshConfigDir();
9961001
await sshConfig.updateInclude(includeDir, safeHostname);
997-
// Without -F, Git for Windows ssh reads its own home's config, which a
998-
// domain home folder moves off the profile even when HOME is unset. When
999-
// it is the profile's config, the include is already there: no write.
1000-
const gitConfigPath = getGitSshConfigPath();
1002+
// Without -F, Git for Windows ssh reads its own home's config. When that
1003+
// is the profile's config, the include is already there: no write.
1004+
const gitConfigPath = getGitForWindowsSshConfigPath();
10011005
if (!configFile && gitConfigPath) {
10021006
try {
1003-
await new SshConfig(gitConfigPath, this.logger).updateInclude(
1004-
includeDir,
1005-
safeHostname,
1007+
await raceWithAbort(
1008+
new SshConfig(gitConfigPath, this.logger).updateInclude(
1009+
includeDir,
1010+
safeHostname,
1011+
),
1012+
AbortSignal.timeout(GIT_SSH_CONFIG_TIMEOUT_MS),
10061013
);
10071014
} catch (error) {
10081015
this.logger.warn(
1009-
"Failed to include the Coder SSH config in",
1010-
gitConfigPath,
1016+
`Failed to include the Coder SSH config in ${gitConfigPath}, so Git for Windows ssh will not find Coder hosts`,
10111017
error,
10121018
);
10131019
}
@@ -1020,6 +1026,9 @@ export class Remote {
10201026
configFile,
10211027
);
10221028
} catch (error) {
1029+
if (error instanceof SshProxyCommandMissingError) {
1030+
this.warnCoderSshConfigNotRead(includeDir, error.configFiles);
1031+
}
10231032
this.logger.warn("ssh -G failed, parsing the SSH config instead", error);
10241033
return computeSshProperties(
10251034
parts.sshHost,
@@ -1028,6 +1037,19 @@ export class Remote {
10281037
}
10291038
}
10301039

1040+
/** Remote-SSH's ssh ran but missed the include, so the connection will fail. */
1041+
private warnCoderSshConfigNotRead(
1042+
includeDir: string,
1043+
configFiles: string[],
1044+
): void {
1045+
const read = configFiles.join(", ") || "no SSH config";
1046+
void vscode.window.showWarningMessage(
1047+
escapeNotificationLinks(
1048+
`Remote-SSH's ssh did not read the Coder SSH config in ${includeDir}, so it cannot reach Coder workspaces. It read ${read}. Check which ssh Remote-SSH uses and its home directory.`,
1049+
),
1050+
);
1051+
}
1052+
10311053
/** Stays hidden while every ignored option was already dismissed. */
10321054
private warnIgnoredSshOptions(safeHostname: string, ignored: string[]): void {
10331055
const memento = this.serviceContainer.getMementoManager();

‎src/remote/sshConfig.ts‎

Lines changed: 75 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ const UNSAFE_CHARS_REGEX = /[\r\n\0]/;
8282
const DRIVE_OR_UNC_PATH_REGEX = /^([a-z]:[\\/]|[\\/]{2}[^\\/])/i;
8383

8484
/** The drive of a forward-slashed Windows path, such as `C:/`. */
85-
const DRIVE_PREFIX_REGEX = /^([a-z]):\//i;
85+
const FORWARD_SLASH_DRIVE_REGEX = /^([a-z]):\//i;
8686

8787
/** The drive of an MSYS path, such as `/h` or `/h/dir`. */
8888
const MSYS_DRIVE_REGEX = /^\/([a-z])(?=\/|$)/i;
@@ -111,14 +111,25 @@ const INCLUDE_MARKERS: BlockMarkers = {
111111
};
112112

113113
/**
114-
* The config Git for Windows ssh reads without `-F` when its home is set by
115-
* the environment: `HOME`, else `HOMEDRIVE` and `HOMEPATH`, which a domain
116-
* home folder sets (the `env` scheme of its `db_home` default). An MSYS `HOME`
117-
* like `/h` is `H:\`, where Git mounts drives. Undefined when Git falls back to
118-
* the profile, off Windows, and for MSYS homes like `/home/jane` under Git's
119-
* install directory. May be the profile's config under another spelling.
114+
* The config Git for Windows ssh reads without `-F`. Undefined off Windows,
115+
* when Git uses the profile, and for an MSYS home such as `/home/jane`. May
116+
* name the profile's config.
120117
*/
121-
export function getGitSshConfigPath(): string | undefined {
118+
export function getGitForWindowsSshConfigPath(): string | undefined {
119+
const home = getGitForWindowsHome();
120+
return home ? path.win32.join(home, ".ssh", "config") : undefined;
121+
}
122+
123+
/**
124+
* Git for Windows ssh's home as a Windows path:
125+
* - `HOME`, where an MSYS drive like `/h` is `H:\`.
126+
* - Else `HOMEDRIVE` + `HOMEPATH`, which Windows sets at logon: the profile
127+
* by default, a network drive such as `H:\` for a domain home folder.
128+
*
129+
* Undefined off Windows, when neither is set (Git uses the profile), and for
130+
* an MSYS home such as `/home/jane`.
131+
*/
132+
function getGitForWindowsHome(): string | undefined {
122133
const { HOME, HOMEDRIVE, HOMEPATH } = process.env;
123134
const home =
124135
HOME || (HOMEDRIVE && HOMEPATH ? HOMEDRIVE + HOMEPATH : undefined);
@@ -129,15 +140,35 @@ export function getGitSshConfigPath(): string | undefined {
129140
MSYS_DRIVE_REGEX,
130141
(_, drive: string) => `${drive.toUpperCase()}:\\`,
131142
);
132-
return DRIVE_OR_UNC_PATH_REGEX.test(windowsHome)
133-
? path.win32.join(windowsHome, ".ssh", "config")
143+
return DRIVE_OR_UNC_PATH_REGEX.test(windowsHome) ? windowsHome : undefined;
144+
}
145+
146+
/**
147+
* Whether every Windows ssh build expands `~` to the profile. Not when `HOME`
148+
* is set, even to the profile, since Windows OpenSSH misreads a non-ASCII one.
149+
*/
150+
function windowsSshHomeIsProfile(): boolean {
151+
if (process.env.HOME) {
152+
return false;
153+
}
154+
const gitHome = getGitForWindowsHome();
155+
const key = (dir: string) => path.win32.resolve(dir).toLowerCase();
156+
return gitHome === undefined || key(gitHome) === key(os.homedir());
157+
}
158+
159+
/** `dir` relative to the home directory, or undefined when outside it. */
160+
function homeRelativePath(dir: string): string | undefined {
161+
const pathApi = process.platform === "win32" ? path.win32 : path.posix;
162+
const relative = pathApi.relative(os.homedir(), dir);
163+
return relative && !relative.startsWith("..") && !pathApi.isAbsolute(relative)
164+
? relative
134165
: undefined;
135166
}
136167

137168
/** `C:/Users/...` as MSYS builds such as Git for Windows spell it: `/c/Users/...`. */
138169
function toMsysPath(dir: string): string {
139170
return dir.replace(
140-
DRIVE_PREFIX_REGEX,
171+
FORWARD_SLASH_DRIVE_REGEX,
141172
(_, drive: string) => `/${drive.toLowerCase()}/`,
142173
);
143174
}
@@ -400,7 +431,11 @@ export class SshConfig {
400431
this.logger.debug("Loaded SSH config", this.filePath);
401432
}
402433

403-
/** Regenerate the whole per-deployment file; last-writer-wins. */
434+
/**
435+
* Regenerate the whole per-deployment file; last-writer-wins.
436+
* @throws {Error} on invalid values or overrides, a `*.conf` entry that is
437+
* not a regular file, or a failed `stat`, write or rename.
438+
*/
404439
async update(values: SshValues, overrides?: Record<string, string>) {
405440
const block = this.renderDeploymentBlock(values, overrides);
406441
this.raw = `${CODER_SSH_CONFIG_HEADER}\n\n${block}`;
@@ -411,6 +446,9 @@ export class SshConfig {
411446
* Keep the shared include first so our options win, removing superseded
412447
* blocks. Read-modify-write with no locking, like the CLI's config-ssh;
413448
* when the include is already in place nothing is written.
449+
* @throws {SshConfigBadFormat} on malformed Coder block markers.
450+
* @throws {Error} on an unrepresentable include path, or a failed read,
451+
* `stat`, write or rename.
414452
*/
415453
async updateInclude(includeDir: string, safeHostname: string) {
416454
const block = this.renderIncludeBlock(this.includeArguments(includeDir));
@@ -489,22 +527,32 @@ export class SshConfig {
489527
}
490528

491529
/**
492-
* `~/...` under the home directory off Windows. Windows gets the absolute
493-
* path, since each build expands `~` from a different home: `/C:/...` for
494-
* Windows OpenSSH (before 8.0 it reads no other absolute spelling) and
495-
* `/c/...` for Git for Windows. Each build skips the one it cannot match.
530+
* How the Include line spells `includeDir`:
531+
* - `~/...` under the home directory; on Windows only when every build's
532+
* `~` is the profile.
533+
* - Else absolute. A Windows drive path gets `/C:/...` (Windows OpenSSH;
534+
* before 8.0 its only absolute form) and `/c/...` (Git for Windows), and
535+
* each build skips the other. A UNC path gets `//server/...` (untested).
536+
*
537+
* Windows OpenSSH reads `/c/...` as `\c\...` on the current drive, which
538+
* any local user can create, so the default setup keeps `~/...`.
496539
*/
497540
private includeArguments(includeDir: string): string[] {
498-
if (process.platform === "win32") {
499-
const dir = includeDir.replaceAll("\\", "/");
500-
return DRIVE_PREFIX_REGEX.test(dir)
501-
? [`/${dir}`, toMsysPath(dir)]
502-
: [dir];
541+
const isWindows = process.platform === "win32";
542+
const relative =
543+
!isWindows || windowsSshHomeIsProfile()
544+
? homeRelativePath(includeDir)
545+
: undefined;
546+
if (relative) {
547+
return [`~/${relative}`];
548+
}
549+
if (!isWindows) {
550+
return [includeDir];
503551
}
504-
const relative = path.relative(os.homedir(), includeDir);
505-
return relative && !relative.startsWith("..") && !path.isAbsolute(relative)
506-
? [`~/${relative}`]
507-
: [includeDir];
552+
const dir = includeDir.replaceAll("\\", "/");
553+
return FORWARD_SLASH_DRIVE_REGEX.test(dir)
554+
? [`/${dir}`, toMsysPath(dir)]
555+
: [dir];
508556
}
509557

510558
private escapeIncludePath(argument: string): string {
@@ -535,7 +583,8 @@ export class SshConfig {
535583
rest = this.removeRange(rest, block);
536584
}
537585
}
538-
return [includeBlock, rest].filter(Boolean).join("\n\n");
586+
// Trim like removeRange, so a second call is a no-op.
587+
return [includeBlock, rest.trimStart()].filter(Boolean).join("\n\n");
539588
}
540589

541590
private removeRange(raw: string, range: Block): string {

‎src/remote/sshSupport.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,29 @@ function matchesHostPattern(host: string, pattern: string): boolean {
2525
/** Keyed by lowercase directive name, so wrong-cased lookups fail to compile. */
2626
export type SshProperties = Record<Lowercase<string>, string>;
2727

28+
/** ssh ran but resolved no ProxyCommand, so it never read the Coder config. */
29+
export class SshProxyCommandMissingError extends Error {
30+
/** The config files ssh read, from its `-v` output. */
31+
readonly configFiles: string[];
32+
33+
constructor(verboseOutput: string) {
34+
super(`ssh -G resolved no ProxyCommand\n${verboseOutput.trim()}`);
35+
this.name = "SshProxyCommandMissingError";
36+
this.configFiles = Array.from(
37+
verboseOutput.matchAll(/Reading configuration data (.+?)\r?$/gm),
38+
(match) => match[1],
39+
);
40+
}
41+
}
42+
2843
/**
2944
* Effective SSH properties for a host as OpenSSH resolves them (`ssh -G`),
3045
* following Include and Match. Runs `sshPath`, or `ssh` on PATH when unset.
46+
* @throws {SshProxyCommandMissingError} when ssh resolves no ProxyCommand,
47+
* meaning it never read the Coder config (a different ssh build or home
48+
* directory).
3149
* @throws {Error} when ssh is a Windows batch file (which needs a shell),
32-
* fails, times out, or resolves no ProxyCommand, meaning it never read the
33-
* Coder config (a different ssh build or home directory).
50+
* fails, or times out.
3451
*/
3552
export async function resolveSshProperties(
3653
sshPath: string | undefined,
@@ -57,7 +74,7 @@ export async function resolveSshProperties(
5774
}
5875
}
5976
if (!properties.proxycommand) {
60-
throw new Error(`ssh -G resolved no ProxyCommand\n${stderr.trim()}`);
77+
throw new SshProxyCommandMissingError(stderr);
6178
}
6279
return properties;
6380
}

0 commit comments

Comments
 (0)