Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Redacted from "effect/Redacted";
6import { ChildProcessSpawner } from "effect/process";
7
8import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
9import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
10import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
11import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
12import * as GitHubCredentials from "./GitHubCredentials.ts";
13
14const TOKEN_VARIABLES = [
15 "GH_TOKEN",
16 "GITHUB_TOKEN",
17 "GH_ENTERPRISE_TOKEN",
18 "GITHUB_ENTERPRISE_TOKEN",
19] as const;
20
21const hostSettings = (
22 hosts: Record<string, { readonly account?: string; readonly enabled?: boolean }>,
23) =>
24 Object.fromEntries(
25 Object.entries(hosts).map(([host, choice]) => [host, { enabled: true, ...choice }]),
26 );
27
28function harness(
29 hosts: Record<string, { readonly account?: string; readonly enabled?: boolean }> = {},
30 signedOut: ReadonlyArray<string> = [],
31 tokens: Record<string, string> = {},
32) {
33 const calls: Array<ReadonlyArray<string>> = [];
34 const run: SourceControlHost.SourceControlHost["Service"]["process"]["run"] = (input) =>
35 Effect.sync(() => {
36 calls.push(input.args);
37 const user = input.args[input.args.indexOf("--user") + 1];
38 if (input.args.includes("--user") && user !== undefined && signedOut.includes(user)) {
39 return {
40 exitCode: ChildProcessSpawner.ExitCode(0),
41 stdout: "",
42 stderr: "",
43 stdoutTruncated: false,
44 stderrTruncated: false,
45 };
46 }
47 return {
48 exitCode: ChildProcessSpawner.ExitCode(0),
49 stdout: input.args.includes("--user") ? `token-for-${user}\n` : "active-token\n",
50 stderr: "",
51 stdoutTruncated: false,
52 stderrTruncated: false,
53 };
54 });
55 const layer = GitHubCredentials.layer.pipe(
56 Layer.provideMerge(
57 TestSourceControlHost.layer({
58 settings: applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
59 sourceControlHosts: { github: { hosts: hostSettings(hosts), tokens } },
60 }),
61 process: { run },
62 }),
63 ),
64 Layer.provide(NodeCrypto.layer),
65 );
66 return { layer, calls };
67}
68
69describe("GitHubCredentials", () => {
70 beforeEach(() => {
71 for (const name of TOKEN_VARIABLES) vi.stubEnv(name, "");
72 });
73 afterEach(() => {
74 vi.unstubAllEnvs();
75 });
76
77 it.effect("asks gh for the active login when Settings pin nothing", () => {
78 const { layer, calls } = harness();
79 return Effect.gen(function* () {
80 const credentials = yield* GitHubCredentials.GitHubCredentials;
81 const credential = yield* credentials.get("GitHub.com");
82 expect(Redacted.value(credential.token)).toBe("active-token");
83 expect(calls).toEqual([["auth", "token", "--hostname", "github.com"]]);
84 }).pipe(Effect.provide(layer));
85 });
86
87 it.effect("passes --user for an account pinned in Settings", () => {
88 const { layer, calls } = harness({ "github.com": { account: "work" } });
89 return Effect.gen(function* () {
90 const credentials = yield* GitHubCredentials.GitHubCredentials;
91 const credential = yield* credentials.get("github.com");
92 expect(Redacted.value(credential.token)).toBe("token-for-work");
93 expect(calls).toEqual([["auth", "token", "--hostname", "github.com", "--user", "work"]]);
94 }).pipe(Effect.provide(layer));
95 });
96
97 it.effect("fails a host turned off in Settings without asking gh", () => {
98 const { layer, calls } = harness({ "github.com": { enabled: false } });
99 return Effect.gen(function* () {
100 const credentials = yield* GitHubCredentials.GitHubCredentials;
101 const error = yield* Effect.flip(credentials.get("github.com"));
102 expect(error._tag).toBe("GitHubHostDisabledError");
103 expect(error.message).toBe(
104 "GitHub host github.com is turned off in Settings → Source Control.",
105 );
106 expect(calls).toEqual([]);
107 }).pipe(Effect.provide(layer));
108 });
109
110 it.effect("lets an environment token win over a pinned account, as gh does", () => {
111 vi.stubEnv("GH_TOKEN", "from-env");
112 const { layer, calls } = harness({ "github.com": { account: "work" } });
113 return Effect.gen(function* () {
114 const credentials = yield* GitHubCredentials.GitHubCredentials;
115 const credential = yield* credentials.get("github.com");
116 expect(Redacted.value(credential.token)).toBe("from-env");
117 expect(credential.source).toBe("env");
118 expect(calls).toEqual([]);
119 }).pipe(Effect.provide(layer));
120 });
121
122 it.effect("picks up a changed account on the next request without a restart", () => {
123 const { layer, calls } = harness();
124 return Effect.gen(function* () {
125 const credentials = yield* GitHubCredentials.GitHubCredentials;
126 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
127 expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
128
129 yield* settings.update({
130 sourceControlHosts: {
131 github: { hosts: { "github.com": { account: "work", enabled: true } } },
132 },
133 });
134 expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("token-for-work");
135
136 yield* settings.update({
137 sourceControlHosts: { github: { hosts: { "github.com": { enabled: false } } } },
138 });
139 expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(
140 "GitHubHostDisabledError",
141 );
142
143 yield* settings.update({ sourceControlHosts: { github: { hosts: {} } } });
144 expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
145 expect(calls).toHaveLength(2);
146 }).pipe(Effect.provide(layer));
147 });
148
149 it.effect("falls back to the active login when the pinned one is no longer signed in", () => {
150 const { layer, calls } = harness({ "github.com": { account: "gone" } }, ["gone"]);
151 return Effect.gen(function* () {
152 const credentials = yield* GitHubCredentials.GitHubCredentials;
153 expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
154 expect(calls).toEqual([
155 ["auth", "token", "--hostname", "github.com", "--user", "gone"],
156 ["auth", "token", "--hostname", "github.com"],
157 ]);
158 }).pipe(Effect.provide(layer));
159 });
160
161 it.effect("uses a token saved in Settings before GH_TOKEN and gh", () => {
162 vi.stubEnv("GH_TOKEN", "env-token");
163 const { layer, calls } = harness({}, [], { "github.com": "saved-token" });
164 return Effect.gen(function* () {
165 const credentials = yield* GitHubCredentials.GitHubCredentials;
166 const credential = yield* credentials.get("github.com");
167 expect(Redacted.value(credential.token)).toBe("saved-token");
168 expect(credential.source).toBe("settings");
169 expect(calls).toEqual([]);
170 }).pipe(Effect.provide(layer));
171 });
172
173 it.effect("keeps a host turned off even with a token saved in Settings", () => {
174 const { layer } = harness({ "github.com": { enabled: false } }, [], {
175 "github.com": "saved-token",
176 });
177 return Effect.gen(function* () {
178 const credentials = yield* GitHubCredentials.GitHubCredentials;
179 expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(
180 "GitHubHostDisabledError",
181 );
182 }).pipe(Effect.provide(layer));
183 });
184});