Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Redacted from "effect/Redacted";
10import { HttpClient, HttpClientResponse } from "effect/http";
11import { ChildProcessSpawner } from "effect/process";
12import * as TestClock from "effect/testing/TestClock";
13
14import { DEFAULT_SERVER_SETTINGS, ServerSettingsError } from "@t3tools/contracts";
15import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
16import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
17import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
18import * as FeatureFlags from "@t3tools/shared/FeatureFlags";
19import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
20import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
21
22import * as GitHubClient from "../shared/definition.ts";
23import * as GitHubAppAccess from "./GitHubAppAccess.ts";
24import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
25import * as GitHubRest from "./GitHubRest.ts";
26
27type Reply = { readonly status?: number; readonly body: unknown };
28interface Sent {
29 readonly host: string;
30 readonly path: string;
31 readonly form: URLSearchParams;
32 /** The bearer token, if any. */
33 readonly token: string | undefined;
34}
35
36const HOUR = 3_600_000;
37
38const session = (overrides: Record<string, unknown> = {}) =>
39 JSON.stringify({
40 accessToken: "ghu_current",
41 accessTokenExpiresAt: 8 * HOUR,
42 refreshToken: "ghr_current",
43 refreshTokenExpiresAt: 4_000 * HOUR,
44 ...overrides,
45 });
46
47/** The whole GitHub request stack over a fake GitHub that `handle` answers. */
48function harness(options: {
49 readonly handle: (sent: Sent) => Reply;
50 readonly signIns?: Record<string, string>;
51 readonly tokens?: Record<string, string>;
52 /** Without one, the server has no `gh` login to fall back to. */
53 readonly ghSignedIn?: boolean;
54 /** Makes every settings write fail, as a full disk would. */
55 readonly settingsWritesFail?: boolean;
56 /** Holds a request open until it completes, to interleave other work with it. */
57 readonly gate?: (sent: Sent) => Effect.Effect<void>;
58 /** Defaults to a configured app; null runs without one. */
59 readonly clientId?: string | null;
60}) {
61 const requests: Array<Sent> = [];
62 const http = HttpClient.make((request) => {
63 const url = new URL(request.url);
64 const sent: Sent = {
65 host: url.host,
66 path: url.pathname,
67 form: new URLSearchParams(
68 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "",
69 ),
70 token: request.headers["authorization"]?.replace(/^Bearer /, ""),
71 };
72 return Effect.suspend(() => options.gate?.(sent) ?? Effect.void).pipe(
73 Effect.map(() => {
74 requests.push(sent);
75 const reply = options.handle(sent);
76 return HttpClientResponse.fromWeb(
77 request,
78 new Response(JSON.stringify(reply.body), {
79 status: reply.status ?? 200,
80 headers: { "content-type": "application/json" },
81 }),
82 );
83 }),
84 );
85 });
86 const run: SourceControlHost.SourceControlHost["Service"]["process"]["run"] = () =>
87 Effect.succeed({
88 exitCode: ChildProcessSpawner.ExitCode(0),
89 stdout: options.ghSignedIn === false ? "" : "gh-token\n",
90 stderr: "",
91 stdoutTruncated: false,
92 stderrTruncated: false,
93 });
94 const host = TestSourceControlHost.layer({
95 settings: applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
96 sourceControlHosts: {
97 github: { signIns: options.signIns ?? {}, tokens: options.tokens ?? {} },
98 },
99 }),
100 process: { run },
101 });
102 const failingWrites = Layer.effect(
103 SourceControlHost.SourceControlHost,
104 Effect.map(Effect.service(SourceControlHost.SourceControlHost), (service) => ({
105 ...service,
106 settings: {
107 ...service.settings,
108 update: () =>
109 Effect.fail(
110 new ServerSettingsError({ settingsPath: "settings.json", operation: "write-file" }),
111 ),
112 },
113 })),
114 ).pipe(Layer.provideMerge(host));
115 const layer = GitHubAppAccess.layer.pipe(
116 Layer.provideMerge(GitHubRest.layerWithDependencies),
117 Layer.provideMerge(SourceControlRateLimit.layer),
118 Layer.provideMerge(options.settingsWritesFail === true ? failingWrites : host),
119 Layer.provide(NodeCrypto.layer),
120 Layer.provide(
121 FeatureFlags.layerTest({
122 githubAppClientId: Option.fromNullishOr(
123 options.clientId === undefined ? "Iv-test-client" : options.clientId,
124 ),
125 }),
126 ),
127 Layer.provide(FileSystem.layerNoop({})),
128 Layer.provide(Layer.succeed(HttpClient.HttpClient, http)),
129 );
130 return { layer, requests };
131}
132
133const savedSignIns = Effect.gen(function* () {
134 const host = yield* SourceControlHost.SourceControlHost;
135 const settings = yield* host.settings.get;
136 return readSourceControlHostSettings(GitHubClient.settings, settings.sourceControlHosts.github)
137 .signIns;
138});
139
140/** A REST read through the request policy, answering with the token it went out with. */
141const readUser = Effect.gen(function* () {
142 const api = yield* GitHubRest.GitHubRest;
143 return yield* api.rest({ host: "github.com", operation: "test", path: "user" });
144});
145
146const deviceCode = {
147 device_code: "device-1",
148 user_code: "ABCD-1234",
149 verification_uri: "https://github.com/login/device",
150 expires_in: 900,
151 interval: 5,
152};
153
154const installedOn = (sent: Sent): Reply =>
155 sent.path === "/user/installations"
156 ? {
157 body: {
158 installations: [
159 { id: 1, repository_selection: "all", account: { login: "pingdotgg" } },
160 { id: 2, repository_selection: "selected", account: { login: "acme" } },
161 ],
162 },
163 }
164 : sent.path === "/user/installations/2/repositories"
165 ? { body: { repositories: [{ full_name: "acme/one" }] } }
166 : { status: 404, body: {} };
167
168beforeEach(() => {
169 for (const name of ["GH_TOKEN", "GITHUB_TOKEN"]) vi.stubEnv(name, "");
170});
171afterEach(() => {
172 vi.unstubAllEnvs();
173});
174
175describe("GitHubAppSignIn", () => {
176 it.effect("finishes a device-flow sign-in and saves the session", () => {
177 const answers = [
178 { error: "authorization_pending" },
179 { error: "slow_down", interval: 10 },
180 {
181 access_token: "ghu_new",
182 expires_in: 28_800,
183 refresh_token: "ghr_new",
184 refresh_token_expires_in: 15_897_600,
185 },
186 ];
187 const { layer, requests } = harness({
188 handle: (sent) =>
189 sent.path === "/login/device/code" ? { body: deviceCode } : { body: answers.shift() },
190 });
191 return Effect.gen(function* () {
192 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
193 expect(yield* signIn.start("github.com")).toEqual({
194 userCode: "ABCD-1234",
195 verificationUri: "https://github.com/login/device",
196 expiresAt: 900_000,
197 });
198 const waiting = yield* Effect.forkChild(signIn.wait("github.com"));
199 yield* TestClock.adjust("20 seconds");
200 yield* Fiber.join(waiting);
201
202 // `slow_down` stretches the interval: polls at 5s, 10s, then 20s.
203 const polls = requests.filter((sent) => sent.path === "/login/oauth/access_token");
204 expect(polls).toHaveLength(3);
205 expect(polls[0]?.form.get("client_id")).toBe("Iv-test-client");
206 expect(polls[0]?.form.get("device_code")).toBe("device-1");
207 expect(JSON.parse((yield* savedSignIns)["github.com"] ?? "")).toEqual({
208 accessToken: "ghu_new",
209 accessTokenExpiresAt: 20_000 + 28_800_000,
210 refreshToken: "ghr_new",
211 refreshTokenExpiresAt: 20_000 + 15_897_600_000,
212 });
213 }).pipe(Effect.provide(layer));
214 });
215
216 it.effect("reports a sign-in cancelled on GitHub and saves nothing", () => {
217 const { layer } = harness({
218 handle: (sent) =>
219 sent.path === "/login/device/code"
220 ? { body: deviceCode }
221 : { body: { error: "access_denied" } },
222 });
223 return Effect.gen(function* () {
224 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
225 yield* signIn.start("github.com");
226 const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com")));
227 yield* TestClock.adjust("5 seconds");
228 expect((yield* Fiber.join(waiting)).reason).toBe("denied");
229 expect(yield* savedSignIns).toEqual({});
230 }).pipe(Effect.provide(layer));
231 });
232
233 it.effect("expires a code nobody entered", () => {
234 const { layer } = harness({
235 handle: (sent) =>
236 sent.path === "/login/device/code"
237 ? { body: { ...deviceCode, expires_in: 12 } }
238 : { body: { error: "authorization_pending" } },
239 });
240 return Effect.gen(function* () {
241 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
242 yield* signIn.start("github.com");
243 const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com")));
244 yield* TestClock.adjust("15 seconds");
245 expect((yield* Fiber.join(waiting)).reason).toBe("expired");
246 }).pipe(Effect.provide(layer));
247 });
248
249 it.effect("cancels a sign-in so approving the code afterwards saves nothing", () => {
250 const { layer, requests } = harness({
251 handle: (sent) =>
252 sent.path === "/login/device/code"
253 ? { body: deviceCode }
254 : { body: { access_token: "ghu_new", expires_in: 28_800 } },
255 });
256 return Effect.gen(function* () {
257 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
258 yield* signIn.start("github.com");
259 const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com")));
260 yield* signIn.cancel("github.com");
261 yield* TestClock.adjust("10 seconds");
262 expect((yield* Fiber.join(waiting)).reason).toBe("cancelled");
263 expect(requests.map((sent) => sent.path)).toEqual(["/login/device/code"]);
264 expect(yield* savedSignIns).toEqual({});
265 }).pipe(Effect.provide(layer));
266 });
267
268 it.effect("refuses hosts the app is not registered on", () => {
269 const { layer, requests } = harness({ handle: () => ({ body: {} }) });
270 return Effect.gen(function* () {
271 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
272 expect((yield* Effect.flip(signIn.start("ghe.acme.test"))).reason).toBe("unsupported");
273 expect((yield* Effect.flip(signIn.wait("github.com"))).reason).toBe("not-started");
274 expect(requests).toEqual([]);
275 }).pipe(Effect.provide(layer));
276 });
277
278 it.effect("does nothing with the app when the server has no client ID", () => {
279 const { layer, requests } = harness({
280 clientId: null,
281 signIns: { "github.com": session() },
282 handle: () => ({ body: { login: "octocat" } }),
283 });
284 return Effect.gen(function* () {
285 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
286 expect(signIn.enabled).toBe(false);
287 expect((yield* Effect.flip(signIn.start("github.com"))).reason).toBe("unsupported");
288 expect(yield* (yield* GitHubAppAccess.GitHubAppAccess).reach("github.com", "acme/one")).toBe(
289 "signed-out",
290 );
291 // A session saved while it was on stays put but is not used.
292 yield* readUser;
293 expect(requests.map((sent) => sent.token)).toEqual(["gh-token"]);
294 expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]);
295 }).pipe(Effect.provide(layer));
296 });
297
298 describe("refresh", () => {
299 const refreshed = {
300 access_token: "ghu_refreshed",
301 expires_in: 28_800,
302 refresh_token: "ghr_refreshed",
303 refresh_token_expires_in: 15_897_600,
304 };
305
306 it.effect("refreshes an expiring token once for concurrent requests", () => {
307 const { layer, requests } = harness({
308 signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) },
309 handle: () => ({ body: refreshed }),
310 });
311 return Effect.gen(function* () {
312 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
313 const tokens = yield* Effect.all([signIn.token("github.com"), signIn.token("github.com")], {
314 concurrency: "unbounded",
315 });
316 expect(tokens).toEqual([Option.some("ghu_refreshed"), Option.some("ghu_refreshed")]);
317 expect(requests).toHaveLength(1);
318 expect(requests[0]?.form.get("grant_type")).toBe("refresh_token");
319 expect(requests[0]?.form.get("refresh_token")).toBe("ghr_current");
320 }).pipe(Effect.provide(layer));
321 });
322
323 it.effect("refreshes a token GitHub refused, and only that one", () => {
324 const { layer, requests } = harness({
325 signIns: { "github.com": session() },
326 handle: () => ({ body: refreshed }),
327 });
328 return Effect.gen(function* () {
329 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
330 yield* signIn.invalidate("github.com", "gh-token");
331 expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_current"));
332 yield* signIn.invalidate("github.com", "ghu_current");
333 expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_refreshed"));
334 expect(requests).toHaveLength(1);
335 }).pipe(Effect.provide(layer));
336 });
337
338 it.effect("signs out when GitHub refuses the refresh token", () => {
339 const { layer } = harness({
340 signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
341 handle: () => ({ body: { error: "bad_refresh_token" } }),
342 });
343 return Effect.gen(function* () {
344 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
345 expect(yield* signIn.token("github.com")).toEqual(Option.none());
346 expect(yield* savedSignIns).toEqual({});
347 }).pipe(Effect.provide(layer));
348 });
349
350 it.effect("keeps the session when a refresh fails for another reason", () => {
351 const { layer } = harness({
352 signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
353 handle: () => ({ body: { error: "unauthorized_client" } }),
354 });
355 return Effect.gen(function* () {
356 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
357 expect((yield* Effect.flip(signIn.token("github.com")))._tag).toBe("GitHubAppSessionError");
358 expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]);
359 }).pipe(Effect.provide(layer));
360 });
361
362 it.effect("does not ask GitHub again after it rejects the client's credentials", () => {
363 const { layer, requests } = harness({
364 signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
365 handle: () => ({ body: { error: "incorrect_client_credentials" } }),
366 });
367 return Effect.gen(function* () {
368 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
369 yield* Effect.exit(signIn.token("github.com"));
370 yield* Effect.exit(signIn.token("github.com"));
371 expect(requests).toHaveLength(1);
372 expect(yield* savedSignIns).toEqual({});
373 }).pipe(Effect.provide(layer));
374 });
375
376 it.effect("serves the still-valid token when a refresh ahead of expiry fails", () => {
377 const { layer } = harness({
378 signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) },
379 handle: () => ({ status: 502, body: {} }),
380 });
381 return Effect.gen(function* () {
382 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
383 expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_current"));
384 }).pipe(Effect.provide(layer));
385 });
386
387 it.effect("serves a refreshed token GitHub issued even when saving it fails", () => {
388 const { layer } = harness({
389 signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) },
390 settingsWritesFail: true,
391 handle: () => ({ body: refreshed }),
392 });
393 return Effect.gen(function* () {
394 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
395 const pending = yield* Effect.forkChild(signIn.token("github.com"));
396 yield* TestClock.adjust("1 second");
397 expect(yield* Fiber.join(pending)).toEqual(Option.some("ghu_refreshed"));
398 }).pipe(Effect.provide(layer));
399 });
400
401 it.effect("does not bring a session back that was signed out while it refreshed", () => {
402 const released = Deferred.makeUnsafe<void>();
403 const requested = Deferred.makeUnsafe<void>();
404 const { layer } = harness({
405 signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
406 gate: () =>
407 Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(released))),
408 handle: () => ({ body: refreshed }),
409 });
410 return Effect.gen(function* () {
411 const signIn = yield* GitHubAppSignIn.GitHubAppSignIn;
412 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
413 const refreshing = yield* Effect.forkChild(signIn.token("github.com"));
414 yield* Deferred.await(requested);
415 yield* settings.update({ sourceControlHosts: { github: { signIns: {} } } });
416 yield* Deferred.succeed(released, undefined);
417 expect(yield* Fiber.join(refreshing)).toEqual(Option.none());
418 expect(yield* savedSignIns).toEqual({});
419 }).pipe(Effect.provide(layer));
420 });
421 });
422});
423
424describe("GitHub requests with the app sign-in", () => {
425 const answerUser = (sent: Sent): Reply => ({ body: { login: sent.token ?? "anonymous" } });
426
427 it.effect("uses the app before GH_TOKEN and gh, and a saved token before the app", () => {
428 vi.stubEnv("GH_TOKEN", "from-env");
429 const signedIn = harness({ signIns: { "github.com": session() }, handle: answerUser });
430 const withToken = harness({
431 signIns: { "github.com": session() },
432 tokens: { "github.com": "saved-pat" },
433 handle: answerUser,
434 });
435 return Effect.gen(function* () {
436 yield* readUser.pipe(Effect.provide(signedIn.layer));
437 yield* readUser.pipe(Effect.provide(withToken.layer));
438 expect(signedIn.requests.map((sent) => sent.token)).toEqual(["ghu_current"]);
439 expect(withToken.requests.map((sent) => sent.token)).toEqual(["saved-pat"]);
440 });
441 });
442
443 it.effect("asks again with the user's own credential when the app gets not found", () => {
444 const { layer, requests } = harness({
445 signIns: { "github.com": session() },
446 handle: (sent) =>
447 sent.token === "ghu_current" ? { status: 404, body: {} } : answerUser(sent),
448 });
449 return Effect.gen(function* () {
450 const response = yield* readUser;
451 expect(JSON.parse(response.body)).toEqual({ login: "gh-token" });
452 expect(requests.map((sent) => sent.token)).toEqual(["ghu_current", "gh-token"]);
453 }).pipe(Effect.provide(layer));
454 });
455
456 it.effect("asks again when GitHub says the resource is not accessible by integration", () => {
457 const { layer, requests } = harness({
458 signIns: { "github.com": session() },
459 handle: (sent) =>
460 sent.token === "ghu_current"
461 ? { status: 403, body: { message: "Resource not accessible by integration" } }
462 : answerUser(sent),
463 });
464 return Effect.gen(function* () {
465 yield* readUser;
466 expect(requests.map((sent) => sent.token)).toEqual(["ghu_current", "gh-token"]);
467 }).pipe(Effect.provide(layer));
468 });
469
470 it.effect("keeps the app's answer when there is no other credential", () => {
471 const { layer, requests } = harness({
472 signIns: { "github.com": session() },
473 ghSignedIn: false,
474 handle: () => ({ status: 404, body: {} }),
475 });
476 return Effect.gen(function* () {
477 expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiNotFoundError");
478 expect(requests.map((sent) => sent.token)).toEqual(["ghu_current"]);
479 }).pipe(Effect.provide(layer));
480 });
481
482 it.effect("does not ask again after the user's own credential is refused", () => {
483 const { layer, requests } = harness({ handle: () => ({ status: 404, body: {} }) });
484 return Effect.gen(function* () {
485 expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiNotFoundError");
486 expect(requests.map((sent) => sent.token)).toEqual(["gh-token"]);
487 }).pipe(Effect.provide(layer));
488 });
489
490 it.effect("uses the gh login while the app session cannot refresh, and keeps the session", () => {
491 const { layer, requests } = harness({
492 signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) },
493 handle: (sent) => (sent.host === "github.com" ? { status: 502, body: {} } : answerUser(sent)),
494 });
495 return Effect.gen(function* () {
496 yield* readUser;
497 expect(requests.filter((sent) => sent.path === "/user").map((sent) => sent.token)).toEqual([
498 "gh-token",
499 ]);
500 expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]);
501 }).pipe(Effect.provide(layer));
502 });
503
504 it.effect("refreshes the app token after GitHub rejects it", () => {
505 let rejected = false;
506 const { layer, requests } = harness({
507 signIns: { "github.com": session() },
508 handle: (sent) => {
509 if (sent.path === "/login/oauth/access_token") {
510 return { body: { access_token: "ghu_refreshed", expires_in: 28_800 } };
511 }
512 if (sent.token === "ghu_current" && !rejected) {
513 rejected = true;
514 return { status: 401, body: {} };
515 }
516 return answerUser(sent);
517 },
518 });
519 return Effect.gen(function* () {
520 expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiAuthenticationError");
521 yield* readUser;
522 expect(requests.map((sent) => sent.token ?? sent.path)).toEqual([
523 "ghu_current",
524 "/login/oauth/access_token",
525 "ghu_refreshed",
526 ]);
527 }).pipe(Effect.provide(layer));
528 });
529});
530
531describe("GitHubAppAccess", () => {
532 it.effect("reads the installations as the app, even with a saved token", () => {
533 const { layer, requests } = harness({
534 signIns: { "github.com": session() },
535 tokens: { "github.com": "saved-pat" },
536 handle: installedOn,
537 });
538 return Effect.gen(function* () {
539 const access = yield* GitHubAppAccess.GitHubAppAccess;
540 expect(yield* access.reach("github.com", "pingdotgg/t3code")).toBe("covered");
541 expect(yield* access.reach("github.com", "acme/one")).toBe("covered");
542 expect(yield* access.reach("github.com", "acme/two")).toBe("not-covered");
543 expect(yield* access.reach("github.com", "https://github.com/Acme/One.git")).toBe("covered");
544 expect(new Set(requests.map((sent) => sent.token))).toEqual(new Set(["ghu_current"]));
545 // One read of the installations serves every repository until it goes stale.
546 expect(requests.filter((sent) => sent.path === "/user/installations")).toHaveLength(1);
547 }).pipe(Effect.provide(layer));
548 });
549
550 it.effect("answers signed out without a session, and covered while GitHub fails", () => {
551 const signedOut = harness({ handle: installedOn });
552 const failing = harness({
553 signIns: { "github.com": session() },
554 handle: () => ({ status: 502, body: {} }),
555 });
556 return Effect.gen(function* () {
557 expect(
558 yield* Effect.flatMap(Effect.service(GitHubAppAccess.GitHubAppAccess), (access) =>
559 access.reach("github.com", "acme/one"),
560 ).pipe(Effect.provide(signedOut.layer)),
561 ).toBe("signed-out");
562 const answers = yield* Effect.gen(function* () {
563 const access = yield* GitHubAppAccess.GitHubAppAccess;
564 return [
565 yield* access.reach("github.com", "acme/one"),
566 yield* access.reach("github.com", "acme/two"),
567 ];
568 }).pipe(Effect.provide(failing.layer));
569 expect(answers).toEqual(["covered", "covered"]);
570 // A failed read is kept briefly instead of asked again per request.
571 expect(failing.requests).toHaveLength(1);
572 });
573 });
574
575 it.effect("gives work on a repository the app cannot reach the user's credential", () => {
576 const { layer } = harness({ signIns: { "github.com": session() }, handle: installedOn });
577 return Effect.gen(function* () {
578 const access = yield* GitHubAppAccess.GitHubAppAccess;
579 const tokenFor = (repository: string) =>
580 access
581 .credentialFor("github.com", repository)
582 .pipe(Effect.map((held) => Redacted.value(held.token)));
583 expect(yield* tokenFor("pingdotgg/t3code")).toBe("ghu_current");
584 expect(yield* tokenFor("someone/else")).toBe("gh-token");
585 }).pipe(Effect.provide(layer));
586 });
587
588 it.effect("pins the user's credential while the app's reach is unknown", () => {
589 const failing = (sent: Sent): Reply =>
590 sent.path.startsWith("/user/installations") ? { status: 502, body: {} } : { body: {} };
591 const withGh = harness({ signIns: { "github.com": session() }, handle: failing });
592 const appOnly = harness({
593 signIns: { "github.com": session() },
594 ghSignedIn: false,
595 handle: failing,
596 });
597 const tokenFor = Effect.flatMap(Effect.service(GitHubAppAccess.GitHubAppAccess), (access) =>
598 access
599 .credentialFor("github.com", "pingdotgg/t3code")
600 .pipe(Effect.map((held) => Redacted.value(held.token))),
601 );
602 return Effect.gen(function* () {
603 expect(yield* tokenFor.pipe(Effect.provide(withGh.layer))).toBe("gh-token");
604 expect(yield* tokenFor.pipe(Effect.provide(appOnly.layer))).toBe("ghu_current");
605 });
606 });
607
608 it.effect("names the account the app sign-in acts as", () => {
609 const { layer } = harness({
610 signIns: { "github.com": session() },
611 tokens: { "github.com": "saved-pat" },
612 handle: (sent) => ({ body: { login: sent.token === "ghu_current" ? "octocat" : "other" } }),
613 });
614 return Effect.gen(function* () {
615 expect(yield* (yield* GitHubAppAccess.GitHubAppAccess).viewer("github.com")).toBe("octocat");
616 }).pipe(Effect.provide(layer));
617 });
618});