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