Skip to content

Commit c401f8a

Browse files
authored
fix(ui): fence stale recovery scope work (#122944)
1 parent 08f9c3a commit c401f8a

2 files changed

Lines changed: 62 additions & 34 deletions

File tree

‎ui/src/api/gateway.node.test.ts‎

Lines changed: 52 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -15,28 +15,24 @@ import {
1515
} from "../lib/nodes/index.ts";
1616
import * as nodes from "../lib/nodes/index.ts";
1717
import {
18+
migrateCloudSessionRecoveryScope,
1819
readCloudSessionRecovery,
1920
writeCloudSessionRecovery,
2021
} from "../lib/sessions/cloud-recovery.ts";
2122
import { createStorageMock } from "../test-helpers/storage.ts";
2223

2324
const wsInstances = vi.hoisted((): MockWebSocket[] => []);
24-
const recoveryMigrationRuntimeLoad = vi.hoisted(() => {
25-
let release = () => {};
26-
let markStarted = () => {};
27-
const started = new Promise<void>((resolve) => {
28-
markStarted = resolve;
29-
});
30-
const pending = new Promise<void>((resolve) => {
31-
release = resolve;
32-
});
33-
return { markStarted, pending, release, started };
34-
});
35-
36-
vi.mock("../lib/sessions/cloud-recovery-migration.runtime.ts", async (importOriginal) => {
37-
recoveryMigrationRuntimeLoad.markStarted();
38-
await recoveryMigrationRuntimeLoad.pending;
39-
return await importOriginal();
25+
const recoveryMigrationRuntimeMock = vi.hoisted(() => ({
26+
loaded: vi.fn(),
27+
migrate: vi.fn(),
28+
}));
29+
30+
vi.mock("../lib/sessions/cloud-recovery-migration.runtime.ts", () => {
31+
recoveryMigrationRuntimeMock.loaded();
32+
return {
33+
default: (gatewayUrl: string, sourceScope: string, destinationScope: string) =>
34+
recoveryMigrationRuntimeMock.migrate(gatewayUrl, sourceScope, destinationScope),
35+
};
4036
});
4137

4238
const DEFAULT_GATEWAY_URL = "ws://127.0.0.1:18789";
@@ -412,6 +408,8 @@ describe("GatewayBrowserClient", () => {
412408
wsInstances.length = 0;
413409
loadOrCreateDeviceIdentityMock.mockReset();
414410
signDevicePayloadMock.mockClear();
411+
recoveryMigrationRuntimeMock.loaded.mockClear();
412+
recoveryMigrationRuntimeMock.migrate.mockImplementation(migrateCloudSessionRecoveryScope);
415413
loadOrCreateDeviceIdentityMock.mockResolvedValue({
416414
deviceId: "device-1",
417415
privateKey: "private-key", // pragma: allowlist secret
@@ -1085,6 +1083,13 @@ describe("GatewayBrowserClient", () => {
10851083
useNodeFakeTimers();
10861084
const sessionStorage = createStorageMock();
10871085
vi.stubGlobal("sessionStorage", sessionStorage);
1086+
const digest = createDeferred<ArrayBuffer>();
1087+
const digestMock = vi.fn(() => digest.promise);
1088+
let requestId = 0;
1089+
vi.stubGlobal("crypto", {
1090+
randomUUID: () => `req-recovery-${++requestId}`,
1091+
subtle: { digest: digestMock },
1092+
});
10881093
const legacyScope = createHash("sha256").update(STORED_CRED).digest("hex");
10891094
const recovery = {
10901095
sessionKey: "agent:cloud:stale",
@@ -1120,13 +1125,35 @@ describe("GatewayBrowserClient", () => {
11201125
},
11211126
},
11221127
});
1123-
await recoveryMigrationRuntimeLoad.started;
1128+
await vi.waitFor(() => expect(digestMock).toHaveBeenCalledOnce());
1129+
expect(recoveryMigrationRuntimeMock.loaded).not.toHaveBeenCalled();
11241130
expect(onRecoveryScopeChange).not.toHaveBeenCalled();
11251131

11261132
firstWs.emitClose(1006, "socket lost");
11271133
await vi.advanceTimersByTimeAsync(800);
11281134
const secondWs = getLatestWebSocket();
1129-
const { connectFrame: secondConnect } = await continueConnect(secondWs, "nonce-current");
1135+
secondWs.emitOpen();
1136+
1137+
digest.resolve(Uint8Array.from(createHash("sha256").update(STORED_CRED).digest()).buffer);
1138+
await vi.waitFor(() => expect(recoveryMigrationRuntimeMock.loaded).toHaveBeenCalledOnce());
1139+
1140+
expect(onRecoveryScopeChange).not.toHaveBeenCalled();
1141+
expect(recoveryMigrationRuntimeMock.migrate).not.toHaveBeenCalled();
1142+
expect(client.recoveryScopeReady).toBe(false);
1143+
expect(readCloudSessionRecovery(DEFAULT_GATEWAY_URL, legacyScope, recovery.sessionKey)).toEqual(
1144+
recovery,
1145+
);
1146+
expect(
1147+
readCloudSessionRecovery(DEFAULT_GATEWAY_URL, "server-stale", recovery.sessionKey),
1148+
).toBeNull();
1149+
1150+
secondWs.emitMessage({
1151+
type: "event",
1152+
event: "connect.challenge",
1153+
payload: { nonce: "nonce-current", ts: 1_800_000_000_000 },
1154+
});
1155+
await vi.advanceTimersByTimeAsync(0);
1156+
const secondConnect = parseLatestConnectFrame(secondWs);
11301157
secondWs.emitMessage({
11311158
type: "res",
11321159
id: secondConnect.id,
@@ -1143,11 +1170,13 @@ describe("GatewayBrowserClient", () => {
11431170
},
11441171
},
11451172
});
1146-
await vi.advanceTimersByTimeAsync(0);
1147-
expect(onRecoveryScopeChange).not.toHaveBeenCalled();
1148-
1149-
recoveryMigrationRuntimeLoad.release();
11501173
await vi.waitFor(() => expect(onRecoveryScopeChange).toHaveBeenCalledOnce());
1174+
expect(recoveryMigrationRuntimeMock.migrate).toHaveBeenCalledExactlyOnceWith(
1175+
DEFAULT_GATEWAY_URL,
1176+
legacyScope,
1177+
"server-current",
1178+
);
1179+
expect(client.recoveryScopeReady).toBe(true);
11511180
expect(client.recoveryScope).toBe("server-current");
11521181
expect(
11531182
readCloudSessionRecovery(DEFAULT_GATEWAY_URL, legacyScope, recovery.sessionKey),
@@ -1159,6 +1188,7 @@ describe("GatewayBrowserClient", () => {
11591188
readCloudSessionRecovery(DEFAULT_GATEWAY_URL, "server-current", recovery.sessionKey),
11601189
).toEqual({ ...recovery, recoveryScope: "server-current" });
11611190
client.stop();
1191+
expect(client.recoveryScopeReady).toBe(false);
11621192
});
11631193

11641194
it("keeps stale credential recovery isolated across a shared-browser principal switch", async () => {
@@ -1199,8 +1229,6 @@ describe("GatewayBrowserClient", () => {
11991229
},
12001230
},
12011231
});
1202-
recoveryMigrationRuntimeLoad.release();
1203-
12041232
await vi.waitFor(() => expect(onRecoveryScopeChange).toHaveBeenCalledOnce());
12051233
expect(client.recoveryScope).toBe(principalScope);
12061234
expect(readCloudSessionRecovery(DEFAULT_GATEWAY_URL, legacyScope, recovery.sessionKey)).toEqual(

‎ui/src/api/gateway.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -315,9 +315,8 @@ export class GatewayBrowserClient {
315315
private tickWatchTimer: ReturnType<typeof setInterval> | null = null;
316316
private pendingDeviceTokenRetry = false;
317317
private deviceTokenRetryBudgetUsed = false;
318-
private recoveryScopeValue = "";
319-
private recoveryScopeResolved = false;
320-
private recoveryScopeGeneration = 0;
318+
// Close/stop advances this generation before another socket can make stale hello work look active.
319+
private recovery = { value: "", resolved: false, generation: 0 };
321320
private scopeUpgradeBinding: ScopeUpgradeBinding | null = null;
322321

323322
constructor(private opts: GatewayBrowserClientOptions) {
@@ -345,6 +344,7 @@ export class GatewayBrowserClient {
345344
},
346345
resolveClose: (context) => this.resolveClose(context),
347346
onClose: (context, decision) => {
347+
this.recovery = { ...this.recovery, generation: context.generation + 1, resolved: false };
348348
this.stopTickWatch();
349349
this.scopeUpgradeBinding = null;
350350
const error = context.connectFailure?.error;
@@ -399,6 +399,7 @@ export class GatewayBrowserClient {
399399

400400
stop() {
401401
this.stopTickWatch();
402+
this.recovery = { ...this.recovery, generation: this.recovery.generation + 1, resolved: false };
402403
this.client.stop();
403404
this.cancelScopeUpgrade();
404405
this.scopeUpgradeBinding = null;
@@ -411,11 +412,11 @@ export class GatewayBrowserClient {
411412
}
412413

413414
get recoveryScope() {
414-
return this.recoveryScopeValue;
415+
return this.recovery.value;
415416
}
416417

417418
get recoveryScopeReady() {
418-
return this.recoveryScopeResolved;
419+
return this.recovery.resolved;
419420
}
420421

421422
get scopeUpgradeReady() {
@@ -441,8 +442,7 @@ export class GatewayBrowserClient {
441442
connectChallengeTs: number | null | undefined,
442443
generation: number,
443444
): Promise<ConnectPlan> {
444-
this.recoveryScopeGeneration = generation;
445-
this.recoveryScopeResolved = false;
445+
this.recovery = { ...this.recovery, generation, resolved: false };
446446
const role = CONTROL_UI_OPERATOR_ROLE;
447447
const client: GatewayConnectClientInfo = {
448448
id: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.CONTROL_UI,
@@ -565,12 +565,12 @@ export class GatewayBrowserClient {
565565
serverScope && hello.auth?.recoveryMigrationAllowed === true && legacyScope
566566
? (await import("../lib/sessions/cloud-recovery-migration.runtime.ts")).default
567567
: undefined;
568-
if (plan.generation !== this.recoveryScopeGeneration || !this.client.connected) {
568+
if (plan.generation !== this.recovery.generation || !this.client.connected) {
569569
return;
570570
}
571571
migrateRecoveryScope?.(this.opts.url, legacyScope, serverScope!);
572-
this.recoveryScopeValue = serverScope ?? legacyScope;
573-
this.recoveryScopeResolved = true;
572+
this.recovery.value = serverScope ?? legacyScope;
573+
this.recovery.resolved = true;
574574
this.opts.onRecoveryScopeChange?.();
575575
}
576576

0 commit comments

Comments
 (0)