Skip to content

Commit 131ed8e

Browse files
committed
refactor(server): move SSH alias resolution into its own module
Covers the remaining edge cases found in review: - public forge hosts and their port-443 endpoints skip ssh - a loopback HostName keeps the alias but still keys the login's home - a config User git cannot spell in a remote is ignored - one-letter hosts with a user stay SSH remotes; without one they are drives - git+ssh:// and ssh+git:// key like ssh://
1 parent 30d716e commit 131ed8e

5 files changed

Lines changed: 324 additions & 290 deletions

File tree

‎apps/server/src/project/RepositoryIdentityResolver.test.ts‎

Lines changed: 145 additions & 146 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,80 @@ const makeRepositoryIdentityResolverTestLayer = (options: {
3838
}),
3939
).pipe(Layer.provide(ProcessRunner.layer));
4040

41+
const processOutput = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
42+
stdout,
43+
stderr: "",
44+
code: ChildProcessSpawner.ExitCode(code),
45+
timedOut: false,
46+
stdoutTruncated: false,
47+
stderrTruncated: false,
48+
stdoutInvalidUtf8: false,
49+
stderrInvalidUtf8: false,
50+
});
51+
52+
/**
53+
* What `ssh -G` prints for a config with these hosts, including `Match` rules on
54+
* the login and port. Any other host prints as itself.
55+
*/
56+
function sshConfigOutput(args: ReadonlyArray<string>): string {
57+
const option = (flag: string) => (args.includes(flag) ? args[args.indexOf(flag) + 1] : undefined);
58+
// ssh matches host names case-insensitively.
59+
const host = (args.at(-1) ?? "").toLowerCase();
60+
const user = option("-l");
61+
const port = option("-p") ?? "22";
62+
const hosts: Record<string, { readonly hostname: string; readonly user?: string }> = {
63+
gh: { hostname: "github.com" },
64+
g: { hostname: "github.com" },
65+
gh443: { hostname: "ssh.github.com" },
66+
// No `User`, so ssh logs in as the local account.
67+
nouser: { hostname: "github.com", user: "localuser" },
68+
// A login git cannot spell in a remote.
69+
spaced: { hostname: "github.com", user: "John Smith" },
70+
"alice-box": { hostname: "192.0.2.10", user: "alice" },
71+
"bob-box": { hostname: "192.0.2.10", user: "bob" },
72+
// `Match originalhost review user git` picks GitHub; otherwise GitLab.
73+
review: { hostname: user === "git" ? "github.com" : "gitlab.com", user: "me" },
74+
// `Match exec "test %p = 2222"` picks a second server for the same name.
75+
forge: { hostname: port === "2222" ? "forge-b.test" : "forge-a.test" },
76+
"gh-fqdn": { hostname: "github.com." },
77+
// Two tunnels to different servers through local ports.
78+
"tunnel-a": { hostname: "localhost" },
79+
"tunnel-b": { hostname: "127.0.0.1" },
80+
};
81+
const entry = hosts[host];
82+
return `user ${user ?? entry?.user ?? "git"}\nhostname ${entry?.hostname ?? host}\nport ${port}\n`;
83+
}
84+
85+
/** Resolves a repository whose primary remote is `remoteUrl`, against the config above. */
86+
const resolveRemote = (remoteUrl: string, options: { readonly sshFails?: boolean } = {}) => {
87+
const sshCalls: Array<ReadonlyArray<string>> = [];
88+
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
89+
run: (input) =>
90+
Effect.sync(() => {
91+
if (input.command !== "ssh") {
92+
return processOutput(
93+
input.args.includes("rev-parse") ? "/repo\n" : `origin\t${remoteUrl} (fetch)\n`,
94+
);
95+
}
96+
sshCalls.push(input.args);
97+
return options.sshFails
98+
? processOutput("", 255)
99+
: processOutput(sshConfigOutput(input.args));
100+
}),
101+
});
102+
return Effect.gen(function* () {
103+
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
104+
return { identity: yield* resolver.resolve("/repo"), sshCalls };
105+
}).pipe(
106+
Effect.provide(
107+
Layer.effect(
108+
RepositoryIdentityResolver.RepositoryIdentityResolver,
109+
RepositoryIdentityResolver.make(),
110+
).pipe(Layer.provide(processRunner)),
111+
),
112+
);
113+
};
114+
41115
it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
42116
it.effect("refreshes the Git root only when requested", () => {
43117
const calls: Array<ReadonlyArray<string>> = [];
@@ -104,16 +178,14 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
104178
expect(calls).toEqual([
105179
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
106180
["-C", "/repo", "remote", "-v"],
107-
["-G", "-l", "git", "github.com"],
108181
]);
109182

110183
const refreshed = yield* resolver.resolve("/repo/packages/web", { refresh: true });
111184
expect(refreshed?.rootPath).toBe("/repo/packages/web");
112185
expect(yield* resolver.resolve("/repo/packages/web")).toEqual(refreshed);
113-
expect(calls.slice(3)).toEqual([
186+
expect(calls.slice(2)).toEqual([
114187
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
115188
["-C", "/repo/packages/web", "remote", "-v"],
116-
["-G", "-l", "git", "github.com"],
117189
]);
118190
remoteUrl = "[email protected]:team/repo.git";
119191
const forgejo = yield* resolver.resolve(rootPath, { refresh: true });
@@ -172,155 +244,82 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
172244
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
173245
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
174246
["-C", "/repo", "remote", "-v"],
175-
["-G", "-l", "git", "github.com"],
176247
]);
177248
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), resolverLayer)));
178249
});
179250

