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