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 // Nothing recorded carries the query string or the token.
121 const everything = spans
122 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
123 .join("\n");
124 expect(everything).not.toContain("head_sha");
125 expect(everything).not.toContain("first");
126 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
127 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
128 });
129
130 it.effect("lets an interactive request through a pause a background read recorded", () => {
131 const reset = Math.floor(NOW / 1000) + 600;
132 let call = 0;
133 const { layer, requests } = harness(() =>
134 ++call === 1
135 ? json(
136 { message: "API rate limit exceeded" },
137 {
138 status: 403,
139 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
140 },
141 )
142 : json({ ok: true }),
143 );
144 return Effect.gen(function* () {
145 yield* TestClock.setTime(NOW);
146 const api = yield* GitHubRest.GitHubRest;
147 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
148 yield* Effect.flip(api.rest(read));
149 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
150 const merged = yield* api
151 .rest({
152 host: "github.com",
153 operation: "merge",
154 method: "PUT",
155 path: "repos/acme/web/pulls/7/merge",
156 })
157 .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
158 expect(merged.status).toBe(200);
159 expect(requests).toHaveLength(2);
160 }).pipe(Effect.provide(layer));
161 });
162
163 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
164 let call = 0;
165 const { layer } = harness(() =>
166 ++call === 1
167 ? new Response(null, { status: 304 })
168 : json(
169 { message: "API rate limit exceeded" },
170 {
171 status: 403,
172 headers: { "retry-after": "60" },
173 },
174 ),
175 );
176 return Effect.gen(function* () {
177 yield* TestClock.setTime(NOW);
178 const api = yield* GitHubRest.GitHubRest;
179 const notModified = yield* api.rest({
180 host: "github.com",
181 operation: "checks",
182 path: "repos/acme/web/pulls/7",
183 ifNoneMatch: '"abc"',
184 });
185 expect(notModified.status).toBe(304);
186 const error = yield* Effect.flip(
187 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
188 );
189 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
190 }).pipe(Effect.provide(layer));
191 });
192
193 it.effect("drops a refused token so the next request asks the source again", () => {
194 const { layer, requests, invalidations } = harness((request) =>
195 request.headers.authorization === "Bearer first"
196 ? new Response(null, { status: 401 })
197 : json({ ok: true }),
198 );
199 return Effect.gen(function* () {
200 const api = yield* GitHubRest.GitHubRest;
201 const refused = yield* Effect.flip(
202 api.rest({ host: "github.com", operation: "user", path: "user" }),
203 );
204 expect(refused._tag).toBe("GitHubApiAuthenticationError");
205 expect(invalidations()).toBe(1);
206 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
207 expect(answered.status).toBe(200);
208 expect(requests.map((request) => request.headers.authorization)).toEqual([
209 "Bearer first",
210 "Bearer second",
211 ]);
212 }).pipe(Effect.provide(layer));
213 });
214
215 it.effect("refuses to send a pinned credential to another host", () => {
216 const { layer, requests } = harness(() => json({}));
217 return Effect.gen(function* () {
218 const api = yield* GitHubRest.GitHubRest;
219 const error = yield* Effect.flip(
220 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
221 ).pipe(
222 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
223 host: "github.com",
224 token: Redacted.make("pinned"),
225 credentialFingerprint: "github.com:pinned",
226 }),
227 );
228 expect(error._tag).toBe("GitHubApiAuthenticationError");
229 expect(requests).toHaveLength(0);
230 }).pipe(Effect.provide(layer));
231 });
232});
233
234describe("GitHubCredentials", () => {
235 const credentialsWith = (run: SourceControlHost.SourceControlHost["Service"]["process"]["run"]) =>
236 GitHubCredentials.layer.pipe(
237 Layer.provide(TestSourceControlHost.layer({ process: { run } })),
238 Layer.provide(NodeCrypto.layer),
239 );
240
241 it.effect("does not cache a gh failure that is not about signing in", () => {
242 let calls = 0;
243 return Effect.gen(function* () {
244 const credentials = yield* GitHubCredentials.GitHubCredentials;
245 const first = yield* Effect.flip(credentials.get("github.com"));
246 expect(first._tag).toBe("GitHubCliFailedError");
247 expect((yield* credentials.get("github.com")).source).toBe("gh");
248 expect(calls).toBe(2);
249 }).pipe(
250 Effect.provide(
251 credentialsWith(() =>
252 ++calls === 1
253 ? Effect.fail(
254 new VcsProcessTimeoutError({
255 operation: "GitHubCredentials.get",
256 command: "gh",
257 cwd: "/",
258 timeoutMs: 10_000,
259 }),
260 )
261 : Effect.succeed({
262 exitCode: ChildProcessSpawner.ExitCode(0),
263 stdout: "token\n",
264 stderr: "",
265 stdoutTruncated: false,
266 stderrTruncated: false,
267 }),
268 ),
269 ),
270 );
271 });
272
273 it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
274 Effect.gen(function* () {
275 const credentials = yield* GitHubCredentials.GitHubCredentials;
276 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
277 expect(error._tag).toBe("GitHubNotSignedInError");
278 }).pipe(
279 Effect.provide(
280 credentialsWith(() =>
281 Effect.succeed({
282 exitCode: ChildProcessSpawner.ExitCode(0),
283 stdout: "\n",
284 stderr: "",
285 stdoutTruncated: false,
286 stderrTruncated: false,
287 }),
288 ),
289 ),
290 ),
291 );
292});