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

GitHubAppSignIn.test.ts

593 lines24.4 KB

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