Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubRest.test.ts

675 lines26.5 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4// @effect-diagnostics-next-line nodeBuiltinImport:off -- A real socket server verifies the HTTP wire format.
5import * as NodeHttp from "node:http";
6// @effect-diagnostics-next-line nodeBuiltinImport:off -- The socket fixture owns its temporary directory.
7import * as NodeFSP from "node:fs/promises";
8import * as NodeOS from "node:os";
9// @effect-diagnostics-next-line nodeBuiltinImport:off -- Keep the native socket path within the temporary directory.
10import * as NodePath from "node:path";
11import * as FeatureFlags from "@t3tools/shared/FeatureFlags";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Redacted from "effect/Redacted";
17import * as TestClock from "effect/testing/TestClock";
18import * as Tracer from "effect/Tracer";
19import { ChildProcessSpawner } from "effect/process";
20import { VcsProcessTimeoutError } from "@t3tools/contracts";
21import { HttpClient, HttpClientResponse, HttpClientRequest } from "effect/http";
22import { GraphQLClient } from "effect/graphql";
23​
24import * as GitHubRest from "./GitHubRest.ts";
25import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
26import * as GitHubCredentials from "./GitHubCredentials.ts";
27import * as GitHubQuota from "./GitHubQuota.ts";
28import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
29import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
30import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
31import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
32import * as GitHubHttpClient from "./GitHubHttpClient.ts";
33import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
34import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts";
35import { driver } from "./driver.ts";
36​
37const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
38 enabled: false,
39 token: () => Effect.succeedNone,
40 invalidate: () => Effect.void,
41});
42​
43const NOW = Date.parse("2026-10-05T12:00:00.000Z");
44​
45function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
46 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
47 let tokens = ["first", "second"];
48 let invalidations = 0;
49 let credentialReads = 0;
50 const credentials = Layer.succeed(
51 GitHubCredentials.GitHubCredentials,
52 GitHubCredentials.GitHubCredentials.of({
53 get: (host) =>
54 Effect.sync(() => {
55 credentialReads++;
56 return {
57 host,
58 token: Redacted.make(tokens[0]!),
59 source: "gh" as const,
60 fingerprint: `${host}:${tokens[0]}`,
61 };
62 }),
63 saved: () => Effect.succeedNone,
64 fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
65 invalidate: () =>
66 Effect.sync(() => {
67 invalidations++;
68 tokens = tokens.slice(1);
69 }),
70 }),
71 );
72 const http = Layer.succeed(
73 HttpClient.HttpClient,
74 HttpClient.make((request) => {
75 requests.push(request);
76 return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
77 }),
78 );
79 const layer = GitHubRest.layer.pipe(
80 Layer.provide(Layer.mergeAll(credentials, http, appSignedOut)),
81 Layer.provideMerge(GitHubQuota.layer),
82 Layer.provideMerge(SourceControlRateLimit.layer),
83 );
84 return {
85 layer,
86 requests,
87 invalidations: () => invalidations,
88 credentialReads: () => credentialReads,
89 };
91​
92const json = (body: unknown, init?: ResponseInit) =>
93 new Response(JSON.stringify(body), {
94 ...init,
95 headers: { "content-type": "application/json", ...init?.headers },
96 });
97​
98describe("environmentToken", () => {
99 it("follows gh's precedence per kind of host", () => {
100 const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
101 expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
102 expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
103 "github",
104 );
105 expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
106 expect(
107 GitHubCredentials.environmentToken("git.acme.internal", {
108 ...env,
109 GH_HOST: "git.acme.internal",
110 }),
111 ).toBe("ghe");
112 expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
113 });
114});
115​
116describe("GitHubRest", () => {
117 it.live("routes REST and GraphQL through gh's plain HTTP Unix socket", () =>
118 Effect.gen(function* () {
119 const directory = yield* Effect.acquireRelease(
120 Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "gh-"))),
121 (directory) =>
122 Effect.promise(() => NodeFSP.rm(directory, { recursive: true, force: true })),
123 );
124 const socketPath = NodePath.join(directory, "api.sock");
125 const requests: Array<{
126 method: string | undefined;
127 path: string | undefined;
128 headers: NodeHttp.IncomingHttpHeaders;
129 body: string;
130 }> = [];
131 let redirectClosed = Promise.resolve();
132 const server = NodeHttp.createServer(async (request, response) => {
133 const chunks: Array<Buffer> = [];
134 for await (const chunk of request) chunks.push(Buffer.from(chunk));
135 const body = Buffer.concat(chunks).toString();
136 requests.push({
137 method: request.method,
138 path: request.url,
139 headers: request.headers,
140 body,
141 });
142 if (request.url?.endsWith("/renamed-user")) {
143 redirectClosed = new Promise<void>((resolve) => response.once("close", resolve));
144 response.writeHead(301, { location: "user?per_page=1" });
145 response.flushHeaders();
146 return;
147 }
148 if (request.url === "/cross-host" || request.url === "/loop") {
149 response.writeHead(301, {
150 location: request.url === "/loop" ? "/loop" : "https://redirect.acme.test:8443/user",
151 });
152 response.end();
153 return;
154 }
155 if (request.url === "/cross-post-307" || request.url === "/cross-post-308") {
156 response.writeHead(Number(request.url.slice(-3)), {
157 location: "https://redirect.acme.test:8443/user",
158 });
159 response.end();
160 return;
161 }
162 if (request.url === "/post-303" || request.url === "/post-307") {
163 response.writeHead(request.url === "/post-303" ? 303 : 307, { location: "/user" });
164 response.end();
165 return;
166 }
167 response.statusCode = request.url === "/user/starred/acme/web" ? 204 : 200;
168 response.setHeader("content-type", "application/json");
169 response.end(
170 JSON.stringify(
171 body.includes("query PullRequestByNumber")
172 ? {
173 data: {
174 repository: {
175 pullRequest: {
176 number: 7,
177 title: "Socket request",
178 url: "https://github.com/acme/web/pull/7",
179 baseRefName: "main",
180 headRefName: "feature",
181 headRefOid: "f".repeat(40),
182 state: "OPEN",
183 isDraft: false,
184 mergedAt: null,
185 closedAt: null,
186 updatedAt: "2026-01-02T00:00:00Z",
187 isCrossRepository: false,
188 headRepository: { name: "web", nameWithOwner: "acme/web" },
189 headRepositoryOwner: { __typename: "User", login: "acme" },
190 },
191 },
192 },
193 }
194 : request.url?.endsWith("graphql")
195 ? { data: { repository: { pullRequest: { additions: 3, deletions: 1 } } } }
196 : { login: "proxy-user" },
197 ),
198 );
199 });
200 yield* Effect.acquireRelease(
201 Effect.promise(
202 () =>
203 new Promise<void>((resolve, reject) => {
204 server.once("error", reject);
205 server.listen(socketPath, resolve);
206 }),
207 ),
208 () =>
209 Effect.promise(
210 () =>
211 new Promise<void>((resolve, reject) =>
212 server.close((error) => (error ? reject(error) : resolve())),
213 ),
214 ),
215 );
216 const directRequests: Array<string> = [];
217 const fallback = Layer.succeed(
218 HttpClient.HttpClient,
219 HttpClient.make((request) => {
220 directRequests.push(request.url);
221 return Effect.succeed(HttpClientResponse.fromWeb(request, json({}, { status: 401 })));
222 }),
223 );
224 const host = TestSourceControlHost.layer({
225 process: {
226 run: (input) => {
227 expect(input.command).toBe("gh");
228 if (input.args[0] === "config") {
229 expect(input.args).toEqual(["config", "get", "http_unix_socket"]);
230 return Effect.succeed(TestSourceControlHost.processOutput(`${socketPath}\n`));
231 }
232 expect(input.args.slice(0, 2)).toEqual(["auth", "token"]);
233 return Effect.succeed(TestSourceControlHost.processOutput("placeholder\n"));
234 },
235 },
236 });
237 const layer = GitHubRest.layerWithDependencies.pipe(
238 Layer.provideMerge(GitHubHttpClient.layer),
239 Layer.provide(
240 Layer.mergeAll(
241 host,
242 fallback,
243 NodeServices.layer,
244 NodeCrypto.layer,
245 SourceControlRateLimit.layer,
246 ),
247 ),
248 );
249 yield* Effect.gen(function* () {
250 const rest = yield* GitHubRest.GitHubRest;
251 const client = yield* GraphQLClient.make(
252 PullRequestBatchesGraphQLGroup.middleware(GitHubGraphQlClient.GitHubGraphQlAuth),
253 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
254 for (const [host, apiHost, root] of [
255 ["github.com", "api.github.com", ""],
256 ["git.acme.test:8443", "git.acme.test:8443", "/api/v3"],
257 ] as const) {
258 const answer = yield* rest.rest({
259 host,
260 operation: "user",
261 path: "user?per_page=1",
262 });
263 expect(JSON.parse(answer.body)).toEqual({ login: "proxy-user" });
264 const stats = yield* client
265 .PullRequestStats({ owner: "acme", name: "web", number: 7 })
266 .pipe(GitHubGraphQlClient.call({ host, operation: "stats" }));
267 expect(stats).toEqual({ repository: { pullRequest: { additions: 3, deletions: 1 } } });
268 const [restRequest, graphqlRequest] = requests.slice(-2);
269 expect(restRequest).toMatchObject({ method: "GET", path: `${root}/user?per_page=1` });
270 expect(graphqlRequest).toMatchObject({
271 method: "POST",
272 path: root === "" ? "/graphql" : "/api/graphql",
273 });
274 for (const request of [restRequest!, graphqlRequest!]) {
275 expect(request.headers).toMatchObject({
276 host: apiHost,
277 authorization: "Bearer placeholder",
278 "user-agent": "t3code",
279 "x-github-api-version": "2022-11-28",
280 });
281 }
282 expect(JSON.parse(graphqlRequest!.body).variables).toEqual({
283 owner: "acme",
284 name: "web",
285 number: 7,
286 });
287 }
288 const renamed = yield* rest.rest({
289 host: "github.com",
290 operation: "renamedUser",
291 path: "renamed-user",
292 });
293 expect(JSON.parse(renamed.body)).toEqual({ login: "proxy-user" });
294 yield* Effect.promise(() => redirectClosed);
295 expect(requests.at(-1)).toMatchObject({
296 path: "/user?per_page=1",
297 headers: { host: "api.github.com", authorization: "Bearer placeholder" },
298 });
299 yield* rest.rest({ host: "github.com", operation: "redirect", path: "cross-host" });
300 expect(requests.at(-1)?.headers.host).toBe("redirect.acme.test:8443");
301 expect(requests.at(-1)?.headers.authorization).toBeUndefined();
302 const loopError = yield* Effect.flip(
303 rest.rest({ host: "github.com", operation: "redirectLoop", path: "loop" }),
304 );
305 expect(loopError._tag).toBe("GitHubApiResponseError");
306 expect(requests.filter((request) => request.path === "/loop")).toHaveLength(11);
307 const http = yield* HttpClient.HttpClient;
308 for (const status of [303, 307]) {
309 const response = yield* http.execute(
310 HttpClientRequest.post(`https://api.github.com/post-${status}`).pipe(
311 HttpClientRequest.bodyJsonUnsafe({ query: "query { viewer { login } }" }),
312 HttpClientRequest.bearerToken("placeholder"),
313 ),
314 );
315 yield* response.text;
316 expect(requests.at(-1)).toMatchObject({
317 method: status === 303 ? "GET" : "POST",
318 path: "/user",
319 body: status === 303 ? "" : JSON.stringify({ query: "query { viewer { login } }" }),
320 });
321 }
322 for (const status of [307, 308]) {
323 const before = requests.length;
324 const response = yield* http.execute(
325 HttpClientRequest.post(`https://api.github.com/cross-post-${status}`).pipe(
326 HttpClientRequest.bodyJsonUnsafe({ query: "query { viewer { login } }" }),
327 HttpClientRequest.bearerToken("placeholder"),
328 ),
329 );
330 yield* response.text;
331 expect(response.status).toBe(status);
332 expect(requests.slice(before)).toHaveLength(1);
333 expect(requests.at(-1)?.headers.host).toBe("api.github.com");
334 }
335 const instance = yield* driver.make.pipe(
336 Effect.provide(
337 Layer.mergeAll(
338 host,
339 fallback,
340 NodeServices.layer,
341 NodeCrypto.layer,
342 SourceControlRateLimit.layer,
343 ),
344 ),
345 );
346 const reference = yield* instance.sourceControl.getChangeRequest({
347 cwd: directory,
348 reference: "https://github.com/acme/web/pull/7",
349 });
350 expect(reference.number).toBe(7);
351 expect(requests.at(-1)?.body).toContain("query PullRequestByNumber");
352 expect(yield* instance.isRepositoryStarred!("github.com", "acme/web")).toBe(true);
353 expect(requests.at(-1)?.path).toBe("/user/starred/acme/web");
354 yield* Effect.promise(() => NodeFSP.unlink(socketPath));
355 const error = yield* Effect.flip(
356 rest.rest({ host: "github.com", operation: "user", path: "user" }),
357 );
358 expect(error._tag).toBe("GitHubApiRequestError");
359 expect(directRequests).toEqual([]);
360 const mediaUrl = "https://objects.githubusercontent.com/proof.png";
361 const media = yield* instance.fetchMedia!({ url: mediaUrl, headers: {} });
362 expect(media?.status).toBe(401);
363 expect(directRequests).toEqual([mediaUrl]);
364 }).pipe(
365 Effect.provide(layer.pipe(Layer.provideMerge(FeatureFlags.layerTest()))),
366 Effect.provideService(HostProcess.Environment, {}),
367 );
368 }),
369 );
370​
371 it.effect.each(["", "unavailable"])(
372 "keeps the existing HTTP client when gh's socket is %s",
373 (config) => {
374 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
375 const fallback = Layer.succeed(
376 HttpClient.HttpClient,
377 HttpClient.make((request) => {
378 requests.push(request);
379 return Effect.succeed(
380 HttpClientResponse.fromWeb(request, json({ login: "direct-user" })),
381 );
382 }),
383 );
384 const host = TestSourceControlHost.layer({
385 process: {
386 run: () =>
387 config === ""
388 ? Effect.succeed(TestSourceControlHost.processOutput("\n"))
389 : Effect.fail(
390 new VcsProcessTimeoutError({
391 operation: "GitHubHttpClient.config",
392 command: "gh",
393 cwd: "/",
394 timeoutMs: 10_000,
395 }),
396 ),
397 },
398 });
399 return Effect.gen(function* () {
400 const api = yield* HttpClient.HttpClient;
401 const answer = yield* api.execute(
402 HttpClientRequest.get("https://api.github.com/user").pipe(
403 HttpClientRequest.bearerToken("first"),
404 ),
405 );
406 expect(yield* answer.json).toEqual({ login: "direct-user" });
407 expect(requests).toHaveLength(1);
408 expect(requests[0]).toMatchObject({
409 url: "https://api.github.com/user",
410 headers: { authorization: "Bearer first" },
411 });
412 }).pipe(
413 Effect.provide(GitHubHttpClient.layer.pipe(Layer.provide(Layer.merge(host, fallback)))),
414 );
415 },
416 );
417​
418 it.effect("traces the operation, path and quota, never the query string or the token", () => {
419 const spans: Array<Tracer.NativeSpan> = [];
420 const tracer = Tracer.make({
421 span: (options) => {
422 const span = new Tracer.NativeSpan(options);
423 spans.push(span);
424 return span;
425 },
426 });
427 const { layer } = harness(() =>
428 json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
429 );
430 return Effect.gen(function* () {
431 yield* TestClock.setTime(NOW);
432 const api = yield* GitHubRest.GitHubRest;
433 yield* api.rest({
434 host: "github.com",
435 operation: "listWorkflowRuns",
436 path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
437 });
438 const send = spans.find((span) => span.name === "GitHubRest.send")!;
439 expect(Object.fromEntries(send.attributes)).toMatchObject({
440 "github.operation": "listWorkflowRuns",
441 "github.kind": "rest",
442 "url.path": "/repos/acme/web/actions/runs",
443 "http.response.status_code": 200,
444 "github.ratelimit.remaining": 4800,
445 });
446 const everything = spans
447 .flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
448 .join("\n");
449 expect(everything).not.toContain("head_sha");
450 expect(everything).not.toContain("first");
451 expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
452 }).pipe(Effect.provide(layer), Effect.withTracer(tracer));
453 });
454​
455 it.effect("lets an interactive request through a pause a background read recorded", () => {
456 const reset = Math.floor(NOW / 1000) + 600;
457 let call = 0;
458 const { layer, requests } = harness(() =>
459 ++call === 1
460 ? json(
461 { message: "API rate limit exceeded" },
462 {
463 status: 403,
464 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
465 },
466 )
467 : json({ ok: true }),
468 );
469 return Effect.gen(function* () {
470 yield* TestClock.setTime(NOW);
471 const api = yield* GitHubRest.GitHubRest;
472 const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
473 yield* Effect.flip(api.rest(read));
474 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
475 const merged = yield* api
476 .rest({
477 host: "github.com",
478 operation: "merge",
479 method: "PUT",
480 path: "repos/acme/web/pulls/7/merge",
481 })
482 .pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
483 expect(merged.status).toBe(200);
484 expect(requests).toHaveLength(2);
485 }).pipe(Effect.provide(layer));
486 });
487​
488 it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
489 let call = 0;
490 const { layer } = harness(() =>
491 ++call === 1
492 ? new Response(null, { status: 304 })
493 : json(
494 { message: "API rate limit exceeded" },
495 {
496 status: 403,
497 headers: { "retry-after": "60" },
498 },
499 ),
500 );
501 return Effect.gen(function* () {
502 yield* TestClock.setTime(NOW);
503 const api = yield* GitHubRest.GitHubRest;
504 const notModified = yield* api.rest({
505 host: "github.com",
506 operation: "checks",
507 path: "repos/acme/web/pulls/7",
508 ifNoneMatch: '"abc"',
509 });
510 expect(notModified.status).toBe(304);
511 const error = yield* Effect.flip(
512 api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
513 );
514 expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
515 }).pipe(Effect.provide(layer));
516 });
517​
518 it.effect("reads a proxy's 403 with Retry-After as a refusal and keeps the host open", () => {
519 const pages = [
520 "<html><head><title>403 Forbidden</title></head><body>nginx</body></html>",
521 "<html><body>Request blocked by proxy abuse detection; contact your administrator</body></html>",
522 ];
523 const { layer, requests } = harness(
524 () =>
525 new Response(pages.shift(), {
526 status: 403,
527 headers: { "content-type": "text/html", "retry-after": "5" },
528 }),
529 );
530 return Effect.gen(function* () {
531 yield* TestClock.setTime(NOW);
532 const api = yield* GitHubRest.GitHubRest;
533 const read = {
534 host: "ghes.example.internal",
535 operation: "checks",
536 path: "repos/acme/web/pulls/7",
537 };
538 const first = yield* Effect.flip(api.rest(read));
539 expect(first).toMatchObject({ _tag: "GitHubApiResponseError", status: 403 });
540 const second = yield* Effect.flip(api.rest(read));
541 expect(second).toMatchObject({ _tag: "GitHubApiResponseError", status: 403 });
542 expect(requests).toHaveLength(2);
543 }).pipe(Effect.provide(layer));
544 });
545​
546 it.effect("pauses the host on an abuse-detection 403 that never says rate limit", () => {
547 const { layer, requests } = harness(() =>
548 json(
549 {
550 message: "You have triggered an abuse detection mechanism. Please wait before retrying.",
551 documentation_url:
552 "https://docs.github.com/rest/overview/resources-in-the-rest-api#abuse-rate-limits",
553 },
554 { status: 403, headers: { "retry-after": "60", "x-ratelimit-remaining": "4878" } },
555 ),
556 );
557 return Effect.gen(function* () {
558 yield* TestClock.setTime(NOW);
559 const api = yield* GitHubRest.GitHubRest;
560 const read = { host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" };
561 expect(yield* Effect.flip(api.rest(read))).toMatchObject({
562 _tag: "GitHubApiRateLimitError",
563 retryAt: NOW + 60_000,
564 });
565 expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
566 expect(requests).toHaveLength(1);
567 }).pipe(Effect.provide(layer));
568 });
569​
570 it.effect("drops a refused token so the next request asks the source again", () => {
571 const { layer, requests, invalidations } = harness((request) =>
572 request.headers.authorization === "Bearer first"
573 ? new Response(null, { status: 401 })
574 : json({ ok: true }),
575 );
576 return Effect.gen(function* () {
577 const api = yield* GitHubRest.GitHubRest;
578 const refused = yield* Effect.flip(
579 api.rest({ host: "github.com", operation: "user", path: "user" }),
580 );
581 expect(refused._tag).toBe("GitHubApiAuthenticationError");
582 expect(invalidations()).toBe(1);
583 const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
584 expect(answered.status).toBe(200);
585 expect(requests.map((request) => request.headers.authorization)).toEqual([
586 "Bearer first",
587 "Bearer second",
588 ]);
589 }).pipe(Effect.provide(layer));
590 });
591​
592 it.effect("refuses to send a pinned credential to another host", () => {
593 const { layer, requests } = harness(() => json({}));
594 return Effect.gen(function* () {
595 const api = yield* GitHubRest.GitHubRest;
596 const error = yield* Effect.flip(
597 api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
598 ).pipe(
599 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
600 host: "github.com",
601 token: Redacted.make("pinned"),
602 credentialFingerprint: "github.com:pinned",
603 }),
604 );
605 expect(error._tag).toBe("GitHubApiAuthenticationError");
606 expect(requests).toHaveLength(0);
607 }).pipe(Effect.provide(layer));
608 });
609});
610​
611describe("GitHubCredentials", () => {
612 const unexpectedHttp = HttpClient.make((request) =>
613 Effect.die(`Unexpected request to ${request.url}`),
614 );
615 const credentialsWith = (run: SourceControlHost.SourceControlHost["Service"]["process"]["run"]) =>
616 GitHubCredentials.layer.pipe(
617 Layer.provide(TestSourceControlHost.layer({ process: { run } })),
618 Layer.provide(NodeCrypto.layer),
619 Layer.provide(FileSystem.layerNoop({})),
620 Layer.provide(Layer.succeed(HttpClient.HttpClient, unexpectedHttp)),
621 );
622​
623 it.effect("reports a gh timeout as a timeout and does not cache it", () => {
624 let calls = 0;
625 return Effect.gen(function* () {
626 const credentials = yield* GitHubCredentials.GitHubCredentials;
627 const first = yield* Effect.flip(credentials.get("github.com"));
628 expect(first._tag).toBe("GitHubCliTimeoutError");
629 expect(first.message).not.toContain("gh auth status");
630 expect((yield* credentials.get("github.com")).source).toBe("gh");
631 expect(calls).toBe(2);
632 }).pipe(
633 Effect.provide(
634 credentialsWith(() =>
635 ++calls === 1
636 ? Effect.fail(
637 new VcsProcessTimeoutError({
638 operation: "GitHubCredentials.get",
639 command: "gh",
640 cwd: "/",
641 timeoutMs: 10_000,
642 }),
643 )
644 : Effect.succeed({
645 exitCode: ChildProcessSpawner.ExitCode(0),
646 stdout: "token\n",
647 stderr: "",
648 stdoutTruncated: false,
649 stderrTruncated: false,
650 }),
651 ),
652 ),
653 );
654 });
655​
656 it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
657 Effect.gen(function* () {
658 const credentials = yield* GitHubCredentials.GitHubCredentials;
659 const error = yield* Effect.flip(credentials.get("git.acme.internal"));
660 expect(error._tag).toBe("GitHubNotSignedInError");
661 }).pipe(
662 Effect.provide(
663 credentialsWith(() =>
664 Effect.succeed({
665 exitCode: ChildProcessSpawner.ExitCode(0),
666 stdout: "\n",
667 stderr: "",
668 stdoutTruncated: false,
669 stderrTruncated: false,
670 }),
671 ),
672 ),
673 ),
674 );
675});