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