Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

gitRemoteAccountEnv.test.ts

436 lines15.0 KB

1import * as NodeFS from "node:fs";
2import * as NodePath from "node:path";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, expect, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Redacted from "effect/Redacted";
9​
10import { ServerConfig } from "../config.ts";
11import * as GitHubCredentials from "../sourceControl/GitHubCredentials.ts";
12import * as ServerSettings from "../serverSettings.ts";
13import * as GitVcsDriver from "./GitVcsDriver.ts";
14import * as VcsProcess from "./VcsProcess.ts";
15import { gitRemoteAccountEnv } from "./gitRemoteAccountEnv.ts";
16​
17const NOEXT_URL = "https://github.com/Noext/trackshop.git";
18const MAXIME_URL = "https://github.com/maxime-pharmania/arpilabe.git";
19​
20/** A resolver standing in for `gh`, so the policy below can be read on its own. */
21const signedInAccounts = (tokens: Readonly<Record<string, string>>) =>
22 ({
23 get: (host: string, request?: GitHubCredentials.GitHubCredentialRequest) => {
24 const login = request?.account?.toLowerCase() ?? "";
25 const token = tokens[login];
26 return token === undefined
27 ? Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host, account: login }))
28 : Effect.succeed({
29 host,
30 token: Redacted.make(token),
31 source: "gh" as const,
32 fingerprint: `fingerprint:${token}`,
33 });
34 },
35 invalidate: () => Effect.void,
36 }) satisfies GitHubCredentials.GitHubCredentials["Service"];
37​
38const resolveEnv = (input: {
39 readonly args: ReadonlyArray<string>;
40 readonly remoteUrls?: ReadonlyMap<string, string>;
41 readonly tokens?: Readonly<Record<string, string>>;
42}) => {
43 const reads: Array<string> = [];
44 return gitRemoteAccountEnv({
45 args: input.args,
46 readRemoteUrls: () =>
47 Effect.sync(() => {
48 reads.push("read");
49 return input.remoteUrls ?? new Map<string, string>();
50 }),
51 }).pipe(
52 Effect.provideService(
53 GitHubCredentials.GitHubCredentials,
54 signedInAccounts(
55 input.tokens ?? { noext: "token-noext", "maxime-pharmania": "token-maxime" },
56 ),
57 ),
58 Effect.map((env) => ({ env, remoteReads: reads.length })),
59 );
60};
61​
62it.effect("resolves no account for a command that cannot reach a remote", () =>
63 Effect.gen(function* () {
64 for (const args of [
65 ["status", "--porcelain"],
66 ["rev-parse", "HEAD"],
67 ["remote", "-v"],
68 ["diff", "--cached", "--patch"],
69 ]) {
70 const { env, remoteReads } = yield* resolveEnv({
71 args,
72 remoteUrls: new Map([["origin", NOEXT_URL]]),
73 });
74​
75 assert.deepStrictEqual(env, {});
76 assert.strictEqual(remoteReads, 0);
77 }
78 }),
79);
80​
81it.effect("reads the repository URL out of the command it is already running", () =>
82 Effect.gen(function* () {
83 const { env, remoteReads } = yield* resolveEnv({
84 args: ["clone", "--progress", NOEXT_URL, "trackshop"],
85 });
86​
87 assert.strictEqual(env.GH_TOKEN, "token-noext");
88 assert.strictEqual(env.GITHUB_TOKEN, "token-noext");
89 assert.strictEqual(env.GH_DEBUG, "");
90 // The URL is in the arguments, so no configuration read is needed.
91 assert.strictEqual(remoteReads, 0);
92 }),
93);
94​
95it.effect("hands an enterprise host its own variables and never GH_TOKEN", () =>
96 Effect.gen(function* () {
97 const { env } = yield* resolveEnv({
98 args: ["clone", "https://github.example.com/Noext/trackshop.git", "trackshop"],
99 tokens: { noext: "token-noext" },
100 });
101​
102 // GH_TOKEN would reach any non-github.com host, so an enterprise token is named explicitly.
103 assert.strictEqual(env.GH_TOKEN, undefined);
104 assert.strictEqual(env.GH_HOST, "github.example.com");
105 assert.strictEqual(env.GH_ENTERPRISE_TOKEN, "token-noext");
106 assert.strictEqual(env.GITHUB_ENTERPRISE_TOKEN, "token-noext");
107 }),
108);
109​
110it.effect("finds the subcommand behind git's global options", () =>
111 Effect.gen(function* () {
112 const { env } = yield* resolveEnv({
113 args: ["-C", "/repo", "--git-dir", "/repo/.git", "fetch", "--quiet", "origin"],
114 remoteUrls: new Map([["origin", NOEXT_URL]]),
115 });
116​
117 assert.strictEqual(env.GH_TOKEN, "token-noext");
118 }),
119);
120​
121it.effect("resolves the owner of the remote a command names", () =>
122 Effect.gen(function* () {
123 const { env, remoteReads } = yield* resolveEnv({
124 args: [
125 "fetch",
126 "--quiet",
127 "--no-tags",
128 "origin",
129 "+refs/heads/main:refs/remotes/origin/main",
130 ],
131 remoteUrls: new Map([
132 ["origin", MAXIME_URL],
133 ["fork", NOEXT_URL],
134 ]),
135 });
136​
137 assert.strictEqual(env.GH_TOKEN, "token-maxime");
138 assert.strictEqual(remoteReads, 1);
139 }),
140);
141​
142it.effect("resolves the only owner a repository has when the command names no remote", () =>
143 Effect.gen(function* () {
144 const { env, remoteReads } = yield* resolveEnv({
145 args: ["push"],
146 remoteUrls: new Map([["origin", NOEXT_URL]]),
147 });
148​
149 assert.strictEqual(env.GH_TOKEN, "token-noext");
150 assert.strictEqual(remoteReads, 1);
151 }),
152);
153​
154it.effect("keeps the named remote's owner when a repository has two owners", () =>
155 Effect.gen(function* () {
156 const remotes = new Map([
157 ["origin", MAXIME_URL],
158 ["fork", NOEXT_URL],
159 ]);
160 const fork = yield* resolveEnv({
161 args: ["push", "-u", "fork", "HEAD:refs/heads/main"],
162 remoteUrls: remotes,
163 });
164 const bare = yield* resolveEnv({ args: ["push"], remoteUrls: remotes });
165​
166 // Pushing to `fork` is unambiguous; a bare push could go to either owner, so it keeps the
167 // account git would have used on its own.
168 assert.strictEqual(fork.env.GH_TOKEN, "token-noext");
169 assert.deepStrictEqual(bare.env, {});
170 }),
171);
172​
173it.effect("injects nothing for a remote that authenticates some other way", () =>
174 Effect.gen(function* () {
175 const ssh = yield* resolveEnv({ args: ["clone", "git@github.com:Noext/trackshop.git"] });
176 const local = yield* resolveEnv({
177 args: ["fetch", "origin"],
178 remoteUrls: new Map([["origin", "/srv/git/trackshop.git"]]),
179 });
180​
181 assert.deepStrictEqual(ssh.env, {});
182 assert.deepStrictEqual(local.env, {});
183 }),
184);
185​
186it.effect("injects nothing for an owner no signed-in account owns", () =>
187 Effect.gen(function* () {
188 const { env } = yield* resolveEnv({
189 args: ["clone", "https://github.com/pharmania/arpilabe-pilotage.git", "pilotage"],
190 });
191​
192 assert.deepStrictEqual(env, {});
193 }),
194);
195​
196const FAKE_GH_SCRIPT = `#!/usr/bin/env node
197const args = process.argv.slice(2);
198const accounts = JSON.parse(process.env.T3_FAKE_GH_ACCOUNTS ?? "{}");
199if (args[0] === "auth" && args[1] === "token") {
200 const at = args.indexOf("--user");
201 const login = at === -1 ? process.env.T3_FAKE_GH_ACTIVE : args[at + 1];
202 const token = accounts[login];
203 if (token === undefined) process.exit(1);
204 process.stdout.write(token);
205 process.exit(0);
207process.exit(1);
208`;
209​
210/** Records the token it was spawned with, so the test observes the real child environment. */
211const FAKE_GIT_SCRIPT = `#!/usr/bin/env node
212const fs = require("node:fs");
213const args = process.argv.slice(2);
214if (process.env.T3_FAKE_GIT_LOG) {
215 fs.appendFileSync(process.env.T3_FAKE_GIT_LOG, args.join(" ") + "|" + (process.env.GH_TOKEN ?? "") + "\\n");
217if (args[0] === "remote") {
218 process.stdout.write((process.env.T3_FAKE_GIT_REMOTES ?? "") + "\\n");
219 process.exit(0);
221const failOn = process.env.T3_FAKE_GIT_FAIL_ON ?? "";
222if (failOn.length > 0 && args.join(" ").includes(failOn)) {
223 process.stderr.write("remote: Repository not found.\\n");
224 process.exit(1);
226process.exit(0);
227`;
228​
229const GIT_LOG_ENV_KEYS = [
230 "T3_FAKE_GH_ACCOUNTS",
231 "T3_FAKE_GH_ACTIVE",
232 "T3_FAKE_GIT_LOG",
233 "T3_FAKE_GIT_REMOTES",
234 "T3_FAKE_GIT_FAIL_ON",
235] as const;
236​
237/** Puts a fake `gh` and a fake `git` ahead of the real ones for the duration of `use`. */
238const withFakeGitHubBinaries = <A, E, R>(
239 input: {
240 readonly accounts: Readonly<Record<string, string>>;
241 readonly activeAccount: string;
242 readonly remotes?: ReadonlyArray<string>;
243 readonly failOn?: string;
244 },
245 use: Effect.Effect<A, E, R>,
246) =>
247 Effect.gen(function* () {
248 const fileSystem = yield* FileSystem.FileSystem;
249 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-git-remote-account-" });
250 const binDir = NodePath.join(tempDir, "bin");
251 NodeFS.mkdirSync(binDir, { recursive: true });
252 const logPath = NodePath.join(tempDir, "git.log");
253 NodeFS.writeFileSync(NodePath.join(binDir, "gh"), FAKE_GH_SCRIPT, { mode: 0o755 });
254 NodeFS.writeFileSync(NodePath.join(binDir, "git"), FAKE_GIT_SCRIPT, { mode: 0o755 });
255​
256 const previousPath = process.env.PATH;
257 const previous = GIT_LOG_ENV_KEYS.map((key) => [key, process.env[key]] as const);
258 yield* Effect.acquireRelease(
259 Effect.sync(() => {
260 process.env.PATH = `${binDir}${NodePath.delimiter}${previousPath ?? ""}`;
261 process.env.T3_FAKE_GH_ACCOUNTS = JSON.stringify(input.accounts);
262 process.env.T3_FAKE_GH_ACTIVE = input.activeAccount;
263 process.env.T3_FAKE_GIT_LOG = logPath;
264 process.env.T3_FAKE_GIT_REMOTES = (input.remotes ?? []).join("\n");
265 if (input.failOn === undefined) delete process.env.T3_FAKE_GIT_FAIL_ON;
266 else process.env.T3_FAKE_GIT_FAIL_ON = input.failOn;
267 }),
268 () =>
269 Effect.sync(() => {
270 process.env.PATH = previousPath;
271 for (const [key, value] of previous) {
272 if (value === undefined) delete process.env[key];
273 else process.env[key] = value;
274 }
275 }),
276 );
277​
278 return yield* use;
279 });
280​
281/** Every git process the driver spawned, with the token it inherited. The remotes read is noise. */
282const gitLog = () =>
283 Effect.gen(function* () {
284 const fileSystem = yield* FileSystem.FileSystem;
285 const text = yield* fileSystem
286 .readFileString(process.env.T3_FAKE_GIT_LOG ?? "/dev/null")
287 .pipe(Effect.orElseSucceed(() => ""));
288 return text
289 .split("\n")
290 .filter((line) => line.length > 0 && !line.startsWith("remote "))
291 .map((line) => {
292 const [args, token] = line.split("|");
293 return { args: args ?? "", token: token ?? "" };
294 });
295 });
296​
297const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
298 prefix: "t3-git-remote-account-",
299});
300/**
301 * The driver as the server assembles it: the credentials service is provided to it, exactly as
302 * `server.ts` provides it to the application layer the driver is built inside.
303 */
304const TestLayer = GitVcsDriver.layer.pipe(
305 Layer.provide(ServerConfigLayer),
306 Layer.provideMerge(NodeServices.layer),
307 Layer.provide(
308 GitHubCredentials.layer.pipe(
309 Layer.provide(VcsProcess.layer),
310 Layer.provide(ServerSettings.ServerSettingsService.layerTest({})),
311 Layer.provide(NodeServices.layer),
312 ),
313 ),
314);
315​
316const twoAccounts = { Noext: "token-noext", "maxime-pharmania": "token-maxime" } as const;
317const noextRemote = [`origin\t${NOEXT_URL} (fetch)`, `origin\t${NOEXT_URL} (push)`] as const;
318​
319it.effect("gives the clone the token of the account that owns the repository", () =>
320 withFakeGitHubBinaries(
321 { accounts: twoAccounts, activeAccount: "maxime-pharmania" },
322 Effect.gen(function* () {
323 const driver = yield* GitVcsDriver.GitVcsDriver;
324 yield* driver.execute({
325 operation: "test.clone",
326 cwd: process.cwd(),
327 args: ["clone", "--progress", NOEXT_URL, "trackshop"],
328 });
329​
330 // The active account cannot see this repository; the owner's token is what makes it readable.
331 expect(yield* gitLog()).toEqual([
332 { args: `clone --progress ${NOEXT_URL} trackshop`, token: "token-noext" },
333 ]);
334 }),
335 ).pipe(Effect.provide(TestLayer)),
336);
337​
338it.effect("follows the same path for a fetch and a push on that clone", () =>
339 withFakeGitHubBinaries(
340 { accounts: twoAccounts, activeAccount: "maxime-pharmania", remotes: noextRemote },
341 Effect.gen(function* () {
342 const driver = yield* GitVcsDriver.GitVcsDriver;
343 yield* driver.execute({
344 operation: "test.fetch",
345 cwd: process.cwd(),
346 args: ["fetch", "--quiet", "--no-tags", "origin"],
347 });
348 yield* driver.execute({
349 operation: "test.push",
350 cwd: process.cwd(),
351 args: ["push", "-u", "origin", "HEAD:refs/heads/main"],
352 });
353​
354 expect(yield* gitLog()).toEqual([
355 { args: "fetch --quiet --no-tags origin", token: "token-noext" },
356 { args: "push -u origin HEAD:refs/heads/main", token: "token-noext" },
357 ]);
358 }),
359 ).pipe(Effect.provide(TestLayer)),
360);
361​
362it.effect("keeps two owners on their own tokens while their commands run at the same time", () =>
363 withFakeGitHubBinaries(
364 { accounts: twoAccounts, activeAccount: "maxime-pharmania" },
365 Effect.gen(function* () {
366 const driver = yield* GitVcsDriver.GitVcsDriver;
367 yield* Effect.all(
368 [
369 driver.execute({
370 operation: "test.clone",
371 cwd: process.cwd(),
372 args: ["clone", NOEXT_URL, "trackshop"],
373 }),
374 driver.execute({
375 operation: "test.clone",
376 cwd: process.cwd(),
377 args: ["clone", MAXIME_URL, "arpilabe"],
378 }),
379 ],
380 { concurrency: 2 },
381 );
382​
383 expect((yield* gitLog()).map((line) => `${line.args} -> ${line.token}`).toSorted()).toEqual([
384 `clone ${NOEXT_URL} trackshop -> token-noext`,
385 `clone ${MAXIME_URL} arpilabe -> token-maxime`,
386 ]);
387 }),
388 ).pipe(Effect.provide(TestLayer)),
389);
390​
391it.effect("leaves a repository no account owns on the ambient account", () =>
392 withFakeGitHubBinaries(
393 { accounts: twoAccounts, activeAccount: "maxime-pharmania" },
394 Effect.gen(function* () {
395 const driver = yield* GitVcsDriver.GitVcsDriver;
396 yield* driver.execute({
397 operation: "test.clone",
398 cwd: process.cwd(),
399 args: ["clone", "https://github.com/pharmania/arpilabe-pilotage.git", "pilotage"],
400 });
401​
402 expect(yield* gitLog()).toEqual([
403 {
404 args: "clone https://github.com/pharmania/arpilabe-pilotage.git pilotage",
405 token: "",
406 },
407 ]);
408 }),
409 ).pipe(Effect.provide(TestLayer)),
410);
411​
412it.effect("reports a failure without the token it was given", () =>
413 withFakeGitHubBinaries(
414 { accounts: twoAccounts, activeAccount: "maxime-pharmania", failOn: "trackshop" },
415 Effect.gen(function* () {
416 const driver = yield* GitVcsDriver.GitVcsDriver;
417 const failure = yield* driver
418 .execute({
419 operation: "test.clone",
420 cwd: process.cwd(),
421 args: ["clone", NOEXT_URL, "trackshop"],
422 })
423 .pipe(Effect.flip);
424​
425 expect(failure.detail).toBe("Git command exited with a non-zero status.");
426 expect(String(failure)).not.toContain("token-noext");
427 expect(JSON.stringify({ message: failure.message, detail: failure.detail })).not.toContain(
428 "token-noext",
429 );
430 // The command did run as that account: only its output is reported back.
431 expect(yield* gitLog()).toEqual([
432 { args: `clone ${NOEXT_URL} trackshop`, token: "token-noext" },
433 ]);
434 }),
435 ).pipe(Effect.provide(TestLayer)),
436);