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 // An enterprise token only goes to the host GH_HOST names, never to whatever a remote says.
98 expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
99 expect(
100 GitHubCredentials.environmentToken("git.acme.internal", {
101 ...env,
102 GH_HOST: "git.acme.internal",
103 }),
104 ).toBe("ghe");
105 expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
106 });
107});
108
109describe("GitHubRest", () => {
110 it.effect("traces the operation, path and quota, never the query string or the token", () => {
111 const spans: Array<Tracer.NativeSpan> = [];
112 const tracer = Tracer.make({
113 span: (options) => {
114 const span = new Tracer.NativeSpan(options);
115 spans.push(span);
116 return span;
117 },
118 });
119 const { layer } = harness(() =>
120 json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
121 );
122 return Effect.gen(function* () {
123 yield* TestClock.setTime(NOW);
124 const api = yield* GitHubRest.GitHubRest;
125 yield* api.rest({
126 host: "github.com",
127 operation: "listWorkflowRuns",
128 path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
129 });
130 const send = spans.find((span) => span.name === "GitHubRest.send")!;
131 expect(Object.fromEntries(send.attributes)).toMatchObject({
132 "github.operation": "listWorkflowRuns",
133 "github.kind": "rest",
134 "url.path": "/repos/acme/web/actions/runs",
135 "http.response.status_code": 200,
136 "github.ratelimit.remaining": 4800,
137 });
138 // Nothing recorded carries the query string or the token.
139 const everything = spans
140 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
141 .join("\n");
142 expect(everything).not.toContain("head_sha");
143 expect(everything).not.toContain("first");
144 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
145 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
146 });
147
148 it.effect("keeps the last tenth of a quota for interactive requests until it resets", () => {
149 const reset = Math.floor(NOW / 1000) + 600;
150 const quota = (remaining: number) => ({
151 "x-ratelimit-resource": "core",
152 "x-ratelimit-limit": "5000",
153 "x-ratelimit-remaining": String(remaining),
154 "x-ratelimit-reset": String(reset),
155 });
156 let remaining = 499;
157 const { layer, requests } = harness(() => json({ ok: true }, { headers: quota(remaining--) }));
158 return Effect.gen(function* () {
159 yield* TestClock.setTime(NOW);
160 const api = yield* GitHubRest.GitHubRest;
161 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
162 // The first answer leaves 499 of 5000, under the last tenth; the next background read waits.
163 yield* api.rest(read);
164 const refused = yield* Effect.flip(api.rest(read));
165 expect(refused).toMatchObject({
166 _tag: "SourceControlRateLimitPausedError",
167 retryAt: reset * 1000,
168 });
169 // A user's own request may spend the reserve.
170 yield* api.rest(read).pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
171 expect(requests).toHaveLength(2);
172 // The reset gives the background its quota back.
173 yield* TestClock.setTime(reset * 1000);
174 yield* api.rest(read);
175 expect(requests).toHaveLength(3);
176 }).pipe(Effect.provide(layer));
177 });
178
179 it.effect("carries GitHub's own reason for a refused REST request", () => {
180 const { layer } = harness(() =>
181 json(
182 {
183 message: "Validation Failed",
184 errors: [
185 {
186 resource: "PullRequest",
187 code: "custom",
188 message: "A pull request already exists for acme:feature.",
189 },
190 ],
191 },
192 { status: 422 },
193 ),
194 );
195 return Effect.gen(function* () {
196 const api = yield* GitHubRest.GitHubRest;
197 const error = yield* Effect.flip(
198 api.rest({
199 host: "github.com",
200 operation: "createPullRequest",
201 method: "POST",
202 path: "repos/acme/web/pulls",
203 }),
204 );
205 expect(error.message).toBe(
206 "GitHub returned an error: Validation Failed; A pull request already exists for acme:feature.",
207 );
208 }).pipe(Effect.provide(layer));
209 });
210
211 it.effect("lets an interactive request through a pause a background read recorded", () => {
212 const reset = Math.floor(NOW / 1000) + 600;
213 let call = 0;
214 const { layer, requests } = harness(() =>
215 ++call === 1
216 ? json(
217 { message: "API rate limit exceeded" },
218 {
219 status: 403,
220 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
221 },
222 )
223 : json({ ok: true }),
224 );
225 return Effect.gen(function* () {
226 yield* TestClock.setTime(NOW);
227 const api = yield* GitHubRest.GitHubRest;
228 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
229 yield* Effect.flip(api.rest(read));
230 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
231 const merged = yield* api
232 .rest({
233 host: "github.com",
234 operation: "merge",
235 method: "PUT",
236 path: "repos/acme/web/pulls/7/merge",
237 })
238 .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
239 expect(merged.status).toBe(200);
240 expect(requests).toHaveLength(2);
241 }).pipe(Effect.provide(layer));
242 });
243
244 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
245 let call = 0;
246 const { layer } = harness(() =>
247 ++call === 1
248 ? new Response(null, { status: 304 })
249 : json(
250 { message: "API rate limit exceeded" },
251 {
252 status: 403,
253 headers: { "retry-after": "60" },
254 },
255 ),
256 );
257 return Effect.gen(function* () {
258 yield* TestClock.setTime(NOW);
259 const api = yield* GitHubRest.GitHubRest;
260 const notModified = yield* api.rest({
261 host: "github.com",
262 operation: "checks",
263 path: "repos/acme/web/pulls/7",
264 ifNoneMatch: '"abc"',
265 });
266 expect(notModified.status).toBe(304);
267 const error = yield* Effect.flip(
268 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
269 );
270 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
271 }).pipe(Effect.provide(layer));
272 });
273
274 it.effect("drops a refused token so the next request asks the source again", () => {
275 const { layer, requests, invalidations } = harness((request) =>
276 request.headers.authorization === "Bearer first"
277 ? new Response(null, { status: 401 })
278 : json({ ok: true }),
279 );
280 return Effect.gen(function* () {
281 const api = yield* GitHubRest.GitHubRest;
282 const refused = yield* Effect.flip(
283 api.rest({ host: "github.com", operation: "user", path: "user" }),
284 );
285 expect(refused._tag).toBe("GitHubApiAuthenticationError");
286 expect(invalidations()).toBe(1);
287 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
288 expect(answered.status).toBe(200);
289 expect(requests.map((request) => request.headers.authorization)).toEqual([
290 "Bearer first",
291 "Bearer second",
292 ]);
293 }).pipe(Effect.provide(layer));
294 });
295
296 it.effect("refuses to send a pinned credential to another host", () => {
297 const { layer, requests } = harness(() => json({}));
298 return Effect.gen(function* () {
299 const api = yield* GitHubRest.GitHubRest;
300 const error = yield* Effect.flip(
301 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
302 ).pipe(
303 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
304 host: "github.com",
305 token: Redacted.make("pinned"),
306 credentialFingerprint: "github.com:pinned",
307 }),
308 );
309 expect(error._tag).toBe("GitHubApiAuthenticationError");
310 expect(requests).toHaveLength(0);
311 }).pipe(Effect.provide(layer));
312 });
313});
314
315describe("GitHubCredentials", () => {
316 const credentialsWith = (run: SourceControlHost.SourceControlHost["Service"]["process"]["run"]) =>
317 GitHubCredentials.layer.pipe(
318 Layer.provide(TestSourceControlHost.layer({ process: { run } })),
319 Layer.provide(NodeCrypto.layer),
320 );
321
322 it.effect("fails with GitHubCliMissingError when gh is not on PATH", () =>
323 Effect.gen(function* () {
324 const credentials = yield* GitHubCredentials.GitHubCredentials;
325 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
326 expect(error._tag).toBe("GitHubCliMissingError");
327 }).pipe(
328 Effect.provide(
329 credentialsWith(() =>
330 Effect.fail(
331 new VcsProcessSpawnError({
332 operation: "GitHubCredentials.get",
333 command: "gh",
334 cwd: "/",
335 cause: PlatformError.systemError({
336 _tag: "NotFound",
337 module: "ChildProcess",
338 method: "spawn",
339 }),
340 }),
341 ),
342 ),
343 ),
344 ),
345 );
346
347 it.effect("does not cache a gh failure that is not about signing in", () => {
348 let calls = 0;
349 return Effect.gen(function* () {
350 const credentials = yield* GitHubCredentials.GitHubCredentials;
351 const first = yield* Effect.flip(credentials.get("github.com"));
352 expect(first._tag).toBe("GitHubCliFailedError");
353 expect((yield* credentials.get("github.com")).source).toBe("gh");
354 expect(calls).toBe(2);
355 }).pipe(
356 Effect.provide(
357 credentialsWith(() =>
358 ++calls === 1
359 ? Effect.fail(
360 new VcsProcessTimeoutError({
361 operation: "GitHubCredentials.get",
362 command: "gh",
363 cwd: "/",
364 timeoutMs: 10_000,
365 }),
366 )
367 : Effect.succeed({
368 exitCode: ChildProcessSpawner.ExitCode(0),
369 stdout: "token\n",
370 stderr: "",
371 stdoutTruncated: false,
372 stderrTruncated: false,
373 }),
374 ),
375 ),
376 );
377 });
378
379 it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
380 Effect.gen(function* () {
381 const credentials = yield* GitHubCredentials.GitHubCredentials;
382 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
383 expect(error._tag).toBe("GitHubNotSignedInError");
384 }).pipe(
385 Effect.provide(
386 credentialsWith(() =>
387 Effect.succeed({
388 exitCode: ChildProcessSpawner.ExitCode(0),
389 stdout: "\n",
390 stderr: "",
391 stdoutTruncated: false,
392 stderrTruncated: false,
393 }),
394 ),
395 ),
396 ),
397 );
398});