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 PlatformError from "effect/PlatformError";
7import * as TestClock from "effect/testing/TestClock";
8import * as Tracer from "effect/Tracer";
9import { ChildProcessSpawner } from "effect/process";
10import { VcsProcessSpawnError, VcsProcessTimeoutError } from "@t3tools/contracts";
11import { HttpClient, HttpClientResponse, type HttpClientRequest } from "effect/http";
12
13import * as GitHubRest from "./GitHubRest.ts";
14import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
15import * as GitHubCredentials from "./GitHubCredentials.ts";
16import * as GitHubQuota from "./GitHubQuota.ts";
17import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
18import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
19import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
20
21const NOW = Date.parse("2026-10-05T12:00:00.000Z");
22
23function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
24 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
25 let tokens = ["first", "second"];
26 let invalidations = 0;
27 let credentialReads = 0;
28 const credentials = Layer.succeed(
29 GitHubCredentials.GitHubCredentials,
30 GitHubCredentials.GitHubCredentials.of({
31 get: (host) =>
32 Effect.sync(() => {
33 credentialReads++;
34 return {
35 host,
36 token: Redacted.make(tokens[0]!),
37 source: "gh" as const,
38 fingerprint: `${host}:${tokens[0]}`,
39 };
40 }),
41 invalidate: () =>
42 Effect.sync(() => {
43 invalidations++;
44 tokens = tokens.slice(1);
45 }),
46 }),
47 );
48 const http = Layer.succeed(
49 HttpClient.HttpClient,
50 HttpClient.make((request) => {
51 requests.push(request);
52 return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
53 }),
54 );
55 const layer = GitHubRest.layer.pipe(
56 Layer.provide(Layer.mergeAll(credentials, http)),
57 Layer.provideMerge(GitHubQuota.layer),
58 Layer.provideMerge(SourceControlRateLimit.layer),
59 );
60 return {
61 layer,
62 requests,
63 invalidations: () => invalidations,
64 credentialReads: () => credentialReads,
65 };
66}
67
68const json = (body: unknown, init?: ResponseInit) =>
69 new Response(JSON.stringify(body), {
70 ...init,
71 headers: { "content-type": "application/json", ...init?.headers },
72 });
73
74describe("gitHubApiUrls", () => {
75 it("maps github.com, GHE.com and GitHub Enterprise Server", () => {
76 expect(GitHubRequestPolicy.gitHubApiUrls("GitHub.com")).toEqual({
77 rest: "https://api.github.com",
78 graphql: "https://api.github.com/graphql",
79 });
80 expect(GitHubRequestPolicy.gitHubApiUrls("acme.ghe.com").graphql).toBe(
81 "https://api.acme.ghe.com/graphql",
82 );
83 expect(GitHubRequestPolicy.gitHubApiUrls("git.acme.internal")).toEqual({
84 rest: "https://git.acme.internal/api/v3",
85 graphql: "https://git.acme.internal/api/graphql",
86 });
87 });
88});
89
90describe("environmentToken", () => {
91 it("follows gh's precedence per kind of host", () => {
92 const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
93 expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
94 expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
95 "github",
96 );
97 expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
98 expect(
99 GitHubCredentials.environmentToken("git.acme.internal", {
100 ...env,
101 GH_HOST: "git.acme.internal",
102 }),
103 ).toBe("ghe");
104 expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
105 });
106});
107
108describe("GitHubRest", () => {
109 it.effect("traces the operation, path and quota, never the query string or the token", () => {
110 const spans: Array<Tracer.NativeSpan> = [];
111 const tracer = Tracer.make({
112 span: (options) => {
113 const span = new Tracer.NativeSpan(options);
114 spans.push(span);
115 return span;
116 },
117 });
118 const { layer } = harness(() =>
119 json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
120 );
121 return Effect.gen(function* () {
122 yield* TestClock.setTime(NOW);
123 const api = yield* GitHubRest.GitHubRest;
124 yield* api.rest({
125 host: "github.com",
126 operation: "listWorkflowRuns",
127 path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
128 });
129 const send = spans.find((span) => span.name === "GitHubRest.send")!;
130 expect(Object.fromEntries(send.attributes)).toMatchObject({
131 "github.operation": "listWorkflowRuns",
132 "github.kind": "rest",
133 "url.path": "/repos/acme/web/actions/runs",
134 "http.response.status_code": 200,
135 "github.ratelimit.remaining": 4800,
136 });
137 // Nothing recorded carries the query string or the token.
138 const everything = spans
139 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
140 .join("\n");
141 expect(everything).not.toContain("head_sha");
142 expect(everything).not.toContain("first");
143 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
144 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
145 });
146
147 it.effect("keeps the last tenth of a quota for interactive requests until it resets", () => {
148 const reset = Math.floor(NOW / 1000) + 600;
149 const quota = (remaining: number) => ({
150 "x-ratelimit-resource": "core",
151 "x-ratelimit-limit": "5000",
152 "x-ratelimit-remaining": String(remaining),
153 "x-ratelimit-reset": String(reset),
154 });
155 let remaining = 499;
156 const { layer, requests } = harness(() => json({ ok: true }, { headers: quota(remaining--) }));
157 return Effect.gen(function* () {
158 yield* TestClock.setTime(NOW);
159 const api = yield* GitHubRest.GitHubRest;
160 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
161 yield* api.rest(read);
162 const refused = yield* Effect.flip(api.rest(read));
163 expect(refused).toMatchObject({
164 _tag: "SourceControlRateLimitPausedError",
165 retryAt: reset * 1000,
166 });
167 // A user's own request may spend the reserve.
168 yield* api.rest(read).pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
169 expect(requests).toHaveLength(2);
170 // The reset gives the background its quota back.
171 yield* TestClock.setTime(reset * 1000);
172 yield* api.rest(read);
173 expect(requests).toHaveLength(3);
174 }).pipe(Effect.provide(layer));
175 });
176
177 it.effect("carries GitHub's own reason for a refused REST request", () => {
178 const { layer } = harness(() =>
179 json(
180 {
181 message: "Validation Failed",
182 errors: [
183 {
184 resource: "PullRequest",
185 code: "custom",
186 message: "A pull request already exists for acme:feature.",
187 },
188 ],
189 },
190 { status: 422 },
191 ),
192 );
193 return Effect.gen(function* () {
194 const api = yield* GitHubRest.GitHubRest;
195 const error = yield* Effect.flip(
196 api.rest({
197 host: "github.com",
198 operation: "createPullRequest",
199 method: "POST",
200 path: "repos/acme/web/pulls",
201 }),
202 );
203 expect(error.message).toBe(
204 "GitHub returned an error: Validation Failed; A pull request already exists for acme:feature.",
205 );
206 }).pipe(Effect.provide(layer));
207 });
208
209 it.effect("lets an interactive request through a pause a background read recorded", () => {
210 const reset = Math.floor(NOW / 1000) + 600;
211 let call = 0;
212 const { layer, requests } = harness(() =>
213 ++call === 1
214 ? json(
215 { message: "API rate limit exceeded" },
216 {
217 status: 403,
218 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
219 },
220 )
221 : json({ ok: true }),
222 );
223 return Effect.gen(function* () {
224 yield* TestClock.setTime(NOW);
225 const api = yield* GitHubRest.GitHubRest;
226 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
227 yield* Effect.flip(api.rest(read));
228 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
229 const merged = yield* api
230 .rest({
231 host: "github.com",
232 operation: "merge",
233 method: "PUT",
234 path: "repos/acme/web/pulls/7/merge",
235 })
236 .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
237 expect(merged.status).toBe(200);
238 expect(requests).toHaveLength(2);
239 }).pipe(Effect.provide(layer));
240 });
241
242 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
243 let call = 0;
244 const { layer } = harness(() =>
245 ++call === 1
246 ? new Response(null, { status: 304 })
247 : json(
248 { message: "API rate limit exceeded" },
249 {
250 status: 403,
251 headers: { "retry-after": "60" },
252 },
253 ),
254 );
255 return Effect.gen(function* () {
256 yield* TestClock.setTime(NOW);
257 const api = yield* GitHubRest.GitHubRest;
258 const notModified = yield* api.rest({
259 host: "github.com",
260 operation: "checks",
261 path: "repos/acme/web/pulls/7",
262 ifNoneMatch: '"abc"',
263 });
264 expect(notModified.status).toBe(304);
265 const error = yield* Effect.flip(
266 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
267 );
268 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
269 }).pipe(Effect.provide(layer));
270 });
271
272 it.effect("drops a refused token so the next request asks the source again", () => {
273 const { layer, requests, invalidations } = harness((request) =>
274 request.headers.authorization === "Bearer first"
275 ? new Response(null, { status: 401 })
276 : json({ ok: true }),
277 );
278 return Effect.gen(function* () {
279 const api = yield* GitHubRest.GitHubRest;
280 const refused = yield* Effect.flip(
281 api.rest({ host: "github.com", operation: "user", path: "user" }),
282 );
283 expect(refused._tag).toBe("GitHubApiAuthenticationError");
284 expect(invalidations()).toBe(1);
285 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
286 expect(answered.status).toBe(200);
287 expect(requests.map((request) => request.headers.authorization)).toEqual([
288 "Bearer first",
289 "Bearer second",
290 ]);
291 }).pipe(Effect.provide(layer));
292 });
293
294 it.effect("refuses to send a pinned credential to another host", () => {
295 const { layer, requests } = harness(() => json({}));
296 return Effect.gen(function* () {
297 const api = yield* GitHubRest.GitHubRest;
298 const error = yield* Effect.flip(
299 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
300 ).pipe(
301 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
302 host: "github.com",
303 token: Redacted.make("pinned"),
304 credentialFingerprint: "github.com:pinned",
305 }),
306 );
307 expect(error._tag).toBe("GitHubApiAuthenticationError");
308 expect(requests).toHaveLength(0);
309 }).pipe(Effect.provide(layer));
310 });
311});
312
313describe("GitHubCredentials", () => {
314 const credentialsWith = (run: SourceControlHost.SourceControlHost["Service"]["process"]["run"]) =>
315 GitHubCredentials.layer.pipe(
316 Layer.provide(TestSourceControlHost.layer({ process: { run } })),
317 Layer.provide(NodeCrypto.layer),
318 );
319
320 it.effect("fails with GitHubCliMissingError when gh is not on PATH", () =>
321 Effect.gen(function* () {
322 const credentials = yield* GitHubCredentials.GitHubCredentials;
323 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
324 expect(error._tag).toBe("GitHubCliMissingError");
325 }).pipe(
326 Effect.provide(
327 credentialsWith(() =>
328 Effect.fail(
329 new VcsProcessSpawnError({
330 operation: "GitHubCredentials.get",
331 command: "gh",
332 cwd: "/",
333 cause: PlatformError.systemError({
334 _tag: "NotFound",
335 module: "ChildProcess",
336 method: "spawn",
337 }),
338 }),
339 ),
340 ),
341 ),
342 ),
343 );
344
345 it.effect("does not cache a gh failure that is not about signing in", () => {
346 let calls = 0;
347 return Effect.gen(function* () {
348 const credentials = yield* GitHubCredentials.GitHubCredentials;
349 const first = yield* Effect.flip(credentials.get("github.com"));
350 expect(first._tag).toBe("GitHubCliFailedError");
351 expect((yield* credentials.get("github.com")).source).toBe("gh");
352 expect(calls).toBe(2);
353 }).pipe(
354 Effect.provide(
355 credentialsWith(() =>
356 ++calls === 1
357 ? Effect.fail(
358 new VcsProcessTimeoutError({
359 operation: "GitHubCredentials.get",
360 command: "gh",
361 cwd: "/",
362 timeoutMs: 10_000,
363 }),
364 )
365 : Effect.succeed({
366 exitCode: ChildProcessSpawner.ExitCode(0),
367 stdout: "token\n",
368 stderr: "",
369 stdoutTruncated: false,
370 stderrTruncated: false,
371 }),
372 ),
373 ),
374 );
375 });
376
377 it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
378 Effect.gen(function* () {
379 const credentials = yield* GitHubCredentials.GitHubCredentials;
380 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
381 expect(error._tag).toBe("GitHubNotSignedInError");
382 }).pipe(
383 Effect.provide(
384 credentialsWith(() =>
385 Effect.succeed({
386 exitCode: ChildProcessSpawner.ExitCode(0),
387 stdout: "\n",
388 stderr: "",
389 stdoutTruncated: false,
390 stderrTruncated: false,
391 }),
392 ),
393 ),
394 ),
395 );
396});