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

GitHubRest.test.ts

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