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