Skip to content

Commit 25feac2

Browse files
fix(ssh): an alias no longer hides known_hosts entries on other ports (#35779)
1 parent adf3151 commit 25feac2

2 files changed

Lines changed: 103 additions & 18 deletions

File tree

‎packages/ssh/src/config.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,48 @@ describe("ssh config", () => {
306306
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
307307
);
308308

309+
it.effect("keeps known_hosts ports that a configured alias for the address does not use", () =>
310+
Effect.gen(function* () {
311+
const fs = yield* FileSystem.FileSystem;
312+
const path = yield* Path.Path;
313+
const homeDir = yield* makeTempHomeDir();
314+
const sshDir = path.join(homeDir, ".ssh");
315+
yield* fs.makeDirectory(sshDir);
316+
yield* fs.writeFileString(
317+
path.join(sshDir, "known_hosts"),
318+
[
319+
"[192.0.2.10]:2222 ssh-ed25519 AAAA",
320+
"[192.0.2.10]:2223 ssh-ed25519 AAAA",
321+
"[192.0.2.20]:2222 ssh-ed25519 AAAA",
322+
"[box]:2200 ssh-ed25519 AAAA",
323+
"box ssh-ed25519 AAAA",
324+
"192.0.2.20 ssh-ed25519 AAAA",
325+
"",
326+
].join("\n"),
327+
);
328+
yield* fs.writeFileString(
329+
path.join(sshDir, "config"),
330+
[
331+
"Host fixture",
332+
" HostName 192.0.2.10",
333+
" Port 22",
334+
"Host prod",
335+
" HostName 192.0.2.20",
336+
" Port 2222",
337+
"Host box",
338+
" Port 2200",
339+
"",
340+
].join("\n"),
341+
);
342+
343+
const hosts = yield* discoverSshHosts({ homeDir });
344+
assert.deepEqual(
345+
hosts.map((host) => `${host.alias} ${host.port}`),
346+
["192.0.2.10 2222", "192.0.2.10 2223", "box null", "fixture null", "prod null"],
347+
);
348+
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
349+
);
350+
309351
it.effect("parses known_hosts entries without returning hashed hosts", () =>
310352
Effect.sync(() => {
311353
assert.deepEqual(

‎packages/ssh/src/config.ts‎

Lines changed: 61 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,11 @@ const expandGlob = Effect.fnUntraced(function* (pattern: string) {
128128

129129
type HostCondition = ReadonlyArray<string> | null;
130130

131-
interface HostNameRule {
131+
interface HostRule {
132132
readonly conditions: ReadonlyArray<HostCondition>;
133-
readonly hostname: string | null;
133+
// null: an unreadable Include that may set any directive.
134+
readonly directive: "hostname" | "port" | null;
135+
readonly value: string | null;
134136
}
135137

136138
function matchesHostPatterns(alias: string, patterns: ReadonlyArray<string>): boolean {
@@ -148,35 +150,53 @@ function matchesHostPatterns(alias: string, patterns: ReadonlyArray<string>): bo
148150
return matched;
149151
}
150152

151-
function resolveConfiguredHostname(alias: string, rules: ReadonlyArray<HostNameRule>) {
152-
for (const { conditions, hostname } of rules) {
153+
function resolveConfiguredValue(
154+
alias: string,
155+
directive: "hostname" | "port",
156+
rules: ReadonlyArray<HostRule>,
157+
) {
158+
for (const rule of rules) {
153159
if (
154-
conditions.some((condition) => condition !== null && !matchesHostPatterns(alias, condition))
160+
(rule.directive !== null && rule.directive !== directive) ||
161+
rule.conditions.some(
162+
(condition) => condition !== null && !matchesHostPatterns(alias, condition),
163+
)
155164
) {
156165
continue;
157166
}
158167
// SSH takes the first value; an uncertain earlier value blocks later fallbacks.
159-
if (conditions.includes(null) || hostname === null) return null;
160-
if (/%(?!h)/u.test(hostname) || hostname.includes("$")) return null;
161-
return hostname.replaceAll("%h", alias);
168+
if (rule.conditions.includes(null) || rule.value === null) return null;
169+
return rule.value;
162170
}
163-
return null;
171+
return undefined;
172+
}
173+
174+
function resolveConfiguredHostname(alias: string, rules: ReadonlyArray<HostRule>) {
175+
const hostname = resolveConfiguredValue(alias, "hostname", rules) ?? null;
176+
if (hostname === null || /%(?!h)/u.test(hostname) || hostname.includes("$")) return null;
177+
return hostname.replaceAll("%h", alias);
178+
}
179+
180+
// "*" when the port is uncertain, so the alias still covers every known_hosts port.
181+
function resolveConfiguredPort(alias: string, rules: ReadonlyArray<HostRule>) {
182+
const port = resolveConfiguredValue(alias, "port", rules);
183+
return port === undefined ? "22" : (port ?? "*");
164184
}
165185

166186
const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
167187
filePath: string,
168188
visited: Set<string>,
169189
homeDir: string,
170190
aliases: Set<string>,
171-
hostNameRules: Array<HostNameRule>,
191+
hostNameRules: Array<HostRule>,
172192
inheritedConditions: ReadonlyArray<HostCondition>,
173193
): Effect.fn.Return<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
174194
const fs = yield* FileSystem.FileSystem;
175195
const path = yield* Path.Path;
176196
const resolvedPath = path.resolve(filePath);
177197
if (visited.has(resolvedPath)) {
178198
// Read each file once, but never reuse its rules under a different Include context.
179-
hostNameRules.push({ conditions: inheritedConditions, hostname: null });
199+
hostNameRules.push({ conditions: inheritedConditions, directive: null, value: null });
180200
return;
181201
}
182202
if (!(yield* fs.exists(resolvedPath))) return;
@@ -201,10 +221,21 @@ const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
201221
} else if (directive === "match") {
202222
condition = null;
203223
} else if (directive === "hostname") {
204-
hostNameRules.push({ conditions, hostname: args?.length === 1 ? args[0]! : null });
224+
hostNameRules.push({
225+
conditions,
226+
directive: "hostname",
227+
value: args?.length === 1 ? args[0]! : null,
228+
});
229+
} else if (directive === "port") {
230+
const port = args?.length === 1 ? Number(args[0]) : Number.NaN;
231+
hostNameRules.push({
232+
conditions,
233+
directive: "port",
234+
value: Number.isInteger(port) && port >= 1 && port <= 65535 ? String(port) : null,
235+
});
205236
} else if (directive === "include") {
206237
if (args === null) {
207-
hostNameRules.push({ conditions, hostname: null });
238+
hostNameRules.push({ conditions, directive: null, value: null });
208239
continue;
209240
}
210241
for (const includePattern of args) {
@@ -218,7 +249,7 @@ const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
218249
(includePattern.startsWith("~") && !/^~(?=$|\/|\\)/u.test(includePattern)) ||
219250
hasSshPattern(path.dirname(resolvedPattern))
220251
) {
221-
hostNameRules.push({ conditions, hostname: null });
252+
hostNameRules.push({ conditions, directive: null, value: null });
222253
continue;
223254
}
224255
const includedPaths = yield* expandGlob(resolvedPattern);
@@ -321,7 +352,7 @@ export const discoverSshHosts = Effect.fnUntraced(
321352

322353
const sshDirectory = path.join(homeDir, ".ssh");
323354
const configAliases = new Set<string>();
324-
const hostNameRules: Array<HostNameRule> = [];
355+
const hostNameRules: Array<HostRule> = [];
325356
yield* collectSshConfigAliasesFromFile(
326357
path.join(sshDirectory, "config"),
327358
new Set<string>(),
@@ -333,10 +364,15 @@ export const discoverSshHosts = Effect.fnUntraced(
333364
const knownHosts = yield* readKnownHosts(path.join(sshDirectory, "known_hosts"));
334365
const discovered = new Map<string, DesktopDiscoveredSshHost>();
335366

336-
const configuredHostnames = new Set<string>();
367+
const configuredNames = new Set<string>();
368+
const configuredDestinations = new Set<string>();
337369
for (const alias of configAliases) {
338370
const hostname = resolveConfiguredHostname(alias, hostNameRules);
339-
if (hostname !== null) configuredHostnames.add(hostname.toLowerCase());
371+
const port = resolveConfiguredPort(alias, hostNameRules);
372+
for (const name of hostname === null ? [alias] : [alias, hostname]) {
373+
configuredNames.add(name.toLowerCase());
374+
configuredDestinations.add(`${name.toLowerCase()}\u0000${port}`);
375+
}
340376
discovered.set(alias, {
341377
alias,
342378
hostname: hostname ?? alias,
@@ -347,7 +383,14 @@ export const discoverSshHosts = Effect.fnUntraced(
347383
}
348384

349385
for (const { hostname, port } of knownHosts) {
350-
if (discovered.has(hostname) || configuredHostnames.has(hostname.toLowerCase())) {
386+
const name = hostname.toLowerCase();
387+
// A port-less entry connects as `ssh <host>`, so a matching alias's Port applies to it.
388+
if (
389+
port === null
390+
? configuredNames.has(name)
391+
: configuredDestinations.has(`${name}\u0000${port}`) ||
392+
configuredDestinations.has(`${name}\u0000*`)
393+
) {
351394
continue;
352395
}
353396
discovered.set(`${hostname}\u0000${port ?? ""}`, {

0 commit comments

Comments
 (0)