Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as SecureRandom from "effect/crypto/SecureRandom";
8import * as SqlClient from "effect/sql/SqlClient";
9import { IssueTrackerKind, type ProjectId } from "@t3tools/contracts";
10import {
11 IssueTrackerError,
12 type StandaloneIssueTrackerApi,
13} from "@t3tools/source-control-core/server/IssueTracker";
14
15import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
17import * as SqlitePersistence from "../persistence/Sqlite.ts";
18import * as IssueTrackerConnections from "./IssueTrackerConnections.ts";
19import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
20
21const LINEAR = IssueTrackerKind.make("linear");
22
23describe("IssueTrackerConnections", () => {
24 it.effect("keeps each account's key and bindings apart, and no key past its account", () => {
25 const secrets = new Map<string, string>();
26 const probing = Deferred.makeUnsafe<void>();
27 const released = Deferred.makeUnsafe<void>();
28 let random = 0;
29 const tracker = {
30 kind: LINEAR,
31 standalone: {
32 tracker: LINEAR,
33 host: "linear.app",
34 credential: { label: "API key", helpUrl: null },
35 },
36 probeCredential: ({ token }: { readonly token: string }) =>
37 token === "bad"
38 ? Effect.fail(
39 new IssueTrackerError({
40 tracker: LINEAR,
41 operation: "viewer",
42 reason: "unauthenticated",
43 detail: "Linear refused the key.",
44 }),
45 )
46 : Effect.as(
47 token === "slow"
48 ? Effect.andThen(Deferred.succeed(probing, undefined), Deferred.await(released))
49 : Effect.void,
50 { account: `user-${token}`, scopes: [] },
51 ),
52 } as unknown as StandaloneIssueTrackerApi;
53 const layer = IssueTrackerConnections.layer.pipe(
54 Layer.provideMerge(IssueTrackerBindings.layer),
55 Layer.provideMerge(
56 Layer.mergeAll(
57 SqlitePersistence.layerMemory,
58 Layer.succeed(
59 IssueTrackerRegistry.IssueTrackerRegistry,
60 IssueTrackerRegistry.fromTrackers([tracker]),
61 ),
62 Layer.mock(ServerSecretStore.ServerSecretStore)({
63 get: (name) =>
64 Effect.succeed(
65 Option.map(Option.fromNullishOr(secrets.get(name)), (value) =>
66 new TextEncoder().encode(value),
67 ),
68 ),
69 set: (name, value) =>
70 Effect.sync(() => void secrets.set(name, new TextDecoder().decode(value))),
71 remove: (name) => Effect.sync(() => void secrets.delete(name)),
72 }),
73 Layer.succeed(
74 SecureRandom.SecureRandom,
75 SecureRandom.make((size) => new Uint8Array(size).fill(++random)),
76 ),
77 ),
78 ),
79 );
80 return Effect.gen(function* () {
81 const connections = yield* IssueTrackerConnections.IssueTrackerConnections;
82 yield* connections.connect({ tracker: LINEAR, token: "work" });
83 const { accountId } = yield* connections.connect({
84 tracker: LINEAR,
85 token: "home",
86 addAccount: true,
87 });
88
89 // The first account keeps the name it was saved under before accounts existed.
90 expect(Object.fromEntries(secrets)).toEqual({
91 "issue-tracker-bGluZWFy-token": "work",
92 [`issue-tracker-bGluZWFy-account-${accountId}-token`]: "home",
93 });
94 yield* connections.bindProject({
95 projectId: "work" as ProjectId,
96 binding: { tracker: LINEAR, scope: "ENG" },
97 });
98 yield* connections.bindProject({
99 projectId: "home" as ProjectId,
100 binding: { tracker: LINEAR, accountId, scope: "ENG" },
101 });
102 // Older clients read `bindings` as the first account's, so the second one's are apart.
103 expect(yield* connections.list).toMatchObject({
104 accounts: [{ accountId, account: "user-home" }],
105 bindings: { work: { tracker: LINEAR, scope: "ENG" } },
106 accountBindings: { home: { tracker: LINEAR, accountId, scope: "ENG" } },
107 });
108 // An older client offers the added account's project as unbound; its unbind leaves it.
109 yield* connections.bindProject({ projectId: "home" as ProjectId, binding: null });
110 expect((yield* connections.list).accountBindings).toHaveProperty("home");
111 yield* Effect.flip(connections.connect({ tracker: LINEAR, token: "bad", addAccount: true }));
112 expect(
113 yield* Effect.flip(
114 connections.connect({ tracker: LINEAR, token: "home", addAccount: true }),
115 ),
116 ).toMatchObject({ detail: "This credential is already connected as another account." });
117 expect(secrets.size).toBe(2);
118
119 // A removal does not wait on a replacement key's probe, and the replacement then finds its
120 // account gone instead of storing a key for it.
121 const replacing = yield* connections
122 .connect({ tracker: LINEAR, accountId, token: "slow" })
123 .pipe(Effect.forkChild({ startImmediately: true }));
124 yield* Deferred.await(probing);
125 yield* connections.connect({ tracker: LINEAR, accountId, token: null });
126 yield* Deferred.succeed(released, undefined);
127 expect(yield* Effect.flip(Fiber.join(replacing))).toMatchObject({
128 detail: "This account is not saved on the server.",
129 });
130 expect([...secrets.keys()]).toEqual(["issue-tracker-bGluZWFy-token"]);
131 const after = yield* connections.list;
132 expect([after.accounts, after.accountBindings]).toEqual([[], {}]);
133 expect(
134 yield* Effect.flip(
135 connections.bindProject({
136 projectId: "home" as ProjectId,
137 binding: { tracker: LINEAR, accountId, scope: "ENG" },
138 }),
139 ),
140 ).toMatchObject({ detail: "This account is not saved on the server." });
141
142 // An account that cannot be saved takes its new key with it.
143 yield* (yield* SqlClient.SqlClient)`DROP TABLE issue_tracker_accounts`;
144 yield* Effect.flip(connections.connect({ tracker: LINEAR, token: "home", addAccount: true }));
145 expect(secrets.size).toBe(1);
146 }).pipe(Effect.provide(layer));
147 });
148});