Skip to content
TypeScript

fix(ssh): deduplicate configured host suggestions (#15630)

maria806b53994568
diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts
index 1fe2b86aae7..adb0a12e8f0 100644
--- a/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts
+++ b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts
@@ -58,7 +58,7 @@ describe("sshEnvironment", () => {
yield* fs.makeDirectory(path.join(sshDir, "config.d"), { recursive: true });
yield* fs.writeFileString(
path.join(sshDir, "config"),
- ["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
+ ["Include config.d/*.conf", "Host devbox", " HostName devbox.example.com", ""].join("\n"),
);
yield* fs.writeFileString(
path.join(sshDir, "config.d", "team.conf"),
@@ -92,7 +92,7 @@ describe("sshEnvironment", () => {
},
{
alias: "devbox",
- hostname: "devbox",
+ hostname: "devbox.example.com",
username: null,
port: null,
source: "ssh-config",
@@ -106,7 +106,7 @@ describe("sshEnvironment", () => {
},
{
alias: "staging",
- hostname: "staging",
+ hostname: "staging.example.com",
username: null,
port: null,
source: "ssh-config",
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index fe02e5be7b4..b984de57f76 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -2198,7 +2198,7 @@ export function ConnectionsSettings() {
const address = formatDesktopSshTarget(target);
return (
!savedDesktopSshEnvironmentKeys.has(target.alias) &&
- !savedDesktopSshEnvironmentKeys.has(address)
+ (target.source === "ssh-config" || !savedDesktopSshEnvironmentKeys.has(address))
);
});
const filteredDiscoveredSshHosts = filterDiscoveredSshHosts(
diff --git a/apps/web/src/state/desktopSshHosts.test.ts b/apps/web/src/state/desktopSshHosts.test.ts
index 4b6b60250e4..631dd9b89e7 100644
--- a/apps/web/src/state/desktopSshHosts.test.ts
+++ b/apps/web/src/state/desktopSshHosts.test.ts
@@ -87,8 +87,9 @@ describe("filterDiscoveredSshHosts", () => {
]);
});
- it("matches case-insensitively", () => {
+ it("matches aliases and hostnames case-insensitively", () => {
expect(filterDiscoveredSshHosts(suggestions, "PINOT")).toEqual([suggestions[1]]);
+ expect(filterDiscoveredSshHosts(hosts, "box.LOCAL")).toEqual(hosts);
});
it("returns an empty array when no hosts match", () => {
diff --git a/apps/web/src/state/desktopSshHosts.ts b/apps/web/src/state/desktopSshHosts.ts
index 2ff05748589..05d19790283 100644
--- a/apps/web/src/state/desktopSshHosts.ts
+++ b/apps/web/src/state/desktopSshHosts.ts
@@ -18,7 +18,10 @@ export function filterDiscoveredSshHosts(
const alias = host.alias.toLowerCase();
if (alias.startsWith(normalizedQuery)) {
prefixMatches.push(host);
- } else if (alias.includes(normalizedQuery)) {
+ } else if (
+ alias.includes(normalizedQuery) ||
+ host.hostname.toLowerCase().includes(normalizedQuery)
+ ) {
substringMatches.push(host);
}
}
diff --git a/packages/ssh/src/config.test.ts b/packages/ssh/src/config.test.ts
index 49e91b2adbc..2c0b7997966 100644
--- a/packages/ssh/src/config.test.ts
+++ b/packages/ssh/src/config.test.ts
@@ -19,7 +19,7 @@ function makeTempHomeDir() {
}
describe("ssh config", () => {
- it.effect("follows quoted and escaped Include paths like OpenSSH", () =>
+ it.effect("deduplicates hosts through quoted and escaped Include paths like OpenSSH", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -28,8 +28,14 @@ describe("ssh config", () => {
const quotedDir = path.join(homeDir, "quoted dir");
yield* fs.makeDirectory(sshDir);
yield* fs.makeDirectory(quotedDir);
- yield* fs.writeFileString(path.join(quotedDir, "team#1=a.conf"), "Host quoted\n");
- yield* fs.writeFileString(path.join(homeDir, "escaped space.conf"), "Host escaped\n");
+ yield* fs.writeFileString(
+ path.join(quotedDir, "team#1=a.conf"),
+ 'Host quoted\n HostName quoted".example.com"\nHost *\n',
+ );
+ yield* fs.writeFileString(
+ path.join(homeDir, "escaped space.conf"),
+ "Host escaped\n HostName escaped.example.com\nHost *\n",
+ );
yield* fs.writeFileString(
path.join(sshDir, "config"),
[
@@ -39,10 +45,18 @@ describe("ssh config", () => {
].join("\n"),
);
+ yield* fs.writeFileString(
+ path.join(sshDir, "known_hosts"),
+ "escaped.example.com ssh-ed25519 AAAA\nquoted.example.com ssh-ed25519 AAAA\n",
+ );
+
const hosts = yield* discoverSshHosts({ homeDir });
assert.deepEqual(
- hosts.map((host) => host.alias),
- ["escaped", "quoted"],
+ hosts.map((host) => [host.alias, host.hostname, host.source]),
+ [
+ ["escaped", "escaped.example.com", "ssh-config"],
+ ["quoted", "quoted.example.com", "ssh-config"],
+ ],
);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
@@ -57,9 +71,10 @@ describe("ssh config", () => {
yield* fs.writeFileString(
path.join(sshDir, "config"),
[
- "Host devbox",
- " HostName devbox.example.com",
+ "Host devbox devbox-admin",
+ " HostName 'devbox.example.com'",
"Host=equalsbox",
+ "Host *",
"Include=config.d/*.conf",
"",
].join("\n"),
@@ -77,6 +92,8 @@ describe("ssh config", () => {
yield* fs.writeFileString(
path.join(sshDir, "known_hosts"),
[
+ "devbox.example.com ssh-ed25519 AAAA",
+ "staging.example.com ssh-ed25519 AAAA",
"known.example.com ssh-ed25519 AAAA",
"|1|hashed|entry ssh-ed25519 AAAA",
"[bastion.example.com]:2222 ssh-ed25519 AAAA",
@@ -95,7 +112,14 @@ describe("ssh config", () => {
},
{
alias: "devbox",
- hostname: "devbox",
+ hostname: "devbox.example.com",
+ username: null,
+ port: null,
+ source: "ssh-config",
+ },
+ {
+ alias: "devbox-admin",
+ hostname: "devbox.example.com",
username: null,
port: null,
source: "ssh-config",
@@ -116,7 +140,7 @@ describe("ssh config", () => {
},
{
alias: "staging",
- hostname: "staging",
+ hostname: "staging.example.com",
username: null,
port: null,
source: "ssh-config",
@@ -125,6 +149,77 @@ describe("ssh config", () => {
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
+ it.effect("retains raw targets when included hostnames are inactive or uncertain", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const homeDir = yield* makeTempHomeDir();
+ const sshDir = path.join(homeDir, ".ssh");
+ yield* fs.makeDirectory(sshDir, { recursive: true });
+ yield* fs.writeFileString(
+ path.join(sshDir, "config"),
+ [
+ "Host WORK*",
+ " HostName case-sensitive.example.com",
+ "Host work",
+ "Host dev",
+ " Include conditional.conf",
+ "Host prod",
+ "Host matched",
+ "Match originalhost matched",
+ " Include match.conf",
+ "Host matched",
+ " HostName fallback.example.com",
+ "Host bracketed",
+ " Include bracket-[ab].conf",
+ " HostName bracket-fallback.example.com",
+ "",
+ ].join("\n"),
+ );
+ yield* fs.writeFileString(
+ path.join(sshDir, "conditional.conf"),
+ "Host prod\n HostName blocked.example.com\n",
+ );
+ yield* fs.writeFileString(
+ path.join(sshDir, "match.conf"),
+ "Host matched\n HostName match.example.com\n",
+ );
+ yield* fs.writeFileString(
+ path.join(sshDir, "bracket-a.conf"),
+ "HostName bracket-real.example.com\n",
+ );
+ yield* fs.writeFileString(
+ path.join(sshDir, "known_hosts"),
+ [
+ "bracket-real.example.com ssh-ed25519 AAAA",
+ "bracket-fallback.example.com ssh-ed25519 AAAA",
+ "blocked.example.com ssh-ed25519 AAAA",
+ "case-sensitive.example.com ssh-ed25519 AAAA",
+ "match.example.com ssh-ed25519 AAAA",
+ "fallback.example.com ssh-ed25519 AAAA",
+ "",
+ ].join("\n"),
+ );
+
+ const hosts = yield* discoverSshHosts({ homeDir });
+ assert.deepEqual(
+ hosts.filter((host) => host.source === "known-hosts").map((host) => host.hostname),
+ [
+ "blocked.example.com",
+ "bracket-fallback.example.com",
+ "bracket-real.example.com",
+ "case-sensitive.example.com",
+ "fallback.example.com",
+ "match.example.com",
+ ],
+ );
+ assert.equal(hosts.find((host) => host.alias === "bracketed")?.hostname, "bracketed");
+ assert.equal(hosts.find((host) => host.alias === "prod")?.hostname, "prod");
+ assert.equal(hosts.find((host) => host.alias === "work")?.hostname, "work");
+ assert.equal(hosts.find((host) => host.alias === "matched")?.hostname, "matched");
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+ );
+
it.effect("parses known_hosts entries without returning hashed hosts", () =>
Effect.sync(() => {
assert.deepEqual(
diff --git a/packages/ssh/src/config.ts b/packages/ssh/src/config.ts
index f2c52e8857d..538f8b1c72b 100644
--- a/packages/ssh/src/config.ts
+++ b/packages/ssh/src/config.ts
@@ -14,14 +14,15 @@ const NO_HOSTS: ReadonlyArray<string> = [] as const;
// Mirrors OpenSSH readconf: the keyword may be followed by one optional "=",
// then the arguments are split like misc.c argv_split() with quotes, the
// escapes \\ \" \' and unquoted "\ ", and "#" starting a comment only at
-// the start of a token. A line with an unterminated quote is ignored.
-function splitDirectiveArgs(line: string): ReadonlyArray<string> {
+// the start of a token. Invalid quoting leaves hostname resolution uncertain.
+function parseSshConfigLine(line: string) {
const match = /^\s*([^\s=]+)\s*=?\s*(.*)$/u.exec(line);
if (!match) {
- return [];
+ return null;
}
- const args = [match[1]!];
+ const directive = match[1]!.toLowerCase();
+ const args: Array<string> = [];
const rest = match[2]!;
let token: string | null = null;
let quote: string | null = null;
@@ -55,12 +56,12 @@ function splitDirectiveArgs(line: string): ReadonlyArray<string> {
}
}
if (quote !== null) {
- return [];
+ return { directive, args: null };
}
if (token !== null) {
args.push(token);
}
- return args;
+ return { directive, args };
}
function expandHomePath(input: string, homeDir: string): string {
@@ -119,68 +120,117 @@ const expandGlob = Effect.fnUntraced(function* (pattern: string) {
matchedPaths.push(entryPath);
}
}
- return matchedPaths.toSorted((left, right) => left.localeCompare(right));
+ return matchedPaths.toSorted();
});
+type HostCondition = ReadonlyArray<string> | null;
+
+interface HostNameRule {
+ readonly conditions: ReadonlyArray<HostCondition>;
+ readonly hostname: string | null;
+}
+
+function matchesHostPatterns(alias: string, patterns: ReadonlyArray<string>): boolean {
+ let matched = false;
+ for (const pattern of patterns) {
+ const negated = pattern.startsWith("!");
+ const hostPattern = negated ? pattern.slice(1) : pattern;
+ const matches =
+ hostPattern === "*" ||
+ (hasSshPattern(hostPattern) ? globToRegExp(hostPattern).test(alias) : hostPattern === alias);
+ if (!matches) continue;
+ if (negated) return false;
+ matched = true;
+ }
+ return matched;
+}
+
+function resolveConfiguredHostname(alias: string, rules: ReadonlyArray<HostNameRule>) {
+ for (const { conditions, hostname } of rules) {
+ if (
+ conditions.some((condition) => condition !== null && !matchesHostPatterns(alias, condition))
+ ) {
+ continue;
+ }
+ // SSH takes the first value; an uncertain earlier value blocks later fallbacks.
+ if (conditions.includes(null) || hostname === null) return null;
+ if (/%(?!h)/u.test(hostname) || hostname.includes("$")) return null;
+ return hostname.replaceAll("%h", alias);
+ }
+ return null;
+}
+
const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
filePath: string,
- visited = new Set<string>(),
+ visited: Set<string>,
homeDir: string,
-): Effect.fn.Return<
- ReadonlyArray<string>,
- PlatformError.PlatformError,
- FileSystem.FileSystem | Path.Path
-> {
+ aliases: Set<string>,
+ hostNameRules: Array<HostNameRule>,
+ inheritedConditions: ReadonlyArray<HostCondition>,
+): Effect.fn.Return<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const resolvedPath = path.resolve(filePath);
- if (visited.has(resolvedPath) || !(yield* fs.exists(resolvedPath))) {
- return NO_HOSTS;
+ if (visited.has(resolvedPath)) {
+ // Read each file once, but never reuse its rules under a different Include context.
+ hostNameRules.push({ conditions: inheritedConditions, hostname: null });
+ return;
}
+ if (!(yield* fs.exists(resolvedPath))) return;
visited.add(resolvedPath);
- const aliases = new Set<string>();
const directory = path.dirname(resolvedPath);
const raw = yield* fs.readFileString(resolvedPath);
+ let condition: HostCondition = ["*"];
for (const line of raw.split(/\r?\n/u)) {
- const [directive = "", ...rawArgs] = splitDirectiveArgs(line);
- const normalizedDirective = directive.toLowerCase();
- if (normalizedDirective === "include") {
- for (const includePattern of rawArgs) {
+ const parsed = parseSshConfigLine(line);
+ if (!parsed) continue;
+ const { directive, args } = parsed;
+ const conditions = [...inheritedConditions, condition];
+
+ if (directive === "host") {
+ condition = args;
+ for (const alias of args ?? []) {
+ if (alias.length > 0 && !hasSshPattern(alias)) aliases.add(alias);
+ }
+ } else if (directive === "match") {
+ condition = null;
+ } else if (directive === "hostname") {
+ hostNameRules.push({ conditions, hostname: args?.length === 1 ? args[0]! : null });
+ } else if (directive === "include") {
+ if (args === null) {
+ hostNameRules.push({ conditions, hostname: null });
+ continue;
+ }
+ for (const includePattern of args) {
const resolvedPattern = yield* resolveSshConfigIncludePattern(
includePattern,
directory,
homeDir,
);
+ if (
+ /%|\$\{|\[/u.test(includePattern) ||
+ (includePattern.startsWith("~") && !/^~(?=$|\/|\\)/u.test(includePattern)) ||
+ hasSshPattern(path.dirname(resolvedPattern))
+ ) {
+ hostNameRules.push({ conditions, hostname: null });
+ continue;
+ }
const includedPaths = yield* expandGlob(resolvedPattern);
for (const includedPath of includedPaths) {
- const includedAliases = yield* collectSshConfigAliasesFromFile(
+ yield* collectSshConfigAliasesFromFile(
includedPath,
visited,
homeDir,
+ aliases,
+ hostNameRules,
+ conditions,
);
- for (const alias of includedAliases) {
- aliases.add(alias);
- }
}
}
- continue;
- }
-
- if (normalizedDirective !== "host") {
- continue;
- }
-
- for (const alias of rawArgs) {
- if (alias.length === 0 || hasSshPattern(alias)) {
- continue;
- }
- aliases.add(alias);
}
}
-
- return [...aliases].toSorted((left, right) => left.localeCompare(right));
});
function normalizeKnownHostsHostname(rawHost: string): string {
@@ -252,18 +302,26 @@ export const discoverSshHosts = Effect.fnUntraced(
}
const sshDirectory = path.join(homeDir, ".ssh");
- const configAliases = yield* collectSshConfigAliasesFromFile(
+ const configAliases = new Set<string>();
+ const hostNameRules: Array<HostNameRule> = [];
+ yield* collectSshConfigAliasesFromFile(
path.join(sshDirectory, "config"),
new Set<string>(),
homeDir,
+ configAliases,
+ hostNameRules,
+ [],
);
const knownHosts = yield* readKnownHostsHostnames(path.join(sshDirectory, "known_hosts"));
const discovered = new Map<string, DesktopDiscoveredSshHost>();
+ const configuredHostnames = new Set<string>();
for (const alias of configAliases) {
+ const hostname = resolveConfiguredHostname(alias, hostNameRules);
+ if (hostname !== null) configuredHostnames.add(hostname.toLowerCase());
discovered.set(alias, {
alias,
- hostname: alias,
+ hostname: hostname ?? alias,
username: null,
port: null,
source: "ssh-config",
@@ -271,7 +329,7 @@ export const discoverSshHosts = Effect.fnUntraced(
}
for (const hostname of knownHosts) {
- if (discovered.has(hostname)) {
+ if (discovered.has(hostname) || configuredHostnames.has(hostname.toLowerCase())) {
continue;
}
discovered.set(hostname, {