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

GitHubRest.test.ts

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