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

platform.test.ts

500 lines16.8 KB

1import {
2 AuthStandardClientScopes,
3 EnvironmentId,
4 PRIMARY_LOCAL_ENVIRONMENT_ID,
5 type DesktopBridge,
6 type DesktopSshEnvironmentBootstrap,
7 type DesktopSshEnvironmentTarget,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "@effect/vitest";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import { afterEach, vi } from "vite-plus/test";
13import { ClientCapabilities } from "@t3tools/client-runtime/platform";
14import {
15 ConnectionBlockedError,
16 ConnectionTransientError,
17} from "@t3tools/client-runtime/connection";
18​
19import {
20 canRetainCachedPlatformRegistrationAfterRefreshFailure,
21 canReuseCachedPlatformRegistration,
22 layer,
23 isRejectedBootstrapCredentialError,
24 isRejectedSecondaryBootstrap,
25 nextRejectedSecondaryBootstrap,
26 primaryRegistrationToRetainAfterTopologyRead,
27 prepareDesktopSshEnvironment,
28 provisionDesktopSshEnvironment,
29 secondaryRegistrationsToRetainAfterTopologyRead,
30} from "./platform.ts";
31import { APP_VERSION } from "../branding.ts";
32​
33const TARGET: DesktopSshEnvironmentTarget = {
34 alias: "devbox",
35 hostname: "devbox.example.test",
36 username: "developer",
37 port: 22,
38};
39​
40const SSH_BOOTSTRAP = {
41 target: TARGET,
42 httpBaseUrl: "http://127.0.0.1:3201/",
43 wsBaseUrl: "ws://127.0.0.1:3201/",
44 pairingToken: "abandoned-token",
45};
46​
47function pendingSetup() {
48 let resolve!: (bootstrap: DesktopSshEnvironmentBootstrap) => void;
49 let reject!: (cause: unknown) => void;
50 const promise = new Promise<DesktopSshEnvironmentBootstrap>((onResolve, onReject) => {
51 resolve = onResolve;
52 reject = onReject;
53 });
54 return { promise, resolve, reject };
56​
57afterEach(() => {
58 vi.unstubAllGlobals();
59 vi.restoreAllMocks();
60});
61​
62function makeBridge(
63 calls: string[],
64 options?: {
65 readonly failDescriptor?: boolean;
66 readonly savedTokenRejected?: boolean;
67 readonly savedTokenPermissions?: ReadonlyArray<string>;
68 },
69): DesktopBridge {
70 return {
71 getClientPlatform: () => "linux",
72 getLocalEnvironmentEnabled: () => true,
73 ensureSshEnvironment: async (
74 target: DesktopSshEnvironmentTarget,
75 ensureOptions?: { issuePairingToken?: boolean; claimTunnel?: boolean },
76 ) => {
77 calls.push("ensure");
78 return {
79 target,
80 httpBaseUrl: "http://127.0.0.1:3201/",
81 wsBaseUrl: "ws://127.0.0.1:3201/",
82 pairingToken: ensureOptions?.issuePairingToken === true ? "pairing-token" : null,
83 ...(ensureOptions?.claimTunnel === true ? { tunnelClaim: "claim" } : {}),
84 };
85 },
86 releaseSshTunnelClaim: async (claim: string) => {
87 calls.push(`release:${claim}`);
88 },
89 disconnectSshEnvironment: async () => {
90 calls.push("disconnect");
91 },
92 fetchSshSessionState: async () => {
93 calls.push("session");
94 return {
95 authenticated: options?.savedTokenRejected !== true,
96 permissions: options?.savedTokenPermissions ?? AuthStandardClientScopes,
97 };
98 },
99 fetchSshEnvironmentDescriptor: async () => {
100 calls.push("descriptor");
101 if (options?.failDescriptor === true) {
102 throw new Error("descriptor unavailable");
103 }
104 return {
105 environmentId: EnvironmentId.make("environment-ssh"),
106 label: "SSH environment",
107 platform: {
108 os: "linux",
109 arch: "x64",
110 },
111 serverVersion: "0.0.0-test",
112 capabilities: {
113 repositoryIdentity: true,
114 },
115 };
116 },
117 bootstrapSshBearerSession: async () => {
118 calls.push("token");
119 return {
120 access_token: "bearer-token",
121 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
122 token_type: "Bearer",
123 expires_in: 3_600,
124 scope: AuthStandardClientScopes.join(" "),
125 };
126 },
127 } as unknown as DesktopBridge;
129​
130describe("desktop SSH pairing", () => {
131 it.effect(
132 "releases the tunnel without consuming the credential when adding a route to a different machine",
133 () =>
134 Effect.gen(function* () {
135 const calls: string[] = [];
136​
137 const error = yield* provisionDesktopSshEnvironment(
138 makeBridge(calls),
139 TARGET,
140 EnvironmentId.make("some-other-machine"),
141 true,
142 ).pipe(Effect.flip);
143​
144 expect(error).toMatchObject({ reason: "configuration" });
145 expect(calls).toEqual(["ensure", "descriptor", "release:claim"]);
146 }),
147 );
148​
149 it.effect("releases a tunnel returned after onboarding was interrupted", () =>
150 Effect.gen(function* () {
151 const bridge = makeBridge([]);
152 const setup = pendingSetup();
153 vi.spyOn(bridge, "ensureSshEnvironment").mockReturnValueOnce(setup.promise);
154 const finished = Promise.withResolvers<string>();
155 vi.spyOn(bridge, "releaseSshTunnelClaim").mockImplementation(async (claim) => {
156 finished.resolve(claim);
157 });
158​
159 const pending = yield* Effect.forkChild(
160 provisionDesktopSshEnvironment(bridge, TARGET, undefined, true),
161 { startImmediately: true },
162 );
163 yield* Fiber.interrupt(pending);
164 setup.resolve({ ...SSH_BOOTSTRAP, tunnelClaim: "late-claim" });
165​
166 expect(yield* Effect.promise(() => finished.promise)).toBe("late-claim");
167 }),
168 );
169​
170 it.effect.each(["fetchSshEnvironmentDescriptor", "bootstrapSshBearerSession"] as const)(
171 "releases the tunnel when interrupted during %s",
172 (operation) =>
173 Effect.gen(function* () {
174 const calls: string[] = [];
175 const bridge = makeBridge(calls);
176 const reached = Promise.withResolvers<void>();
177 vi.spyOn(bridge, operation).mockImplementation(() => {
178 reached.resolve();
179 return new Promise<never>(() => {});
180 });
181 const pending = yield* Effect.forkChild(
182 provisionDesktopSshEnvironment(bridge, TARGET, undefined, true),
183 );
184 yield* Effect.promise(() => reached.promise);
185 yield* Fiber.interrupt(pending);
186 expect(calls.at(-1)).toBe("release:claim");
187 }),
188 );
189​
190 it.effect("exchanges one setup credential after repeated interrupted provisions", () =>
191 Effect.gen(function* () {
192 const bridge = makeBridge([]);
193 const setup = pendingSetup();
194 const ensure = vi.spyOn(bridge, "ensureSshEnvironment").mockReturnValue(setup.promise);
195 const exchange = vi.spyOn(bridge, "bootstrapSshBearerSession");
196 for (let attempt = 0; attempt < 2; attempt += 1) {
197 const interrupted = yield* Effect.forkChild(
198 provisionDesktopSshEnvironment(bridge, TARGET),
199 { startImmediately: true },
200 );
201 yield* Fiber.interrupt(interrupted);
202 }
203​
204 const retry = yield* Effect.forkChild(provisionDesktopSshEnvironment(bridge, TARGET), {
205 startImmediately: true,
206 });
207 setup.resolve(SSH_BOOTSTRAP);
208 const provisioned = yield* Fiber.join(retry);
209​
210 expect(provisioned.bearerToken).toBe("bearer-token");
211 expect(ensure).toHaveBeenCalledExactlyOnceWith(TARGET, { issuePairingToken: true });
212 expect(exchange).toHaveBeenCalledExactlyOnceWith(
213 SSH_BOOTSTRAP.httpBaseUrl,
214 "abandoned-token",
215 );
216 }),
217 );
218​
219 it.effect("starts fresh after an abandoned setup settles in success or failure", () =>
220 Effect.gen(function* () {
221 for (const outcome of ["success", "failure"]) {
222 const bridge = makeBridge([]);
223 const setup = pendingSetup();
224 const ensure = vi.spyOn(bridge, "ensureSshEnvironment").mockReturnValueOnce(setup.promise);
225 const exchange = vi.spyOn(bridge, "bootstrapSshBearerSession");
226 const interrupted = yield* Effect.forkChild(
227 provisionDesktopSshEnvironment(bridge, TARGET),
228 { startImmediately: true },
229 );
230 yield* Fiber.interrupt(interrupted);
231 if (outcome === "success") setup.resolve(SSH_BOOTSTRAP);
232 else setup.reject(new Error("remote launch failed"));
233 yield* Effect.promise(() =>
234 setup.promise.then(
235 () => undefined,
236 () => undefined,
237 ),
238 );
239​
240 const provisioned = yield* provisionDesktopSshEnvironment(bridge, TARGET);
241​
242 expect(provisioned.bearerToken).toBe("bearer-token");
243 expect(ensure).toHaveBeenCalledTimes(2);
244 expect(exchange).toHaveBeenCalledExactlyOnceWith(
245 SSH_BOOTSTRAP.httpBaseUrl,
246 "pairing-token",
247 );
248 }
249 }),
250 );
251​
252 it.effect("disconnect invalidates unfinished setup even before provision is interrupted", () =>
253 Effect.gen(function* () {
254 const calls: string[] = [];
255 const bridge = makeBridge(calls);
256 const setup = pendingSetup();
257 const ensure = vi.spyOn(bridge, "ensureSshEnvironment").mockReturnValueOnce(setup.promise);
258 const exchange = vi.spyOn(bridge, "bootstrapSshBearerSession");
259 vi.stubGlobal("window", { desktopBridge: bridge });
260 const ssh = yield* ClientCapabilities.SshEnvironmentGateway.pipe(Effect.provide(layer));
261 const interrupted = yield* Effect.forkChild(ssh.provision(TARGET), {
262 startImmediately: true,
263 });
264 yield* ssh.disconnect(TARGET);
265 yield* Fiber.interrupt(interrupted);
266​
267 const retry = yield* Effect.forkChild(ssh.provision(TARGET), { startImmediately: true });
268 setup.resolve(SSH_BOOTSTRAP);
269 const provisioned = yield* Fiber.join(retry);
270​
271 expect(provisioned.bearerToken).toBe("bearer-token");
272 expect(ensure).toHaveBeenCalledTimes(2);
273 expect(calls).toEqual(["disconnect", "ensure", "descriptor", "token"]);
274 expect(exchange).toHaveBeenCalledExactlyOnceWith(SSH_BOOTSTRAP.httpBaseUrl, "pairing-token");
275 }),
276 );
277​
278 const failPairing = (serverVersion: string, message: string) => {
279 const bridge = makeBridge([]);
280 const fetchDescriptor = bridge.fetchSshEnvironmentDescriptor;
281 vi.spyOn(bridge, "fetchSshEnvironmentDescriptor").mockImplementation(async (url) => ({
282 ...(await fetchDescriptor(url)),
283 serverVersion,
284 }));
285 vi.spyOn(bridge, "bootstrapSshBearerSession").mockRejectedValue(new Error(message));
286 return provisionDesktopSshEnvironment(bridge, TARGET).pipe(Effect.flip);
287 };
288 const PAIRING_500 =
289 "[ssh_http:500] SSH remote API request failed during bootstrap-bearer-session.";
290​
291 it.effect("blocks with both versions when a server on another build rejects pairing", () =>
292 Effect.gen(function* () {
293 const error = yield* failPairing("0.0.46-nightly.20261004.2652", PAIRING_500);
294​
295 expect(error).toBeInstanceOf(ConnectionBlockedError);
296 expect(error.detail).toContain("0.0.46-nightly.20261004.2652");
297 expect(error.detail).toContain(APP_VERSION);
298 }),
299 );
300​
301 it.effect("keeps retrying pairing failures that are not a version mismatch", () =>
302 Effect.gen(function* () {
303 expect(yield* failPairing(APP_VERSION, PAIRING_500)).toBeInstanceOf(ConnectionTransientError);
304 expect(
305 yield* failPairing(
306 "0.0.46-nightly.20261004.2652",
307 "SSH remote API request failed during bootstrap-bearer-session.",
308 ),
309 ).toBeInstanceOf(ConnectionTransientError);
310 }),
311 );
312​
313 it.effect("reconnects with the saved token while it holds every standard scope", () =>
314 Effect.gen(function* () {
315 const calls: string[] = [];
316​
317 const bridge = makeBridge(calls);
318 const ensure = vi.spyOn(bridge, "ensureSshEnvironment");
319 const prepared = yield* prepareDesktopSshEnvironment(bridge, {
320 target: TARGET,
321 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
322 bearerToken: "saved-token",
323 });
324​
325 expect(prepared.bearerToken).toBe("saved-token");
326 expect(ensure).toHaveBeenCalledExactlyOnceWith(TARGET, { issuePairingToken: false });
327 expect(calls).toEqual(["ensure", "descriptor", "session"]);
328 }),
329 );
330​
331 it.effect("pairs again when the host no longer accepts the saved token", () =>
332 Effect.gen(function* () {
333 const calls: string[] = [];
334​
335 const prepared = yield* prepareDesktopSshEnvironment(
336 makeBridge(calls, { savedTokenRejected: true }),
337 {
338 target: TARGET,
339 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
340 bearerToken: "saved-token",
341 },
342 );
343​
344 expect(prepared.bearerToken).toBe("bearer-token");
345 expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);
346 }),
347 );
348​
349 it.effect("pairs again when the saved token predates a standard scope", () =>
350 Effect.gen(function* () {
351 const calls: string[] = [];
352​
353 const prepared = yield* prepareDesktopSshEnvironment(
354 makeBridge(calls, {
355 savedTokenPermissions: ["orchestration:read", "orchestration:operate"],
356 }),
357 {
358 target: TARGET,
359 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
360 bearerToken: "saved-token",
361 },
362 );
363​
364 expect(prepared.bearerToken).toBe("bearer-token");
365 expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);
366 }),
367 );
368​
369 it.effect("stops before sending the saved token or pairing on a different machine", () =>
370 Effect.gen(function* () {
371 const calls: string[] = [];
372​
373 const error = yield* prepareDesktopSshEnvironment(makeBridge(calls), {
374 target: TARGET,
375 expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
376 bearerToken: "saved-token",
377 }).pipe(Effect.flip);
378​
379 expect(error).toMatchObject({ reason: "configuration" });
380 expect(calls).toEqual(["ensure", "descriptor"]);
381 }),
382 );
383});
384​
385describe("desktop-local bearer cache", () => {
386 const registration = {} as never;
387​
388 it("retains only unexpired secondaries after a topology read failure", () => {
389 const valid = {
390 expiresAtEpochMs: 20_000,
391 signature: "valid-secondary",
392 registration,
393 refreshAtEpochMs: 15_000,
394 };
395 const previous = new Map([
396 ["valid-secondary", valid],
397 [
398 "expired-secondary",
399 {
400 expiresAtEpochMs: 10_000,
401 signature: "expired-secondary",
402 registration,
403 refreshAtEpochMs: 5_000,
404 },
405 ],
406 ]);
407​
408 expect(
409 secondaryRegistrationsToRetainAfterTopologyRead(
410 previous,
411 { _tag: "Failure", cause: new Error("IPC unavailable") },
412 10_000,
413 ),
414 ).toEqual(new Map([["valid-secondary", valid]]));
415 });
416​
417 it("treats a successful empty topology as authoritative removal", () => {
418 const previous = new Map([
419 [
420 "secondary",
421 {
422 expiresAtEpochMs: 20_000,
423 signature: "secondary",
424 registration,
425 refreshAtEpochMs: 15_000,
426 },
427 ],
428 ]);
429​
430 expect(
431 secondaryRegistrationsToRetainAfterTopologyRead(
432 previous,
433 { _tag: "Success", bootstraps: [] },
434 10_000,
435 ),
436 ).toEqual(new Map());
437 });
438});
439​
440describe("rejected desktop-local bootstrap tokens", () => {
441 it("retries at once when the token or endpoint changes", () => {
442 const rejected = nextRejectedSecondaryBootstrap(undefined, "http://a|ws://a|old-token", 0);
443​
444 expect(isRejectedSecondaryBootstrap(rejected, "http://a|ws://a|new-token", 1)).toBe(false);
445 expect(isRejectedSecondaryBootstrap(rejected, "http://b|ws://b|old-token", 1)).toBe(false);
446 expect(isRejectedSecondaryBootstrap(undefined, "http://a|ws://a|old-token", 1)).toBe(false);
447 expect(nextRejectedSecondaryBootstrap(rejected, "http://a|ws://a|new-token", 1).delayMs).toBe(
448 60_000,
449 );
450 });
451​
452 // regression: #16273 a rejected desktop-local credential was retried every poll
453 it("treats only authentication rejections as a dead credential", () => {
454 expect(
455 isRejectedBootstrapCredentialError(
456 new ConnectionBlockedError({ reason: "authentication", detail: "invalid" }),
457 ),
458 ).toBe(true);
459 expect(
460 isRejectedBootstrapCredentialError(
461 new ConnectionTransientError({ reason: "endpoint-unavailable", detail: "booting" }),
462 ),
463 ).toBe(false);
464 });
465});
466​
467describe("desktop-local bearer cache across token changes", () => {
468 it("keeps a live bearer when only the bootstrap token rotates", () => {
469 const cached = {
470 signature: "http://a|ws://a",
471 registration: {} as never,
472 expiresAtEpochMs: 20_000,
473 refreshAtEpochMs: 15_000,
474 };
475​
476 expect(canReuseCachedPlatformRegistration(cached, "http://a|ws://a", 10_000)).toBe(true);
477 expect(
478 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, "http://a|ws://a", 16_000),
479 ).toBe(true);
480 expect(canReuseCachedPlatformRegistration(cached, "http://b|ws://b", 10_000)).toBe(false);
481 });
482});
483​
484describe("primary topology cache", () => {
485 const registration = {} as never;
486 const cached = {
487 signature: "primary|http://127.0.0.1:3773/|ws://127.0.0.1:3773/",
488 registration,
489 };
490 const previous = new Map([[PRIMARY_LOCAL_ENVIRONMENT_ID, cached]]);
491​
492 it("retains the cached primary after a transient topology read failure", () => {
493 expect(
494 primaryRegistrationToRetainAfterTopologyRead(previous, {
495 _tag: "Failure",
496 cause: new Error("IPC unavailable"),
497 }),
498 ).toBe(cached);
499 });
500});