180-
it.effect("keys a remote through its SSH host alias", () => {
181-
const sshHosts: Array<string> = [];
182-
let remoteUrl = "gh:T3Tools/t3code";
183-
let sshFails = false;
184-
// `Host gh` / `HostName github.com`, `Host gh443` for the port-443 endpoint,
185-
// and `alice-box` / `bob-box`, two logins on one server.
186-
const sshConfigs: Record<string, string> = {
187-
gh: "user git\nhostname github.com",
188-
gh443: "user git\nhostname ssh.github.com",
189-
"alice-box": "user alice\nhostname 192.0.2.10",
190-
"bob-box": "user bob\nhostname 192.0.2.10",
191-
nouser: "user localuser\nhostname github.com",
192-
// `Match originalhost review user git` picks GitHub; otherwise GitLab.
193-
"git@review": "user git\nhostname github.com",
194-
review: "user me\nhostname gitlab.com",
195-
};
196-
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
197-
run: (input) =>
198-
Effect.sync(() => {
199-
const sshArgs = input.args.slice(1);
200-
const host = sshArgs.at(-1) ?? "";
201-
const user = sshArgs.includes("-l") ? sshArgs[sshArgs.indexOf("-l") + 1] : undefined;
202-
if (input.command === "ssh") sshHosts.push(sshArgs.join(" "));
203-
const config = sshConfigs[`${user}@${host}`] ?? sshConfigs[host];
204-
const stdout =
205-
input.command === "ssh"
206-
? `${config ?? `user git\nhostname ${host}`}\nport 22\n`
207-
: input.args.includes("rev-parse")
208-
? "/repo\n"
209-
: `origin\t${remoteUrl} (fetch)\n`;
210-
const failed = input.command === "ssh" && sshFails;
211-
return {
212-
stdout: failed ? "" : stdout,
213-
stderr: "",
214-
code: ChildProcessSpawner.ExitCode(failed ? 255 : 0),
215-
timedOut: false,
216-
stdoutTruncated: false,
217-
stderrTruncated: false,
218-
stdoutInvalidUtf8: false,
219-
stderrInvalidUtf8: false,
220-
};
221-
}),
222-
});
223-
const resolverLayer = Layer.effect(
224-
RepositoryIdentityResolver.RepositoryIdentityResolver,
225-
RepositoryIdentityResolver.make(),
226-
).pipe(Layer.provide(processRunner));
251+
it.effect("keys an aliased remote by its host while git keeps the alias", () =>
252+
Effect.gen(function* () {
253+
const { identity } = yield* resolveRemote("gh:T3Tools/t3code");
254+
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
255+
expect(identity?.provider).toBe("github");
256+
expect(identity?.locator.remoteUrl).toBe("gh:T3Tools/t3code");
257+
}),
258+
);
227259

