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