Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Redacted from "effect/Redacted";
6import * as TestClock from "effect/testing/TestClock";
7import * as Tracer from "effect/Tracer";
8import { ChildProcessSpawner } from "effect/process";
9import { VcsProcessTimeoutError } from "@t3tools/contracts";
10import { HttpClient, HttpClientResponse, type HttpClientRequest } from "effect/http";
11
12import * as GitHubRest from "./GitHubRest.ts";
13import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
14import * as GitHubCredentials from "./GitHubCredentials.ts";
15import * as GitHubQuota from "./GitHubQuota.ts";
16import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
17import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
18import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
19import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
20
21const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
22 enabled: false,
23 token: () => Effect.succeedNone,
24 invalidate: () => Effect.void,
25});
26
27const NOW = Date.parse("2026-10-05T12:00:00.000Z");
28
29function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
30 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
31 let tokens = ["first", "second"];
32 let invalidations = 0;
33 let credentialReads = 0;
34 const credentials = Layer.succeed(
35 GitHubCredentials.GitHubCredentials,
36 GitHubCredentials.GitHubCredentials.of({
37 get: (host) =>
38 Effect.sync(() => {
39 credentialReads++;
40 return {
41 host,
42 token: Redacted.make(tokens[0]!),
43 source: "gh" as const,
44 fingerprint: `${host}:${tokens[0]}`,
45 };
46 }),
47 saved: () => Effect.succeedNone,
48 fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
49 invalidate: () =>
50 Effect.sync(() => {
51 invalidations++;
52 tokens = tokens.slice(1);
53 }),
54 }),
55 );
56 const http = Layer.succeed(
57 HttpClient.HttpClient,
58 HttpClient.make((request) => {
59 requests.push(request);
60 return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
61 }),
62 );
63 const layer = GitHubRest.layer.pipe(
64 Layer.provide(Layer.mergeAll(credentials, http, appSignedOut)),
65 Layer.provideMerge(GitHubQuota.layer),
66 Layer.provideMerge(SourceControlRateLimit.layer),
67 );
68 return {
69 layer,
70 requests,
71 invalidations: () => invalidations,
72 credentialReads: () => credentialReads,
73 };
74}
75
76const json = (body: unknown, init?: ResponseInit) =>
77 new Response(JSON.stringify(body), {
78 ...init,
79 headers: { "content-type": "application/json", ...init?.headers },
80 });
81
82describe("environmentToken", () => {
83 it("follows gh's precedence per kind of host", () => {
84 const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
85 expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
86 expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
87 "github",
88 );
89 expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
90 expect(
91 GitHubCredentials.environmentToken("git.acme.internal", {
92 ...env,
93 GH_HOST: "git.acme.internal",
94 }),
95 ).toBe("ghe");
96 expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
97 });
98});
99
100describe("GitHubRest", () => {
101 it.effect("traces the operation, path and quota, never the query string or the token", () => {
102 const spans: Array<Tracer.NativeSpan> = [];
103 const tracer = Tracer.make({
104 span: (options) => {
105 const span = new Tracer.NativeSpan(options);
106 spans.push(span);
107 return span;
108 },
109 });
110 const { layer } = harness(() =>
111 json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
112 );
113 return Effect.gen(function* () {
114 yield* TestClock.setTime(NOW);
115 const api = yield* GitHubRest.GitHubRest;
116 yield* api.rest({
117 host: "github.com",
118 operation: "listWorkflowRuns",
119 path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
120 });
121 const send = spans.find((span) => span.name === "GitHubRest.send")!;
122 expect(Object.fromEntries(send.attributes)).toMatchObject({
123 "github.operation": "listWorkflowRuns",
124 "github.kind": "rest",
125 "url.path": "/repos/acme/web/actions/runs",
126 "http.response.status_code": 200,
127 "github.ratelimit.remaining": 4800,
128 });
129 const everything = spans
130 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
131 .join("\n");
132 expect(everything).not.toContain("head_sha");
133 expect(everything).not.toContain("first");
134 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
135 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
136 });
137
138 it.effect("lets an interactive request through a pause a background read recorded", () => {
139 const reset = Math.floor(NOW / 1000) + 600;
140 let call = 0;
141 const { layer, requests } = harness(() =>
142 ++call === 1
143 ? json(
144 { message: "API rate limit exceeded" },
145 {
146 status: 403,
147 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
148 },
149 )
150 : json({ ok: true }),
151 );
152 return Effect.gen(function* () {
153 yield* TestClock.setTime(NOW);
154 const api = yield* GitHubRest.GitHubRest;
155 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
156 yield* Effect.flip(api.rest(read));
157 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
158 const merged = yield* api
159 .rest({
160 host: "github.com",
161 operation: "merge",
162 method: "PUT",
163 path: "repos/acme/web/pulls/7/merge",
164 })
165 .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
166 expect(merged.status).toBe(200);
167 expect(requests).toHaveLength(2);
168 }).pipe(Effect.provide(layer));
169 });
170
171 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
172 let call = 0;
173 const { layer } = harness(() =>
174 ++call === 1
175 ? new Response(null, { status: 304 })
176 : json(
177 { message: "API rate limit exceeded" },
178 {
179 status: 403,
180 headers: { "retry-after": "60" },
181 },
182 ),
183 );
184 return Effect.gen(function* () {
185 yield* TestClock.setTime(NOW);
186 const api = yield* GitHubRest.GitHubRest;
187 const notModified = yield* api.rest({
188 host: "github.com",
189 operation: "checks",
190 path: "repos/acme/web/pulls/7",
191 ifNoneMatch: '"abc"',
192 });
193 expect(notModified.status).toBe(304);
194 const error = yield* Effect.flip(
195 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
196 );
197 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
198 }).pipe(Effect.provide(layer));
199 });
200
201 it.effect("drops a refused token so the next request asks the source again", () => {
202 const { layer, requests, invalidations } = harness((request) =>
203 request.headers.authorization === "Bearer first"
204 ? new Response(null, { status: 401 })
205 : json({ ok: true }),
206 );
207 return Effect.gen(function* () {
208 const api = yield* GitHubRest.GitHubRest;
209 const refused = yield* Effect.flip(
210 api.rest({ host: "github.com", operation: "user", path: "user" }),
211 );
212 expect(refused._tag).toBe("GitHubApiAuthenticationError");
213 expect(invalidations()).toBe(1);
214 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
215 expect(answered.status).toBe(200);
216 expect(requests.map((request) => request.headers.authorization)).toEqual([
217 "Bearer first",
218 "Bearer second",
219 ]);
220 }).pipe(Effect.provide(layer));
221 });
222
223 it.effect("refuses to send a pinned credential to another host", () => {
224 const { layer, requests } = harness(() => json({}));
225 return Effect.gen(function* () {
226 const api = yield* GitHubRest.GitHubRest;
227 const error = yield* Effect.flip(
228 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
229 ).pipe(
230 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
231 host: "github.com",
232 token: Redacted.make("pinned"),
233 credentialFingerprint: "github.com:pinned",
234 }),
235 );
236 expect(error._tag).toBe("GitHubApiAuthenticationError");
237 expect(requests).toHaveLength(0);
238 }).pipe(Effect.provide(layer));
239 });
240});
241
242describe("GitHubCredentials", () => {
243 const unexpectedHttp = HttpClient.make((request) =>
244 Effect.die(`Unexpected request to ${request.url}`),
245 );
246 const credentialsWith = (run: SourceControlHost.SourceControlHost["Service"]["process"]["run"]) =>
247 GitHubCredentials.layer.pipe(
248 Layer.provide(TestSourceControlHost.layer({ process: { run } })),
249 Layer.provide(NodeCrypto.layer),
250 Layer.provide(Layer.succeed(HttpClient.HttpClient, unexpectedHttp)),
251 );
252
253 it.effect("does not cache a gh failure that is not about signing in", () => {
254 let calls = 0;
255 return Effect.gen(function* () {
256 const credentials = yield* GitHubCredentials.GitHubCredentials;
257 const first = yield* Effect.flip(credentials.get("github.com"));
258 expect(first._tag).toBe("GitHubCliFailedError");
259 expect((yield* credentials.get("github.com")).source).toBe("gh");
260 expect(calls).toBe(2);
261 }).pipe(
262 Effect.provide(
263 credentialsWith(() =>
264 ++calls === 1
265 ? Effect.fail(
266 new VcsProcessTimeoutError({
267 operation: "GitHubCredentials.get",
268 command: "gh",
269 cwd: "/",
270 timeoutMs: 10_000,
271 }),
272 )
273 : Effect.succeed({
274 exitCode: ChildProcessSpawner.ExitCode(0),
275 stdout: "token\n",
276 stderr: "",
277 stdoutTruncated: false,
278 stderrTruncated: false,
279 }),
280 ),
281 ),
282 );
283 });
284
285 it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
286 Effect.gen(function* () {
287 const credentials = yield* GitHubCredentials.GitHubCredentials;
288 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
289 expect(error._tag).toBe("GitHubNotSignedInError");
290 }).pipe(
291 Effect.provide(
292 credentialsWith(() =>
293 Effect.succeed({
294 exitCode: ChildProcessSpawner.ExitCode(0),
295 stdout: "\n",
296 stderr: "",
297 stdoutTruncated: false,
298 stderrTruncated: false,
299 }),
300 ),
301 ),
302 ),
303 );
304});