Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
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 GitHubApi from "./GitHubApi.ts";
14import * as GitHubCredentials from "./GitHubCredentials.ts";
15import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
16import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
17import * as VcsProcess from "../vcs/VcsProcess.ts";
18import * as ServerSettings from "../serverSettings.ts";
19
20const NOW = Date.parse("2026-10-05T12:00:00.000Z");
21
22function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
23 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
24 let tokens = ["first", "second"];
25 let invalidations = 0;
26 const credentials = Layer.succeed(
27 GitHubCredentials.GitHubCredentials,
28 GitHubCredentials.GitHubCredentials.of({
29 get: (host) =>
30 Effect.sync(() => ({
31 host,
32 token: Redacted.make(tokens[0]!),
33 source: "gh" as const,
34 fingerprint: `${host}:${tokens[0]}`,
35 })),
36 invalidate: () =>
37 Effect.sync(() => {
38 invalidations++;
39 tokens = tokens.slice(1);
40 }),
41 }),
42 );
43 const http = Layer.succeed(
44 HttpClient.HttpClient,
45 HttpClient.make((request) => {
46 requests.push(request);
47 return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
48 }),
49 );
50 const layer = GitHubApi.layer.pipe(
51 Layer.provide(Layer.mergeAll(credentials, http)),
52 Layer.provideMerge(GitHubGraphQlBudget.layer),
53 Layer.provideMerge(SourceControlRateLimit.layer),
54 );
55 return { layer, requests, invalidations: () => invalidations };
56}
57
58const json = (body: unknown, init?: ResponseInit) =>
59 new Response(JSON.stringify(body), {
60 ...init,
61 headers: { "content-type": "application/json", ...init?.headers },
62 });
63
64describe("gitHubApiUrls", () => {
65 it("maps github.com, GHE.com and GitHub Enterprise Server", () => {
66 expect(GitHubApi.gitHubApiUrls("GitHub.com")).toEqual({
67 rest: "https://api.github.com",
68 graphql: "https://api.github.com/graphql",
69 });
70 expect(GitHubApi.gitHubApiUrls("acme.ghe.com").graphql).toBe(
71 "https://api.acme.ghe.com/graphql",
72 );
73 expect(GitHubApi.gitHubApiUrls("git.acme.internal")).toEqual({
74 rest: "https://git.acme.internal/api/v3",
75 graphql: "https://git.acme.internal/api/graphql",
76 });
77 });
78});
79
80describe("environmentToken", () => {
81 it("follows gh's precedence per kind of host", () => {
82 const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
83 expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
84 expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
85 "github",
86 );
87 // An enterprise token only goes to the host GH_HOST names, never to whatever a remote says.
88 expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
89 expect(
90 GitHubCredentials.environmentToken("git.acme.internal", {
91 ...env,
92 GH_HOST: "git.acme.internal",
93 }),
94 ).toBe("ghe");
95 expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
96 });
97});
98
99describe("GitHubApi", () => {
100 it.effect("sends GraphQL with the token and records the reported budget", () => {
101 const { layer, requests } = harness(() =>
102 json({
103 data: {
104 viewer: { login: "julius" },
105 rateLimit: { cost: 1, limit: 5000, remaining: 4999, resetAt: "2026-10-05T13:00:00Z" },
106 },
107 }),
108 );
109 return Effect.gen(function* () {
110 yield* TestClock.setTime(NOW);
111 const api = yield* GitHubApi.GitHubApi;
112 const body = yield* api.graphql({
113 host: "github.com",
114 operation: "viewer",
115 query: "query { viewer { login } }",
116 });
117 expect(body).toContain('"login":"julius"');
118 expect(requests[0]!.url).toBe("https://api.github.com/graphql");
119 expect(requests[0]!.headers.authorization).toBe("Bearer first");
120 }).pipe(Effect.provide(layer));
121 });
122
123 it.effect(
124 "traces the operation, path, query and cost, never the query string or variables",
125 () => {
126 const spans: Array<Tracer.NativeSpan> = [];
127 const tracer = Tracer.make({
128 span: (options) => {
129 const span = new Tracer.NativeSpan(options);
130 spans.push(span);
131 return span;
132 },
133 });
134 const { layer } = harness((request) =>
135 request.url.endsWith("/graphql")
136 ? json(
137 {
138 data: {
139 viewer: { login: "julius" },
140 rateLimit: {
141 cost: 3,
142 limit: 5000,
143 remaining: 4990,
144 resetAt: "2026-10-05T13:00:00Z",
145 },
146 },
147 },
148 { headers: { "x-ratelimit-remaining": "4990", "x-ratelimit-resource": "graphql" } },
149 )
150 : json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
151 );
152 return Effect.gen(function* () {
153 yield* TestClock.setTime(NOW);
154 const api = yield* GitHubApi.GitHubApi;
155 yield* api.graphql({
156 host: "github.com",
157 operation: "getPullRequestDetail",
158 query: "query($body: String!) { viewer { login } }",
159 variables: { body: "secret user text" },
160 });
161 yield* api.rest({
162 host: "github.com",
163 operation: "listWorkflowRuns",
164 path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
165 });
166 const byName = (name: string) => spans.filter((span) => span.name === name);
167 const graphql = Object.fromEntries(byName("GitHubApi.graphql")[0]!.attributes);
168 expect(graphql).toMatchObject({
169 "github.operation": "getPullRequestDetail",
170 "github.graphql.query": "query($body: String!) { viewer { login } }",
171 "github.graphql.cost": 3,
172 "github.graphql.remaining": 4990,
173 });
174 expect(String(graphql["github.graphql.query_hash"])).toMatch(/^[0-9a-f]{8}$/);
175 const rest = Object.fromEntries(byName("GitHubApi.send")[1]!.attributes);
176 expect(rest).toMatchObject({
177 "github.operation": "listWorkflowRuns",
178 "github.kind": "rest",
179 "url.path": "/repos/acme/web/actions/runs",
180 "http.response.status_code": 200,
181 "github.ratelimit.remaining": 4800,
182 });
183 // Nothing recorded carries the query string, the variables, or the token.
184 const everything = spans
185 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
186 .join("\n");
187 expect(everything).not.toContain("head_sha");
188 expect(everything).not.toContain("secret user text");
189 expect(everything).not.toContain("first");
190 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
191 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
192 },
193 );
194
195 it.effect("fails a GraphQL answer that carries errors, naming GitHub's reason", () => {
196 const { layer } = harness(() =>
197 json({ data: null, errors: [{ type: "FORBIDDEN", message: "Resource not accessible" }] }),
198 );
199 return Effect.gen(function* () {
200 const api = yield* GitHubApi.GitHubApi;
201 const error = yield* Effect.flip(
202 api.graphql({ host: "github.com", operation: "detail", query: "query { viewer { id } }" }),
203 );
204 expect(error._tag).toBe("GitHubApiResponseError");
205 expect(error.message).toContain("Resource not accessible");
206 }).pipe(Effect.provide(layer));
207 });
208
209 it.effect(
210 "reads a NOT_FOUND answer with another error as a failure, not a missing resource",
211 () => {
212 const { layer } = harness(() =>
213 json({
214 data: null,
215 errors: [
216 { type: "NOT_FOUND", message: "Could not resolve" },
217 { message: "Something went wrong" },
218 ],
219 }),
220 );
221 return Effect.gen(function* () {
222 const api = yield* GitHubApi.GitHubApi;
223 const error = yield* Effect.flip(
224 api.graphql({
225 host: "github.com",
226 operation: "detail",
227 query: "query { viewer { id } }",
228 }),
229 );
230 expect(error._tag).toBe("GitHubApiResponseError");
231 }).pipe(Effect.provide(layer));
232 },
233 );
234
235 it.effect("pauses the host after a GraphQL RATE_LIMITED answer until the reset", () => {
236 const reset = Math.floor(NOW / 1000) + 600;
237 const { layer, requests } = harness(() =>
238 json(
239 { errors: [{ type: "RATE_LIMITED", message: "API rate limit exceeded" }] },
240 { headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
241 ),
242 );
243 return Effect.gen(function* () {
244 yield* TestClock.setTime(NOW);
245 const api = yield* GitHubApi.GitHubApi;
246 const first = yield* Effect.flip(
247 api.graphql({ host: "github.com", operation: "summary", query: "query { viewer { id } }" }),
248 );
249 expect(first).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
250 const second = yield* Effect.flip(
251 api.rest({ host: "github.com", operation: "stack", path: "repos/acme/web/stacks" }),
252 );
253 expect(second).toMatchObject({
254 _tag: "SourceControlRateLimitPausedError",
255 retryAt: reset * 1000,
256 });
257 expect(requests).toHaveLength(1);
258 }).pipe(Effect.provide(layer));
259 });
260
261 it.effect("carries GitHub's own reason for a refused REST request", () => {
262 const { layer } = harness(() =>
263 json(
264 {
265 message: "Validation Failed",
266 errors: [
267 {
268 resource: "PullRequest",
269 code: "custom",
270 message: "A pull request already exists for acme:feature.",
271 },
272 ],
273 },
274 { status: 422 },
275 ),
276 );
277 return Effect.gen(function* () {
278 const api = yield* GitHubApi.GitHubApi;
279 const error = yield* Effect.flip(
280 api.rest({
281 host: "github.com",
282 operation: "createPullRequest",
283 method: "POST",
284 path: "repos/acme/web/pulls",
285 }),
286 );
287 expect(error.message).toBe(
288 "GitHub returned an error: Validation Failed; A pull request already exists for acme:feature.",
289 );
290 }).pipe(Effect.provide(layer));
291 });
292
293 it.effect("lets an interactive request through a pause a background read recorded", () => {
294 const reset = Math.floor(NOW / 1000) + 600;
295 let call = 0;
296 const { layer, requests } = harness(() =>
297 ++call === 1
298 ? json(
299 { message: "API rate limit exceeded" },
300 {
301 status: 403,
302 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
303 },
304 )
305 : json({ ok: true }),
306 );
307 return Effect.gen(function* () {
308 yield* TestClock.setTime(NOW);
309 const api = yield* GitHubApi.GitHubApi;
310 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
311 yield* Effect.flip(api.rest(read));
312 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
313 const merged = yield* api
314 .rest({
315 host: "github.com",
316 operation: "merge",
317 method: "PUT",
318 path: "repos/acme/web/pulls/7/merge",
319 })
320 .pipe(Effect.provideService(GitHubApi.AllowGitHubReserve, true));
321 expect(merged.status).toBe(200);
322 expect(requests).toHaveLength(2);
323 }).pipe(Effect.provide(layer));
324 });
325
326 it.effect("reads an untyped GraphQL quota error as a rate limit", () => {
327 const reset = Math.floor(NOW / 1000) + 900;
328 const { layer } = harness(() =>
329 json(
330 { errors: [{ message: "API rate limit already exceeded for user ID 1." }] },
331 { headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
332 ),
333 );
334 return Effect.gen(function* () {
335 yield* TestClock.setTime(NOW);
336 const api = yield* GitHubApi.GitHubApi;
337 const error = yield* Effect.flip(
338 api.graphql({ host: "github.com", operation: "lookup", query: "query { viewer { id } }" }),
339 );
340 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
341 }).pipe(Effect.provide(layer));
342 });
343
344 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
345 let call = 0;
346 const { layer } = harness(() =>
347 ++call === 1
348 ? new Response(null, { status: 304 })
349 : json(
350 { message: "API rate limit exceeded" },
351 {
352 status: 403,
353 headers: { "retry-after": "60" },
354 },
355 ),
356 );
357 return Effect.gen(function* () {
358 yield* TestClock.setTime(NOW);
359 const api = yield* GitHubApi.GitHubApi;
360 const notModified = yield* api.rest({
361 host: "github.com",
362 operation: "checks",
363 path: "repos/acme/web/pulls/7",
364 ifNoneMatch: '"abc"',
365 });
366 expect(notModified.status).toBe(304);
367 const error = yield* Effect.flip(
368 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
369 );
370 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
371 }).pipe(Effect.provide(layer));
372 });
373
374 it.effect("drops a refused token so the next request asks the source again", () => {
375 const { layer, requests, invalidations } = harness((request) =>
376 request.headers.authorization === "Bearer first"
377 ? new Response(null, { status: 401 })
378 : json({ ok: true }),
379 );
380 return Effect.gen(function* () {
381 const api = yield* GitHubApi.GitHubApi;
382 const refused = yield* Effect.flip(
383 api.rest({ host: "github.com", operation: "user", path: "user" }),
384 );
385 expect(refused._tag).toBe("GitHubApiAuthenticationError");
386 expect(invalidations()).toBe(1);
387 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
388 expect(answered.status).toBe(200);
389 expect(requests.map((request) => request.headers.authorization)).toEqual([
390 "Bearer first",
391 "Bearer second",
392 ]);
393 }).pipe(Effect.provide(layer));
394 });
395
396 it.effect("refuses to send a pinned credential to another host", () => {
397 const { layer, requests } = harness(() => json({}));
398 return Effect.gen(function* () {
399 const api = yield* GitHubApi.GitHubApi;
400 const error = yield* Effect.flip(
401 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
402 ).pipe(
403 Effect.provideService(GitHubApi.PinnedGitHubCredential, {
404 host: "github.com",
405 token: Redacted.make("pinned"),
406 credentialFingerprint: "github.com:pinned",
407 }),
408 );
409 expect(error._tag).toBe("GitHubApiAuthenticationError");
410 expect(requests).toHaveLength(0);
411 }).pipe(Effect.provide(layer));
412 });
413});
414
415describe("GitHubCredentials", () => {
416 const credentialsWith = (run: VcsProcess.VcsProcess["Service"]["run"]) =>
417 GitHubCredentials.layer.pipe(
418 Layer.provide(Layer.mock(VcsProcess.VcsProcess)({ run })),
419 Layer.provide(NodeServices.layer),
420 Layer.provide(ServerSettings.layerTest()),
421 );
422
423 it.effect("fails with GitHubCliMissingError when gh is not on PATH", () =>
424 Effect.gen(function* () {
425 const credentials = yield* GitHubCredentials.GitHubCredentials;
426 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
427 expect(error._tag).toBe("GitHubCliMissingError");
428 }).pipe(
429 Effect.provide(
430 credentialsWith(() =>
431 Effect.fail(
432 new VcsProcessSpawnError({
433 operation: "GitHubCredentials.get",
434 command: "gh",
435 cwd: "/",
436 cause: PlatformError.systemError({
437 _tag: "NotFound",
438 module: "ChildProcess",
439 method: "spawn",
440 }),
441 }),
442 ),
443 ),
444 ),
445 ),
446 );
447
448 it.effect("does not cache a gh failure that is not about signing in", () => {
449 let calls = 0;
450 return Effect.gen(function* () {
451 const credentials = yield* GitHubCredentials.GitHubCredentials;
452 const first = yield* Effect.flip(credentials.get("github.com"));
453 expect(first._tag).toBe("GitHubCliFailedError");
454 expect((yield* credentials.get("github.com")).source).toBe("gh");
455 expect(calls).toBe(2);
456 }).pipe(
457 Effect.provide(
458 credentialsWith(() =>
459 ++calls === 1
460 ? Effect.fail(
461 new VcsProcessTimeoutError({
462 operation: "GitHubCredentials.get",
463 command: "gh",
464 cwd: "/",
465 timeoutMs: 10_000,
466 }),
467 )
468 : Effect.succeed({
469 exitCode: ChildProcessSpawner.ExitCode(0),
470 stdout: "token\n",
471 stderr: "",
472 stdoutTruncated: false,
473 stderrTruncated: false,
474 }),
475 ),
476 ),
477 );
478 });
479
480 it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
481 Effect.gen(function* () {
482 const credentials = yield* GitHubCredentials.GitHubCredentials;
483 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
484 expect(error._tag).toBe("GitHubNotSignedInError");
485 }).pipe(
486 Effect.provide(
487 credentialsWith(() =>
488 Effect.succeed({
489 exitCode: ChildProcessSpawner.ExitCode(0),
490 stdout: "\n",
491 stderr: "",
492 stdoutTruncated: false,
493 stderrTruncated: false,
494 }),
495 ),
496 ),
497 ),
498 );
499});