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

platform.test.ts

436 lines14.0 KB

1// @vitest-environment jsdom
2import {
3 AuthStandardClientScopes,
4 EnvironmentId,
5 PRIMARY_LOCAL_ENVIRONMENT_ID,
6 type DesktopBridge,
7 type DesktopSshEnvironmentTarget,
8} from "@t3tools/contracts";
9import { afterEach, describe, expect, it, vi } from "@effect/vitest";
10import * as Effect from "effect/Effect";
11import * as Stream from "effect/Stream";
12import { PlatformConnectionSource } from "@t3tools/client-runtime/platform";
13import {
14 ConnectionBlockedError,
15 ConnectionTransientError,
16} from "@t3tools/client-runtime/connection";
17​
18import {
19 canRetainCachedPlatformRegistrationAfterRefreshFailure,
20 canReuseCachedPlatformRegistration,
21 isRejectedBootstrapCredentialError,
22 isRejectedSecondaryBootstrap,
23 nextRejectedSecondaryBootstrap,
24 layerPlatformConnectionSource,
25 primaryRegistrationToRetainAfterTopologyRead,
26 prepareDesktopSshEnvironment,
27 provisionDesktopSshEnvironment,
28 readPrimaryEnvironmentTargetResult,
29 secondaryRegistrationsToRetainAfterTopologyRead,
30 secondaryBearerExpiresAtEpochMs,
31 secondaryBearerRefreshAtEpochMs,
32} from "./platform.ts";
33​
34const TARGET: DesktopSshEnvironmentTarget = {
35 alias: "devbox",
36 hostname: "devbox.example.test",
37 username: "developer",
38 port: 22,
39};
40​
41function makeBridge(
42 calls: string[],
43 options?: {
44 readonly failDescriptor?: boolean;
45 readonly savedTokenRejected?: boolean;
46 readonly savedTokenPermissions?: ReadonlyArray<string>;
47 },
48): DesktopBridge {
49 return {
50 ensureSshEnvironment: async (
51 target: DesktopSshEnvironmentTarget,
52 ensureOptions?: { issuePairingToken?: boolean },
53 ) => {
54 calls.push("ensure");
55 return {
56 target,
57 httpBaseUrl: "http://127.0.0.1:3201/",
58 wsBaseUrl: "ws://127.0.0.1:3201/",
59 pairingToken: ensureOptions?.issuePairingToken === true ? "pairing-token" : null,
60 };
61 },
62 fetchSshSessionState: async () => {
63 calls.push("session");
64 return {
65 authenticated: options?.savedTokenRejected !== true,
66 permissions: options?.savedTokenPermissions ?? AuthStandardClientScopes,
67 };
68 },
69 fetchSshEnvironmentDescriptor: async () => {
70 calls.push("descriptor");
71 if (options?.failDescriptor === true) {
72 throw new Error("descriptor unavailable");
73 }
74 return {
75 environmentId: EnvironmentId.make("environment-ssh"),
76 label: "SSH environment",
77 platform: {
78 os: "linux",
79 arch: "x64",
80 },
81 serverVersion: "0.0.0-test",
82 capabilities: {
83 repositoryIdentity: true,
84 },
85 };
86 },
87 bootstrapSshBearerSession: async () => {
88 calls.push("token");
89 return {
90 access_token: "bearer-token",
91 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
92 token_type: "Bearer",
93 expires_in: 3_600,
94 scope: AuthStandardClientScopes.join(" "),
95 };
96 },
97 } as unknown as DesktopBridge;
99​
100describe("desktop SSH pairing", () => {
101 it.effect("fetches the descriptor before consuming the one-time credential", () =>
102 Effect.gen(function* () {
103 const calls: string[] = [];
104​
105 const provisioned = yield* provisionDesktopSshEnvironment(makeBridge(calls), TARGET);
106​
107 expect(provisioned.environmentId).toBe(EnvironmentId.make("environment-ssh"));
108 expect(calls).toEqual(["ensure", "descriptor", "token"]);
109 }),
110 );
111​
112 it.effect("does not consume the credential when adding a route to a different machine", () =>
113 Effect.gen(function* () {
114 const calls: string[] = [];
115​
116 const error = yield* provisionDesktopSshEnvironment(
117 makeBridge(calls),
118 TARGET,
119 EnvironmentId.make("some-other-machine"),
120 ).pipe(Effect.flip);
121​
122 expect(error).toMatchObject({ reason: "configuration" });
123 expect(calls).toEqual(["ensure", "descriptor"]);
124 }),
125 );
126​
127 it.effect("does not consume the credential when descriptor discovery fails", () =>
128 Effect.gen(function* () {
129 const calls: string[] = [];
130​
131 yield* provisionDesktopSshEnvironment(
132 makeBridge(calls, { failDescriptor: true }),
133 TARGET,
134 ).pipe(Effect.flip);
135​
136 expect(calls).toEqual(["ensure", "descriptor"]);
137 }),
138 );
139​
140 it.effect("reconnects with the saved token while it holds every standard scope", () =>
141 Effect.gen(function* () {
142 const calls: string[] = [];
143​
144 const prepared = yield* prepareDesktopSshEnvironment(makeBridge(calls), {
145 target: TARGET,
146 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
147 bearerToken: "saved-token",
148 });
149​
150 expect(prepared.bearerToken).toBe("saved-token");
151 expect(calls).toEqual(["ensure", "descriptor", "session"]);
152 }),
153 );
154​
155 it.effect("pairs again when the host no longer accepts the saved token", () =>
156 Effect.gen(function* () {
157 const calls: string[] = [];
158​
159 const prepared = yield* prepareDesktopSshEnvironment(
160 makeBridge(calls, { savedTokenRejected: true }),
161 {
162 target: TARGET,
163 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
164 bearerToken: "saved-token",
165 },
166 );
167​
168 expect(prepared.bearerToken).toBe("bearer-token");
169 expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);
170 }),
171 );
172​
173 it.effect("pairs again when the saved token predates a standard scope", () =>
174 Effect.gen(function* () {
175 const calls: string[] = [];
176​
177 const prepared = yield* prepareDesktopSshEnvironment(
178 makeBridge(calls, {
179 savedTokenPermissions: ["orchestration:read", "orchestration:operate"],
180 }),
181 {
182 target: TARGET,
183 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
184 bearerToken: "saved-token",
185 },
186 );
187​
188 expect(prepared.bearerToken).toBe("bearer-token");
189 expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);
190 }),
191 );
192​
193 it.effect("stops before sending the saved token or pairing on a different machine", () =>
194 Effect.gen(function* () {
195 const calls: string[] = [];
196​
197 const error = yield* prepareDesktopSshEnvironment(makeBridge(calls), {
198 target: TARGET,
199 expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
200 bearerToken: "saved-token",
201 }).pipe(Effect.flip);
202​
203 expect(error).toMatchObject({ reason: "configuration" });
204 expect(calls).toEqual(["ensure", "descriptor"]);
205 }),
206 );
207});
208​
209describe("desktop-local bearer cache", () => {
210 const registration = {} as never;
211​
212 it("refreshes a secondary bearer before it expires", () => {
213 const issuedAtEpochMs = 10_000;
214 const refreshAtEpochMs = secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, 60);
215 const expiresAtEpochMs = secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, 60);
216 const cached = {
217 expiresAtEpochMs,
218 signature: "secondary-signature",
219 registration,
220 refreshAtEpochMs,
221 };
222​
223 expect(refreshAtEpochMs).toBe(65_000);
224 expect(canReuseCachedPlatformRegistration(cached, cached.signature, 64_999)).toBe(true);
225 expect(canReuseCachedPlatformRegistration(cached, cached.signature, 65_000)).toBe(false);
226 expect(
227 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, cached.signature, 69_999),
228 ).toBe(true);
229 expect(
230 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, cached.signature, 70_000),
231 ).toBe(false);
232 });
233​
234 it("does not cache credentials whose lifetime is shorter than the refresh skew", () => {
235 const refreshAtEpochMs = secondaryBearerRefreshAtEpochMs(10_000, 3);
236 const cached = {
237 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(10_000, 3),
238 signature: "secondary-signature",
239 registration,
240 refreshAtEpochMs,
241 };
242​
243 expect(refreshAtEpochMs).toBe(10_000);
244 expect(canReuseCachedPlatformRegistration(cached, cached.signature, 10_000)).toBe(false);
245 });
246​
247 it("retains only unexpired secondaries after a topology read failure", () => {
248 const valid = {
249 expiresAtEpochMs: 20_000,
250 signature: "valid-secondary",
251 registration,
252 refreshAtEpochMs: 15_000,
253 };
254 const previous = new Map([
255 ["valid-secondary", valid],
256 [
257 "expired-secondary",
258 {
259 expiresAtEpochMs: 10_000,
260 signature: "expired-secondary",
261 registration,
262 refreshAtEpochMs: 5_000,
263 },
264 ],
265 ]);
266​
267 expect(
268 secondaryRegistrationsToRetainAfterTopologyRead(
269 previous,
270 { _tag: "Failure", cause: new Error("IPC unavailable") },
271 10_000,
272 ),
273 ).toEqual(new Map([["valid-secondary", valid]]));
274 });
275​
276 it("treats a successful empty topology as authoritative removal", () => {
277 const previous = new Map([
278 [
279 "secondary",
280 {
281 expiresAtEpochMs: 20_000,
282 signature: "secondary",
283 registration,
284 refreshAtEpochMs: 15_000,
285 },
286 ],
287 ]);
288​
289 expect(
290 secondaryRegistrationsToRetainAfterTopologyRead(
291 previous,
292 { _tag: "Success", bootstraps: [] },
293 10_000,
294 ),
295 ).toEqual(new Map());
296 });
297});
298​
299describe("rejected desktop-local bootstrap tokens", () => {
300 it("backs off on a rejected signature and retries it on a growing, capped delay", () => {
301 const signature = "http://a|ws://a|old-token";
302 const first = nextRejectedSecondaryBootstrap(undefined, signature, 0);
303​
304 expect(isRejectedSecondaryBootstrap(first, signature, 59_999)).toBe(true);
305 expect(isRejectedSecondaryBootstrap(first, signature, 60_000)).toBe(false);
306​
307 const second = nextRejectedSecondaryBootstrap(first, signature, 60_000);
308 expect(second.retryAtEpochMs).toBe(180_000);
309​
310 let backoff = second;
311 for (let attempt = 0; attempt < 10; attempt += 1) {
312 backoff = nextRejectedSecondaryBootstrap(backoff, signature, 0);
313 }
314 expect(backoff.delayMs).toBe(30 * 60_000);
315 });
316​
317 it("retries at once when the token or endpoint changes", () => {
318 const rejected = nextRejectedSecondaryBootstrap(undefined, "http://a|ws://a|old-token", 0);
319​
320 expect(isRejectedSecondaryBootstrap(rejected, "http://a|ws://a|new-token", 1)).toBe(false);
321 expect(isRejectedSecondaryBootstrap(rejected, "http://b|ws://b|old-token", 1)).toBe(false);
322 expect(isRejectedSecondaryBootstrap(undefined, "http://a|ws://a|old-token", 1)).toBe(false);
323 expect(nextRejectedSecondaryBootstrap(rejected, "http://a|ws://a|new-token", 1).delayMs).toBe(
324 60_000,
325 );
326 });
327​
328 it("treats only authentication rejections as a dead credential", () => {
329 expect(
330 isRejectedBootstrapCredentialError(
331 new ConnectionBlockedError({ reason: "authentication", detail: "invalid" }),
332 ),
333 ).toBe(true);
334 expect(
335 isRejectedBootstrapCredentialError(
336 new ConnectionTransientError({ reason: "endpoint-unavailable", detail: "booting" }),
337 ),
338 ).toBe(false);
339 });
340});
341​
342describe("desktop-local bearer cache across token changes", () => {
343 it("keeps a live bearer when only the bootstrap token rotates", () => {
344 const cached = {
345 signature: "http://a|ws://a",
346 registration: {} as never,
347 expiresAtEpochMs: 20_000,
348 refreshAtEpochMs: 15_000,
349 };
350​
351 expect(canReuseCachedPlatformRegistration(cached, "http://a|ws://a", 10_000)).toBe(true);
352 expect(
353 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, "http://a|ws://a", 16_000),
354 ).toBe(true);
355 expect(canReuseCachedPlatformRegistration(cached, "http://b|ws://b", 10_000)).toBe(false);
356 });
357});
358​
359describe("primary topology cache", () => {
360 const registration = {} as never;
361 const cached = {
362 signature: "primary|http://127.0.0.1:3773/|ws://127.0.0.1:3773/",
363 registration,
364 };
365 const previous = new Map([[PRIMARY_LOCAL_ENVIRONMENT_ID, cached]]);
366​
367 it("captures synchronous primary target read failures", () => {
368 const cause = new Error("invalid primary target");
369​
370 expect(
371 readPrimaryEnvironmentTargetResult(() => {
372 throw cause;
373 }),
374 ).toEqual({ _tag: "Failure", cause });
375 });
376​
377 it("retains the cached primary after a transient topology read failure", () => {
378 expect(
379 primaryRegistrationToRetainAfterTopologyRead(previous, {
380 _tag: "Failure",
381 cause: new Error("IPC unavailable"),
382 }),
383 ).toBe(cached);
384 });
385​
386 it("treats a successful primary absence as authoritative removal", () => {
387 expect(
388 primaryRegistrationToRetainAfterTopologyRead(previous, {
389 _tag: "Success",
390 target: null,
391 }),
392 ).toBeUndefined();
393 });
394});
395​
396describe("cached primary discovery", () => {
397 afterEach(() => {
398 localStorage.clear();
399 vi.unstubAllGlobals();
400 });
401​
402 it.live("retains the early primary through failed discovery and retries discovery", () => {
403 const target = {
404 _tag: "PrimaryConnectionTarget",
405 environmentId: EnvironmentId.make("cached-primary"),
406 label: "Cached primary",
407 httpBaseUrl: `${window.location.origin}/`,
408 wsBaseUrl: `${window.location.origin.replace("http", "ws")}/`,
409 };
410 localStorage.setItem("t3code:desktop-primary-target:v1", JSON.stringify(target));
411 const fetchMock = vi
412 .fn()
413 .mockResolvedValueOnce(new Response(null, { status: 503 }))
414 .mockImplementation(() =>
415 Promise.resolve(
416 Response.json({
417 environmentId: target.environmentId,
418 label: "Discovered primary",
419 platform: { os: "linux", arch: "x64" },
420 serverVersion: "0.0.0-test",
421 capabilities: { repositoryIdentity: true },
422 }),
423 ),
424 );
425 vi.stubGlobal("fetch", fetchMock);
426​
427 return Effect.gen(function* () {
428 const source = yield* PlatformConnectionSource.PlatformConnectionSource;
429 const emissions = yield* source.registrations.pipe(Stream.take(3), Stream.runCollect);
430 expect(
431 emissions.map((registrations) => registrations.map((entry) => entry.target.label)),
432 ).toEqual([["Cached primary"], ["Cached primary"], ["Discovered primary"]]);
433 expect(fetchMock).toHaveBeenCalledTimes(2);
434 }).pipe(Effect.provide(layerPlatformConnectionSource));
435 });
436});