Skip to content

Commit d733412

Browse files
committed
fix(ssh): validate discovered ports and IPv6 destinations
1 parent 451947d commit d733412

4 files changed

Lines changed: 55 additions & 24 deletions

File tree

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

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@ import * as Result from "effect/Result";
88
import * as Sink from "effect/Sink";
99
import * as Stream from "effect/Stream";
1010
import * as TestClock from "effect/testing/TestClock";
11-
import { ChildProcessSpawner } from "effect/unstable/process";
11+
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
12+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
1213

1314
import {
1415
baseSshArgs,
1516
buildSshHostSpecEffect,
17+
collectProcessOutput,
1618
getLastNonEmptyOutputLine,
1719
parseSshResolveOutput,
1820
runSshCommand,
@@ -86,7 +88,7 @@ describe("ssh command", () => {
8688
Effect.gen(function* () {
8789
for (const [alias, hostname, expected] of [
8890
["ssh://host.example:2222", "host.example", "ssh://[email protected]:2222"],
89-
["ssh://[::1]:2222", "::1", "ssh://alice@[::1]:2222"],
91+
["ssh://[::1]:2222", "::1", "alice@::1"],
9092
]) {
9193
const resolved = parseSshResolveOutput(
9294
alias!,
@@ -98,6 +100,31 @@ describe("ssh command", () => {
98100
}),
99101
);
100102

103+
it.effect.skipIf(HostProcessPlatform.defaultValue() === "win32")(
104+
"passes discovered IPv6 destinations to OpenSSH without losing the user or port",
105+
() =>
106+
Effect.gen(function* () {
107+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
108+
for (const username of [null, "developer"]) {
109+
const target = {
110+
alias: "ssh://[2001:db8::1]:2222",
111+
hostname: "2001:db8::1",
112+
username,
113+
port: null,
114+
};
115+
const hostSpec = yield* buildSshHostSpecEffect(target);
116+
const child = yield* spawner.spawn(
117+
ChildProcess.make("ssh", ["-F", "/dev/null", "-G", ...baseSshArgs(target), hostSpec]),
118+
);
119+
const stdout = yield* collectProcessOutput(child.stdout);
120+
assert.equal(Number(yield* child.exitCode), 0);
121+
assert.include(stdout, "port 2222\n");
122+
assert.include(stdout, "hostname 2001:db8::1\n");
123+
if (username) assert.include(stdout, `user ${username}\n`);
124+
}
125+
}).pipe(Effect.provide(NodeServices.layer)),
126+
);
127+
101128
it.effect("builds interactive ssh args without forcing batch mode", () =>
102129
Effect.sync(() => {
103130
assert.deepEqual(

‎packages/ssh/src/command.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,17 @@ function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string {
8484
if (destination.length === 0) {
8585
throw new Error("SSH target is missing its alias/hostname.");
8686
}
87-
if (target.username && destination.startsWith("ssh://")) {
87+
if (destination.startsWith("ssh://")) {
8888
const uri = new URL(destination);
89-
uri.username = target.username;
90-
return uri.toString();
89+
if (uri.hostname.startsWith("[")) {
90+
const username = target.username ?? (uri.username ? decodeURIComponent(uri.username) : null);
91+
const hostname = uri.hostname.slice(1, -1);
92+
return username ? `${username}@${hostname}` : hostname;
93+
}
94+
if (target.username) {
95+
uri.username = target.username;
96+
return uri.toString();
97+
}
9198
}
9299
return target.username ? `${target.username}@${destination}` : destination;
93100
}
@@ -107,12 +114,14 @@ export function baseSshArgs(
107114
target: DesktopSshEnvironmentTarget,
108115
input?: { readonly batchMode?: "yes" | "no" },
109116
): string[] {
117+
const destination = target.alias.trim() || target.hostname.trim();
118+
const port = target.port ?? (destination.startsWith("ssh://") ? new URL(destination).port : null);
110119
return [
111120
"-o",
112121
`BatchMode=${input?.batchMode ?? "no"}`,
113122
"-o",
114123
"ConnectTimeout=10",
115-
...(target.port !== null ? ["-p", String(target.port)] : []),
124+
...(port ? ["-p", String(port)] : []),
116125
];
117126
}
118127

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,25 @@ it.effect("preserves distinct known-host ports and IPv6 destinations", () =>
2222
"[host.example.com]:2222 ssh-rsa BBBB",
2323
"[2001:db8::1]:2200 ssh-ed25519 AAAA",
2424
"[invalid.example.com]:65536 ssh-ed25519 AAAA",
25+
"[invalid.example.com]:abc ssh-ed25519 AAAA",
26+
"[invalid.example.com]: ssh-ed25519 AAAA",
27+
"invalid.example.com:70000x ssh-ed25519 AAAA",
28+
"invalid.example.com:abc ssh-ed25519 AAAA",
29+
"invalid.example.com: ssh-ed25519 AAAA",
30+
"plain.example.com:2201 ssh-ed25519 AAAA",
31+
"2001:db8::2 ssh-ed25519 AAAA",
2532
].join("\n"),
2633
);
2734
const hosts = yield* discoverSshHosts({ homeDir });
2835
assert.deepEqual(
2936
hosts.map(({ alias, hostname, port }) => ({ alias, hostname, port })),
3037
[
38+
{ alias: "2001:db8::2", hostname: "2001:db8::2", port: null },
3139
{ alias: "host.example.com", hostname: "host.example.com", port: null },
3240
{ alias: "ssh://[2001:db8::1]:2200", hostname: "2001:db8::1", port: 2200 },
3341
{ alias: "ssh://host.example.com:2222", hostname: "host.example.com", port: 2222 },
3442
{ alias: "ssh://host.example.com:2223", hostname: "host.example.com", port: 2223 },
43+
{ alias: "ssh://plain.example.com:2201", hostname: "plain.example.com", port: 2201 },
3544
],
3645
);
3746
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),

‎packages/ssh/src/config.ts‎

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -155,21 +155,6 @@ const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
155155
return [...aliases].toSorted((left, right) => left.localeCompare(right));
156156
});
157157

158-
function normalizeKnownHostsHostname(rawHost: string): string {
159-
const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost);
160-
if (bracketMatch?.[1]) {
161-
return bracketMatch[1];
162-
}
163-
164-
if (!rawHost.includes(":")) {
165-
return rawHost;
166-
}
167-
168-
const firstColonIndex = rawHost.indexOf(":");
169-
const lastColonIndex = rawHost.lastIndexOf(":");
170-
return firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost;
171-
}
172-
173158
function parseKnownHostsTargets(raw: string): ReadonlyArray<DesktopDiscoveredSshHost> {
174159
const targets = new Map<string, DesktopDiscoveredSshHost>();
175160

@@ -188,12 +173,13 @@ function parseKnownHostsTargets(raw: string): ReadonlyArray<DesktopDiscoveredSsh
188173
}
189174

190175
for (const rawHost of hostField.split(",")) {
191-
const host = normalizeKnownHostsHostname(rawHost).trim();
176+
const withPort = /^\[([^\]]+)\]:(.*)$/u.exec(rawHost) ?? /^([^:]+):([^:]*)$/u.exec(rawHost);
177+
const host = (withPort?.[1] ?? rawHost).trim();
192178
if (host.length === 0 || hasSshPattern(host)) {
193179
continue;
194180
}
195-
const portText =
196-
/^\[[^\]]+\]:(\d+)$/.exec(rawHost)?.[1] ?? /^[^:]+:(\d+)$/.exec(rawHost)?.[1];
181+
const portText = withPort?.[2];
182+
if (portText !== undefined && !/^\d+$/u.test(portText)) continue;
197183
const port = portText === undefined ? null : Number(portText);
198184
if (port !== null && (!Number.isSafeInteger(port) || port < 1 || port > 65535)) continue;
199185
const alias =

0 commit comments

Comments
 (0)