Skip to content
TypeScript

fix(web): interrupted SSH pairing retries reuse unfinished setup (#19666)

Krishna Vijayeca0e05512e3
diff --git a/apps/web/src/connection/platform.test.ts b/apps/web/src/connection/platform.test.ts
index d0176c239e9..e2f52555253 100644
--- a/apps/web/src/connection/platform.test.ts
+++ b/apps/web/src/connection/platform.test.ts
@@ -3,10 +3,14 @@ import {
EnvironmentId,
PRIMARY_LOCAL_ENVIRONMENT_ID,
type DesktopBridge,
+ type DesktopSshEnvironmentBootstrap,
type DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import { afterEach, vi } from "vite-plus/test";
+import { ClientCapabilities } from "@t3tools/client-runtime/platform";
import {
ConnectionBlockedError,
ConnectionTransientError,
@@ -15,6 +19,7 @@ import {
import {
canRetainCachedPlatformRegistrationAfterRefreshFailure,
canReuseCachedPlatformRegistration,
+ layer,
isRejectedBootstrapCredentialError,
isRejectedSecondaryBootstrap,
nextRejectedSecondaryBootstrap,
@@ -34,6 +39,28 @@ const TARGET: DesktopSshEnvironmentTarget = {
port: 22,
};
+const SSH_BOOTSTRAP = {
+ target: TARGET,
+ httpBaseUrl: "http://127.0.0.1:3201/",
+ wsBaseUrl: "ws://127.0.0.1:3201/",
+ pairingToken: "abandoned-token",
+};
+
+function pendingSetup() {
+ let resolve!: (bootstrap: DesktopSshEnvironmentBootstrap) => void;
+ let reject!: (cause: unknown) => void;
+ const promise = new Promise<DesktopSshEnvironmentBootstrap>((onResolve, onReject) => {
+ resolve = onResolve;
+ reject = onReject;
+ });
+ return { promise, resolve, reject };
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
function makeBridge(
calls: string[],
options?: {
@@ -55,6 +82,9 @@ function makeBridge(
pairingToken: ensureOptions?.issuePairingToken === true ? "pairing-token" : null,
};
},
+ disconnectSshEnvironment: async () => {
+ calls.push("disconnect");
+ },
fetchSshSessionState: async () => {
calls.push("session");
return {
@@ -133,17 +163,108 @@ describe("desktop SSH pairing", () => {
}),
);
+ it.effect("exchanges one setup credential after repeated interrupted provisions", () =>
+ Effect.gen(function* () {
+ const bridge = makeBridge([]);
+ const setup = pendingSetup();
+ const ensure = vi.spyOn(bridge, "ensureSshEnvironment").mockReturnValue(setup.promise);
+ const exchange = vi.spyOn(bridge, "bootstrapSshBearerSession");
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const interrupted = yield* Effect.forkChild(
+ provisionDesktopSshEnvironment(bridge, TARGET),
+ { startImmediately: true },
+ );
+ yield* Fiber.interrupt(interrupted);
+ }
+
+ const retry = yield* Effect.forkChild(provisionDesktopSshEnvironment(bridge, TARGET), {
+ startImmediately: true,
+ });
+ setup.resolve(SSH_BOOTSTRAP);
+ const provisioned = yield* Fiber.join(retry);
+
+ expect(provisioned.bearerToken).toBe("bearer-token");
+ expect(ensure).toHaveBeenCalledExactlyOnceWith(TARGET, { issuePairingToken: true });
+ expect(exchange).toHaveBeenCalledExactlyOnceWith(
+ SSH_BOOTSTRAP.httpBaseUrl,
+ "abandoned-token",
+ );
+ }),
+ );
+
+ it.effect("starts fresh after an abandoned setup settles in success or failure", () =>
+ Effect.gen(function* () {
+ for (const outcome of ["success", "failure"]) {
+ const bridge = makeBridge([]);
+ const setup = pendingSetup();
+ const ensure = vi.spyOn(bridge, "ensureSshEnvironment").mockReturnValueOnce(setup.promise);
+ const exchange = vi.spyOn(bridge, "bootstrapSshBearerSession");
+ const interrupted = yield* Effect.forkChild(
+ provisionDesktopSshEnvironment(bridge, TARGET),
+ { startImmediately: true },
+ );
+ yield* Fiber.interrupt(interrupted);
+ if (outcome === "success") setup.resolve(SSH_BOOTSTRAP);
+ else setup.reject(new Error("remote launch failed"));
+ yield* Effect.promise(() =>
+ setup.promise.then(
+ () => undefined,
+ () => undefined,
+ ),
+ );
+
+ const provisioned = yield* provisionDesktopSshEnvironment(bridge, TARGET);
+
+ expect(provisioned.bearerToken).toBe("bearer-token");
+ expect(ensure).toHaveBeenCalledTimes(2);
+ expect(exchange).toHaveBeenCalledExactlyOnceWith(
+ SSH_BOOTSTRAP.httpBaseUrl,
+ "pairing-token",
+ );
+ }
+ }),
+ );
+
+ it.effect("disconnect invalidates unfinished setup even before provision is interrupted", () =>
+ Effect.gen(function* () {
+ const calls: string[] = [];
+ const bridge = makeBridge(calls);
+ const setup = pendingSetup();
+ const ensure = vi.spyOn(bridge, "ensureSshEnvironment").mockReturnValueOnce(setup.promise);
+ const exchange = vi.spyOn(bridge, "bootstrapSshBearerSession");
+ vi.stubGlobal("window", { desktopBridge: bridge });
+ const ssh = yield* ClientCapabilities.SshEnvironmentGateway.pipe(Effect.provide(layer));
+ const interrupted = yield* Effect.forkChild(ssh.provision(TARGET), {
+ startImmediately: true,
+ });
+ yield* ssh.disconnect(TARGET);
+ yield* Fiber.interrupt(interrupted);
+
+ const retry = yield* Effect.forkChild(ssh.provision(TARGET), { startImmediately: true });
+ setup.resolve(SSH_BOOTSTRAP);
+ const provisioned = yield* Fiber.join(retry);
+
+ expect(provisioned.bearerToken).toBe("bearer-token");
+ expect(ensure).toHaveBeenCalledTimes(2);
+ expect(calls).toEqual(["disconnect", "ensure", "descriptor", "token"]);
+ expect(exchange).toHaveBeenCalledExactlyOnceWith(SSH_BOOTSTRAP.httpBaseUrl, "pairing-token");
+ }),
+ );
+
it.effect("reconnects with the saved token while it holds every standard scope", () =>
Effect.gen(function* () {
const calls: string[] = [];
- const prepared = yield* prepareDesktopSshEnvironment(makeBridge(calls), {
+ const bridge = makeBridge(calls);
+ const ensure = vi.spyOn(bridge, "ensureSshEnvironment");
+ const prepared = yield* prepareDesktopSshEnvironment(bridge, {
target: TARGET,
expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
bearerToken: "saved-token",
});
expect(prepared.bearerToken).toBe("saved-token");
+ expect(ensure).toHaveBeenCalledExactlyOnceWith(TARGET, { issuePairingToken: false });
expect(calls).toEqual(["ensure", "descriptor", "session"]);
}),
);
diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts
index 24ca4804415..1cbaaa163a6 100644
--- a/apps/web/src/connection/platform.ts
+++ b/apps/web/src/connection/platform.ts
@@ -16,6 +16,7 @@ import {
type PlatformConnectionRegistration,
PrimaryConnectionRegistration,
PrimaryConnectionTarget,
+ sshTargetKey,
Wakeups,
} from "@t3tools/client-runtime/connection";
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
@@ -26,6 +27,7 @@ import {
AuthStandardClientScopes,
type DesktopBridge,
type DesktopEnvironmentBootstrap,
+ type DesktopSshEnvironmentBootstrap,
type DesktopSshEnvironmentTarget,
type EnvironmentId,
PRIMARY_LOCAL_ENVIRONMENT_ID,
@@ -178,6 +180,36 @@ function sshPreparationError(cause: unknown) {
});
}
+// IPC keeps running after its waiter is interrupted. A retry can adopt only
+// that interrupted waiter's unfinished setup.
+const pendingSshSetups = new Map<
+ string,
+ { readonly promise: Promise<DesktopSshEnvironmentBootstrap>; signal: AbortSignal }
+>();
+
+const ensureDesktopSshEnvironment = (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) =>
+ Effect.tryPromise({
+ try: (signal) => {
+ const key = sshTargetKey(target);
+ const pending = pendingSshSetups.get(key);
+ if (pending?.signal.aborted) {
+ pending.signal = signal;
+ return pending.promise;
+ }
+ const setup = {
+ promise: bridge.ensureSshEnvironment(target, { issuePairingToken: true }),
+ signal,
+ };
+ pendingSshSetups.set(key, setup);
+ const forget = () => {
+ if (pendingSshSetups.get(key) === setup) pendingSshSetups.delete(key);
+ };
+ setup.promise.then(forget, forget);
+ return setup.promise;
+ },
+ catch: sshPreparationError,
+ });
+
export const provisionDesktopSshEnvironment = Effect.fn(
"web.connectionPlatform.ssh.provisionDesktop",
)(function* (
@@ -185,13 +217,7 @@ export const provisionDesktopSshEnvironment = Effect.fn(
target: DesktopSshEnvironmentTarget,
expectedEnvironmentId?: EnvironmentId,
) {
- const bootstrap = yield* Effect.tryPromise({
- try: () =>
- bridge.ensureSshEnvironment(target, {
- issuePairingToken: true,
- }),
- catch: sshPreparationError,
- });
+ const bootstrap = yield* ensureDesktopSshEnvironment(bridge, target);
const pairingToken = bootstrap.pairingToken;
if (pairingToken === null) {
return yield* new ConnectionBlockedError({
@@ -352,6 +378,7 @@ const layerCapabilities = Layer.effectContext(
if (bridge === undefined) {
return;
}
+ pendingSshSetups.delete(sshTargetKey(target));
yield* Effect.tryPromise({
try: () => bridge.disconnectSshEnvironment(target),
catch: (cause) =>