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