228-
return Effect.gen(function* () {
229-
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
230-
const resolveKey = (url: string) => {
231-
remoteUrl = url;
232-
return resolver.resolve("/repo", { refresh: true });
233-
};
234-
235-
const aliased = yield* resolveKey("gh:T3Tools/t3code");
236-
expect(aliased?.canonicalKey).toBe("github.com/t3tools/t3code");
237-
expect(aliased?.provider).toBe("github");
238-
expect(aliased?.owner).toBe("t3tools");
239-
// Git still reaches the repository through the alias.
240-
expect(aliased?.locator.remoteUrl).toBe("gh:T3Tools/t3code");
241-
242-
expect((yield* resolveKey("me@gh:T3Tools/t3code.git"))?.canonicalKey).toBe(
243-
"github.com/t3tools/t3code",
244-
);
245-
expect((yield* resolveKey("ssh://gh/T3Tools/t3code.git"))?.canonicalKey).toBe(
246-
"github.com/t3tools/t3code",
247-
);
248-
expect((yield* resolveKey("git+ssh://git@gh:2222/T3Tools/t3code"))?.canonicalKey).toBe(
249-
"github.com/t3tools/t3code",
250-
);
251-
expect((yield* resolveKey("gh443:T3Tools/t3code"))?.canonicalKey).toBe(
252-
"github.com/t3tools/t3code",
253-
);
254-
// A server alias with an absolute path keys like the same path by address.
255-
const byAlias = yield* resolveKey("alice-box:/srv/git/app.git");
256-
const byAddress = yield* resolveKey("ssh://[email protected]/srv/git/app.git");
257-
expect(byAlias?.canonicalKey).toBe("192.0.2.10/srv/git/app");
258-
expect(byAddress?.canonicalKey).toBe(byAlias?.canonicalKey);
259-
// The remote's user and port reach ssh, which `Match` rules can depend on.
260-
expect(sshHosts).toEqual([
261-
"gh",
262-
"-l me gh",
263-
"gh",
264-
"-l git -p 2222 gh",
265-
"gh443",
266-
"alice-box",
267-
"-l deploy 192.0.2.10",
268-
]);
269-
expect((yield* resolveKey("git@review:Team/App"))?.canonicalKey).toBe("github.com/team/app");
270-
expect((yield* resolveKey("review:Team/App"))?.canonicalKey).toBe("gitlab.com/team/app");
271-
272-
// A relative path on a server is in the login's home: two logins, two repositories.
273-
const aliceHome = "192.0.2.10/~alice/app";
274-
expect((yield* resolveKey("alice-box:app.git"))?.canonicalKey).toBe(aliceHome);
275-
expect((yield* resolveKey("bob-box:app.git"))?.canonicalKey).toBe("192.0.2.10/~bob/app");
276-
expect((yield* resolveKey("[email protected]:~/app.git"))?.canonicalKey).toBe(aliceHome);
277-
expect((yield* resolveKey("ssh://[email protected]/~/app.git"))?.canonicalKey).toBe(aliceHome);
278-
expect((yield* resolveKey("bob-box:~alice/app.git"))?.canonicalKey).toBe(aliceHome);
279-
// A forge reads the path as the repository, whatever the login.
280-
expect((yield* resolveKey("[email protected]:team/app.git"))?.canonicalKey).toBe(
281-
"gitlab.example.com/team/app",
282-
);
260+
it.effect.each([
261+
// Each SSH spelling of an aliased repository.
262+
{ remote: "me@gh:T3Tools/t3code.git", key: "github.com/t3tools/t3code" },
263+
{ remote: "ssh://gh/T3Tools/t3code.git", key: "github.com/t3tools/t3code" },
264+
{ remote: "git+ssh://git@gh:2222/T3Tools/t3code", key: "github.com/t3tools/t3code" },
265+
{ remote: "git@g:T3Tools/t3code", key: "github.com/t3tools/t3code" },
266+
{ remote: "gh443:T3Tools/t3code", key: "github.com/t3tools/t3code" },
267+
{ remote: "nouser:T3Tools/t3code", key: "github.com/t3tools/t3code" },
268+
{ remote: "spaced:T3Tools/t3code", key: "github.com/t3tools/t3code" },
269+
{ remote: "GH:T3Tools/t3code", key: "github.com/t3tools/t3code" },
270+
{ remote: "[email protected]:T3Tools/t3code", key: "github.com/t3tools/t3code" },
271+
// `Match` rules see the remote's login and port.
272+
{ remote: "git@review:team/app", key: "github.com/team/app" },
273+
{ remote: "review:team/app", key: "gitlab.com/team/app" },
274+
{ remote: "git@forge:team/app", key: "forge-a.test/team/app" },
275+
{ remote: "ssh://git@forge:2222/team/app", key: "forge-b.test/team/app" },
276+
// An absolute path names one repository, through an alias or by address.
277+
{ remote: "alice-box:/srv/git/app.git", key: "192.0.2.10/srv/git/app" },
278+
{ remote: "ssh://[email protected]/srv/git/app.git", key: "192.0.2.10/srv/git/app" },
279+
// A relative path on a server is in the login's home.
280+
{ remote: "alice-box:app.git", key: "192.0.2.10/~alice/app" },
281+
{ remote: "bob-box:app.git", key: "192.0.2.10/~bob/app" },
282+
{ remote: "[email protected]:~/app.git", key: "192.0.2.10/~alice/app" },
283+
{ remote: "ssh://[email protected]/~/app.git", key: "192.0.2.10/~alice/app" },
284+
{ remote: "bob-box:~alice/app.git", key: "192.0.2.10/~alice/app" },
285+
// A forge reads the path as the repository's name, whatever the login.
286+
{ remote: "[email protected]:team/app.git", key: "gitlab.example.com/team/app" },
287+
{ remote: "[email protected]:team/app.git", key: "git.corp.example/team/app" },
288+
// A trailing dot is the same name; a tunnel keeps its alias and the login's home.
289+
{ remote: "gh-fqdn:T3Tools/t3code", key: "github.com/t3tools/t3code" },
290+
{ remote: "git@tunnel-a:team/app", key: "tunnel-a/team/app" },
291+
{ remote: "git@tunnel-b:team/app", key: "tunnel-b/team/app" },
292+
{ remote: "alice@tunnel-a:app.git", key: "tunnel-a/~alice/app" },
293+
])("keys $remote as $key", ({ remote, key }) =>
294+
Effect.gen(function* () {
295+
expect((yield* resolveRemote(remote)).identity?.canonicalKey).toBe(key);
296+
}),
297+
);
283298

284-
// Every spelling of one repository keys the same, on every kind of host.
285-
const codeCommit = "git-codecommit.us-east-1.amazonaws.com/v1/repos/app";
286-
for (const [remote, key] of [
287-
["[email protected]:Team/App.git", "bitbucket.org/team/app"],
288-
["https://[email protected]/Team/App.git", "bitbucket.org/team/app"],
289-
["[email protected]:~alice/app", "git.sr.ht/~alice/app"],
290-
["https://git.sr.ht/~alice/app", "git.sr.ht/~alice/app"],
291-
// A self-hosted forge on a plain name still serves everyone as `git`.
292-
["[email protected]:team/app.git", "git.corp.example/team/app"],
293-
["https://git.corp.example/team/app", "git.corp.example/team/app"],
294-
// Per-user logins with absolute paths: CodeCommit's key id, Gerrit's account.
295-
["ssh://[email protected]/v1/repos/App", codeCommit],
296-
[`https://${codeCommit}`, codeCommit],
297-
["ssh://[email protected]:29418/platform/app", "review.corp.example/platform/app"],
298-
["https://review.corp.example/platform/app", "review.corp.example/platform/app"],
299-
// An alias without `User` logs in as the local account; GitHub ignores it.
300-
["nouser:Team/App", "github.com/team/app"],
301-
] as const) {
302-
expect((yield* resolveKey(remote))?.canonicalKey, remote).toBe(key);
303-
}
304-
const sshCalls = sshHosts.length;
305-
306-
// HTTPS never reaches ssh, nor does a host that reads as an option or a
307-
// user with shell syntax a `Match exec` `%r` would expand.
308-
expect((yield* resolveKey("https://github.com/T3Tools/t3code"))?.canonicalKey).toBe(
309-
"github.com/t3tools/t3code",
310-
);
311-
yield* resolveKey("-oProxyCommand=calc:T3Tools/t3code");
312-
yield* resolveKey("x;id@gh:T3Tools/t3code");
313-
yield* resolveKey("ssh://x%3Bid@gh/T3Tools/t3code");
314-
expect(sshHosts).toHaveLength(sshCalls);
315-
316-
// Without ssh, the alias keys the repository as before.
317-
sshFails = true;
318-
const unresolved = yield* resolveKey("gh:T3Tools/t3code");
319-
expect(unresolved?.canonicalKey).toBe("gh/t3tools/t3code");
320-
// A login spelled in the remote keys its home the same with or without ssh.
321-
expect((yield* resolveKey("[email protected]:app.git"))?.canonicalKey).toBe(aliceHome);
322-
}).pipe(Effect.provide(resolverLayer));
323-
});
299+
it.effect.each([
300+
"https://github.com/T3Tools/t3code",
301+
// Public forges key as themselves.
302+
"[email protected]:T3Tools/t3code",
303+
"[email protected]:T3Tools/t3code",
304+
// Would read as an option.
305+
"-oProxyCommand=calc:T3Tools/t3code",
306+
// Shell syntax that a `Match exec` `%r` would expand.
307+
"x;id@gh:T3Tools/t3code",
308+
"ssh://x%3Bid@gh/T3Tools/t3code",
309+
])("never runs ssh for %s", (remote) =>
310+
Effect.gen(function* () {
311+
expect((yield* resolveRemote(remote)).sshCalls).toEqual([]);
312+
}),
313+
);
314+
315+
it.effect("keeps the alias when ssh fails but still keys a spelled login's home", () =>
316+
Effect.gen(function* () {
317+
const aliased = yield* resolveRemote("gh:T3Tools/t3code", { sshFails: true });
318+
expect(aliased.identity?.canonicalKey).toBe("gh/t3tools/t3code");
319+
const spelled = yield* resolveRemote("[email protected]:app.git", { sshFails: true });
320+
expect(spelled.identity?.canonicalKey).toBe("192.0.2.10/~alice/app");
321+
}),
322+
);
324323

325324
it.effect("normalizes equivalent GitHub remotes into a stable repository identity", () =>
326325
Effect.gen(function* () {

0 commit comments

Comments
 (0)