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

PairingGrantStore.test.ts

237 lines9.3 KB

1import { AuthStandardClientScopes } from "@t3tools/contracts";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { expect, it } from "@effect/vitest";
4import * as Crypto from "effect/Crypto";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Stream from "effect/Stream";
9import * as Queue from "effect/Queue";
10import * as TestClock from "effect/testing/TestClock";
11import {
12 DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
13 currentDesktopBootstrapToken,
14} from "@t3tools/shared/desktopBootstrapToken";
15​
16import * as ServerConfig from "../config.ts";
17import * as SqlitePersistence from "../persistence/Sqlite.ts";
18import * as PairingGrantStore from "./PairingGrantStore.ts";
19​
20const layerServerConfig = (
21 overrides?: Partial<
22 Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken" | "desktopBootstrapSecret">
23 >,
24) =>
25 Layer.effect(
26 ServerConfig.ServerConfig,
27 Effect.gen(function* () {
28 const config = yield* ServerConfig.ServerConfig;
29 return {
30 ...config,
31 ...overrides,
32 } satisfies ServerConfig.ServerConfig["Service"];
33 }),
34 ).pipe(
35 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
36 );
37​
38const layerPairingGrantStore = (
39 overrides?: Partial<
40 Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken" | "desktopBootstrapSecret">
41 >,
42) =>
43 PairingGrantStore.layer.pipe(
44 Layer.provide(SqlitePersistence.layerMemory),
45 Layer.provide(layerServerConfig(overrides)),
46 );
47​
48it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
49 it.effect("accepts lowercase one-time tokens exactly once", () =>
50 Effect.gen(function* () {
51 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
52 const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
53 const first = yield* bootstrapCredentials.consume(issued.credential.toLowerCase());
54 const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
55​
56 expect(first.method).toBe("one-time-token");
57 expect(first.scopes).toEqual(AuthStandardClientScopes);
58 expect(first.subject).toBe("one-time-token");
59 expect(first.label).toBe("Julius iPhone");
60 expect(issued.label).toBe("Julius iPhone");
61 expect(second._tag).toBe("UnknownBootstrapCredentialError");
62 expect(second.message).toContain("Unknown bootstrap credential");
63 }).pipe(
64 Effect.provide(layerPairingGrantStore()),
65 Effect.provideServiceEffect(
66 Crypto.Crypto,
67 Effect.map(Crypto.Crypto, (crypto) => ({
68 ...crypto,
69 randomBytes: (size) => Effect.succeed(new Uint8Array(size).fill(8)),
70 })),
71 ),
72 ),
73 );
74​
75 it.effect("atomically consumes a one-time token when multiple requests race", () =>
76 Effect.gen(function* () {
77 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
78 const token = yield* bootstrapCredentials.issueOneTimeToken();
79 const results = yield* Effect.all(
80 Array.from({ length: 8 }, () =>
81 Effect.result(
82 bootstrapCredentials.consume(token.credential, {
83 requestedScopes: ["orchestration:read"],
84 }),
85 ),
86 ),
87 {
88 concurrency: "unbounded",
89 },
90 );
91​
92 const successes = results.filter((result) => result._tag === "Success");
93 const failures = results.filter((result) => result._tag === "Failure");
94​
95 expect(successes).toHaveLength(1);
96 expect(failures).toHaveLength(7);
97 for (const failure of failures) {
98 expect(failure.failure._tag).toBe("UnknownBootstrapCredentialError");
99 expect(failure.failure.message).toContain("Unknown bootstrap credential");
100 }
101 }).pipe(Effect.provide(layerPairingGrantStore())),
102 );
103​
104 it.effect("requires the bound proof key thumbprint when present", () =>
105 Effect.gen(function* () {
106 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
107 const token = yield* bootstrapCredentials.issueOneTimeToken({
108 proofKeyThumbprint: "client-proof-key-thumbprint",
109 scopes: ["orchestration:read"],
110 });
111​
112 const missing = yield* Effect.flip(bootstrapCredentials.consume(token.credential));
113 const wrong = yield* Effect.flip(
114 bootstrapCredentials.consume(token.credential, {
115 proofKeyThumbprint: "other-proof-key-thumbprint",
116 requestedScopes: ["access:write"],
117 }),
118 );
119 const forbiddenScope = yield* Effect.flip(
120 bootstrapCredentials.consume(token.credential, {
121 proofKeyThumbprint: "client-proof-key-thumbprint",
122 requestedScopes: ["access:write"],
123 }),
124 );
125 const consumed = yield* bootstrapCredentials.consume(token.credential, {
126 proofKeyThumbprint: "client-proof-key-thumbprint",
127 requestedScopes: ["orchestration:read"],
128 });
129​
130 expect(missing.message).toContain("proof key mismatch");
131 expect(wrong.message).toContain("proof key mismatch");
132 expect(forbiddenScope._tag).toBe("BootstrapCredentialScopeNotGrantedError");
133 expect(consumed.proofKeyThumbprint).toBe("client-proof-key-thumbprint");
134 }).pipe(Effect.provide(layerPairingGrantStore())),
135 );
136​
137 it.effect("matches a seeded desktop bootstrap credential exactly", () =>
138 Effect.gen(function* () {
139 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
140 const exact = yield* bootstrapCredentials.consume("abcdefghjkmn");
141 const otherCase = yield* Effect.flip(bootstrapCredentials.consume("ABCDEFGHJKMN"));
142​
143 expect(exact.method).toBe("desktop-bootstrap");
144 expect(otherCase._tag).toBe("UnknownBootstrapCredentialError");
145 }).pipe(
146 Effect.provide(
147 layerPairingGrantStore({
148 desktopBootstrapToken: "abcdefghjkmn",
149 }),
150 ),
151 ),
152 );
153​
154 it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
155 Effect.gen(function* () {
156 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
157​
158 yield* TestClock.adjust(Duration.hours(12));
159 const stillValid = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
160 expect(stillValid.method).toBe("desktop-bootstrap");
161​
162 yield* TestClock.adjust(Duration.hours(13));
163 const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
164​
165 expect(expired._tag).toBe("ExpiredBootstrapCredentialError");
166 expect(expired.message).toContain("Bootstrap credential expired");
167 }).pipe(
168 Effect.provide(
169 Layer.merge(
170 layerPairingGrantStore({
171 desktopBootstrapToken: "desktop-bootstrap-token",
172 }),
173 TestClock.layer(),
174 ),
175 ),
176 ),
177 );
178​
179 it.effect("accepts rotating desktop bootstrap tokens derived from the desktop secret", () =>
180 Effect.gen(function* () {
181 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
182 const window = DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS;
183​
184 yield* TestClock.adjust(Duration.days(5));
185 const now = 5 * 24 * 60 * 60 * 1000;
186 const current = yield* bootstrapCredentials.consume(
187 currentDesktopBootstrapToken("desktop-secret", now),
188 );
189 expect(current.method).toBe("desktop-bootstrap");
190​
191 const stale = yield* Effect.flip(
192 bootstrapCredentials.consume(
193 currentDesktopBootstrapToken("desktop-secret", now - 2 * window),
194 ),
195 );
196 expect(stale._tag).toBe("UnknownBootstrapCredentialError");
197​
198 const launch = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
199 expect(launch._tag).toBe("UnknownBootstrapCredentialError");
200 }).pipe(
201 Effect.provide(
202 Layer.merge(
203 layerPairingGrantStore({
204 desktopBootstrapToken: "desktop-bootstrap-token",
205 desktopBootstrapSecret: "desktop-secret",
206 }),
207 TestClock.layer(),
208 ),
209 ),
210 ),
211 );
212​
213 it.effect("keeps credentials out of pairing lists and change events", () =>
214 Effect.gen(function* () {
215 const grants = yield* PairingGrantStore.PairingGrantStore;
216 const changes = yield* Queue.unbounded<PairingGrantStore.BootstrapCredentialChange>();
217 yield* grants.streamChanges.pipe(
218 Stream.runForEach((change) => Queue.offer(changes, change)),
219 Effect.forkScoped({ startImmediately: true }),
220 );
221 for (const input of [{}, { label: "Synthetic phone" }]) {
222 const issued = yield* grants.issueOneTimeToken(input);
223 const change = yield* Queue.take(changes);
224 expect(change?.type).toBe("pairingLinkUpserted");
225 if (change?.type !== "pairingLinkUpserted")
226 throw new Error("Expected a pairing link update");
227 expect(change.pairingLink.id).toBe(issued.id);
228 expect(change.pairingLink).not.toHaveProperty("credential");
229 const listed = (yield* grants.listActive()).find((link) => link.id === issued.id);
230 expect(listed).toEqual(change.pairingLink);
231 const consumed = yield* grants.consume(issued.credential);
232 expect(consumed.scopes).toEqual(change.pairingLink.scopes);
233 expect(yield* Queue.take(changes)).toEqual({ type: "pairingLinkRemoved", id: issued.id });
234 }
235 }).pipe(Effect.scoped, Effect.provide(layerPairingGrantStore())),
236 );
237});