Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

platform.test.ts

390 lines12.2 KB

1import {
2 AuthStandardClientScopes,
3 EnvironmentId,
4 PRIMARY_LOCAL_ENVIRONMENT_ID,
5 type DesktopBridge,
6 type DesktopSshEnvironmentTarget,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import {
11 ConnectionBlockedError,
12 ConnectionTransientError,
13} from "@t3tools/client-runtime/connection";
14​
15import {
16 canRetainCachedPlatformRegistrationAfterRefreshFailure,
17 canReuseCachedPlatformRegistration,
18 isRejectedBootstrapCredentialError,
19 isRejectedSecondaryBootstrap,
20 nextRejectedSecondaryBootstrap,
21 primaryRegistrationToRetainAfterTopologyRead,
22 prepareDesktopSshEnvironment,
23 provisionDesktopSshEnvironment,
24 readPrimaryEnvironmentTargetResult,
25 secondaryRegistrationsToRetainAfterTopologyRead,
26 secondaryBearerExpiresAtEpochMs,
27 secondaryBearerRefreshAtEpochMs,
28} from "./platform.ts";
29​
30const TARGET: DesktopSshEnvironmentTarget = {
31 alias: "devbox",
32 hostname: "devbox.example.test",
33 username: "developer",
34 port: 22,
35};
36​
37function makeBridge(
38 calls: string[],
39 options?: {
40 readonly failDescriptor?: boolean;
41 readonly savedTokenRejected?: boolean;
42 readonly savedTokenPermissions?: ReadonlyArray<string>;
43 },
44): DesktopBridge {
45 return {
46 ensureSshEnvironment: async (
47 target: DesktopSshEnvironmentTarget,
48 ensureOptions?: { issuePairingToken?: boolean },
49 ) => {
50 calls.push("ensure");
51 return {
52 target,
53 httpBaseUrl: "http://127.0.0.1:3201/",
54 wsBaseUrl: "ws://127.0.0.1:3201/",
55 pairingToken: ensureOptions?.issuePairingToken === true ? "pairing-token" : null,
56 };
57 },
58 fetchSshSessionState: async () => {
59 calls.push("session");
60 return {
61 authenticated: options?.savedTokenRejected !== true,
62 permissions: options?.savedTokenPermissions ?? AuthStandardClientScopes,
63 };
64 },
65 fetchSshEnvironmentDescriptor: async () => {
66 calls.push("descriptor");
67 if (options?.failDescriptor === true) {
68 throw new Error("descriptor unavailable");
69 }
70 return {
71 environmentId: EnvironmentId.make("environment-ssh"),
72 label: "SSH environment",
73 platform: {
74 os: "linux",
75 arch: "x64",
76 },
77 serverVersion: "0.0.0-test",
78 capabilities: {
79 repositoryIdentity: true,
80 },
81 };
82 },
83 bootstrapSshBearerSession: async () => {
84 calls.push("token");
85 return {
86 access_token: "bearer-token",
87 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
88 token_type: "Bearer",
89 expires_in: 3_600,
90 scope: AuthStandardClientScopes.join(" "),
91 };
92 },
93 } as unknown as DesktopBridge;
95​
96describe("desktop SSH pairing", () => {
97 it.effect("fetches the descriptor before consuming the one-time credential", () =>
98 Effect.gen(function* () {
99 const calls: string[] = [];
100​
101 const provisioned = yield* provisionDesktopSshEnvironment(makeBridge(calls), TARGET);
102​
103 expect(provisioned.environmentId).toBe(EnvironmentId.make("environment-ssh"));
104 expect(calls).toEqual(["ensure", "descriptor", "token"]);
105 }),
106 );
107​
108 it.effect("does not consume the credential when adding a route to a different machine", () =>
109 Effect.gen(function* () {
110 const calls: string[] = [];
111​
112 const error = yield* provisionDesktopSshEnvironment(
113 makeBridge(calls),
114 TARGET,
115 EnvironmentId.make("some-other-machine"),
116 ).pipe(Effect.flip);
117​
118 expect(error).toMatchObject({ reason: "configuration" });
119 expect(calls).toEqual(["ensure", "descriptor"]);
120 }),
121 );
122​
123 it.effect("does not consume the credential when descriptor discovery fails", () =>
124 Effect.gen(function* () {
125 const calls: string[] = [];
126​
127 yield* provisionDesktopSshEnvironment(
128 makeBridge(calls, { failDescriptor: true }),
129 TARGET,
130 ).pipe(Effect.flip);
131​
132 expect(calls).toEqual(["ensure", "descriptor"]);
133 }),
134 );
135​
136 it.effect("reconnects with the saved token while it holds every standard scope", () =>
137 Effect.gen(function* () {
138 const calls: string[] = [];
139​
140 const prepared = yield* prepareDesktopSshEnvironment(makeBridge(calls), {
141 target: TARGET,
142 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
143 bearerToken: "saved-token",
144 });
145​
146 expect(prepared.bearerToken).toBe("saved-token");
147 expect(calls).toEqual(["ensure", "descriptor", "session"]);
148 }),
149 );
150​
151 it.effect("pairs again when the host no longer accepts the saved token", () =>
152 Effect.gen(function* () {
153 const calls: string[] = [];
154​
155 const prepared = yield* prepareDesktopSshEnvironment(
156 makeBridge(calls, { savedTokenRejected: true }),
157 {
158 target: TARGET,
159 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
160 bearerToken: "saved-token",
161 },
162 );
163​
164 expect(prepared.bearerToken).toBe("bearer-token");
165 expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);
166 }),
167 );
168​
169 it.effect("pairs again when the saved token predates a standard scope", () =>
170 Effect.gen(function* () {
171 const calls: string[] = [];
172​
173 const prepared = yield* prepareDesktopSshEnvironment(
174 makeBridge(calls, {
175 savedTokenPermissions: ["orchestration:read", "orchestration:operate"],
176 }),
177 {
178 target: TARGET,
179 expectedEnvironmentId: EnvironmentId.make("environment-ssh"),
180 bearerToken: "saved-token",
181 },
182 );
183​
184 expect(prepared.bearerToken).toBe("bearer-token");
185 expect(calls).toEqual(["ensure", "descriptor", "session", "ensure", "descriptor", "token"]);
186 }),
187 );
188​
189 it.effect("stops before sending the saved token or pairing on a different machine", () =>
190 Effect.gen(function* () {
191 const calls: string[] = [];
192​
193 const error = yield* prepareDesktopSshEnvironment(makeBridge(calls), {
194 target: TARGET,
195 expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
196 bearerToken: "saved-token",
197 }).pipe(Effect.flip);
198​
199 expect(error).toMatchObject({ reason: "configuration" });
200 expect(calls).toEqual(["ensure", "descriptor"]);
201 }),
202 );
203});
204​
205describe("desktop-local bearer cache", () => {
206 const registration = {} as never;
207​
208 it("refreshes a secondary bearer before it expires", () => {
209 const issuedAtEpochMs = 10_000;
210 const refreshAtEpochMs = secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, 60);
211 const expiresAtEpochMs = secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, 60);
212 const cached = {
213 expiresAtEpochMs,
214 signature: "secondary-signature",
215 registration,
216 refreshAtEpochMs,
217 };
218​
219 expect(refreshAtEpochMs).toBe(65_000);
220 expect(canReuseCachedPlatformRegistration(cached, cached.signature, 64_999)).toBe(true);
221 expect(canReuseCachedPlatformRegistration(cached, cached.signature, 65_000)).toBe(false);
222 expect(
223 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, cached.signature, 69_999),
224 ).toBe(true);
225 expect(
226 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, cached.signature, 70_000),
227 ).toBe(false);
228 });
229​
230 it("does not cache credentials whose lifetime is shorter than the refresh skew", () => {
231 const refreshAtEpochMs = secondaryBearerRefreshAtEpochMs(10_000, 3);
232 const cached = {
233 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(10_000, 3),
234 signature: "secondary-signature",
235 registration,
236 refreshAtEpochMs,
237 };
238​
239 expect(refreshAtEpochMs).toBe(10_000);
240 expect(canReuseCachedPlatformRegistration(cached, cached.signature, 10_000)).toBe(false);
241 });
242​
243 it("retains only unexpired secondaries after a topology read failure", () => {
244 const valid = {
245 expiresAtEpochMs: 20_000,
246 signature: "valid-secondary",
247 registration,
248 refreshAtEpochMs: 15_000,
249 };
250 const previous = new Map([
251 ["valid-secondary", valid],
252 [
253 "expired-secondary",
254 {
255 expiresAtEpochMs: 10_000,
256 signature: "expired-secondary",
257 registration,
258 refreshAtEpochMs: 5_000,
259 },
260 ],
261 ]);
262​
263 expect(
264 secondaryRegistrationsToRetainAfterTopologyRead(
265 previous,
266 { _tag: "Failure", cause: new Error("IPC unavailable") },
267 10_000,
268 ),
269 ).toEqual(new Map([["valid-secondary", valid]]));
270 });
271​
272 it("treats a successful empty topology as authoritative removal", () => {
273 const previous = new Map([
274 [
275 "secondary",
276 {
277 expiresAtEpochMs: 20_000,
278 signature: "secondary",
279 registration,
280 refreshAtEpochMs: 15_000,
281 },
282 ],
283 ]);
284​
285 expect(
286 secondaryRegistrationsToRetainAfterTopologyRead(
287 previous,
288 { _tag: "Success", bootstraps: [] },
289 10_000,
290 ),
291 ).toEqual(new Map());
292 });
293});
294​
295describe("rejected desktop-local bootstrap tokens", () => {
296 it("backs off on a rejected signature and retries it on a growing, capped delay", () => {
297 const signature = "http://a|ws://a|old-token";
298 const first = nextRejectedSecondaryBootstrap(undefined, signature, 0);
299​
300 expect(isRejectedSecondaryBootstrap(first, signature, 59_999)).toBe(true);
301 expect(isRejectedSecondaryBootstrap(first, signature, 60_000)).toBe(false);
302​
303 const second = nextRejectedSecondaryBootstrap(first, signature, 60_000);
304 expect(second.retryAtEpochMs).toBe(180_000);
305​
306 let backoff = second;
307 for (let attempt = 0; attempt < 10; attempt += 1) {
308 backoff = nextRejectedSecondaryBootstrap(backoff, signature, 0);
309 }
310 expect(backoff.delayMs).toBe(30 * 60_000);
311 });
312​
313 it("retries at once when the token or endpoint changes", () => {
314 const rejected = nextRejectedSecondaryBootstrap(undefined, "http://a|ws://a|old-token", 0);
315​
316 expect(isRejectedSecondaryBootstrap(rejected, "http://a|ws://a|new-token", 1)).toBe(false);
317 expect(isRejectedSecondaryBootstrap(rejected, "http://b|ws://b|old-token", 1)).toBe(false);
318 expect(isRejectedSecondaryBootstrap(undefined, "http://a|ws://a|old-token", 1)).toBe(false);
319 expect(nextRejectedSecondaryBootstrap(rejected, "http://a|ws://a|new-token", 1).delayMs).toBe(
320 60_000,
321 );
322 });
323​
324 it("treats only authentication rejections as a dead credential", () => {
325 expect(
326 isRejectedBootstrapCredentialError(
327 new ConnectionBlockedError({ reason: "authentication", detail: "invalid" }),
328 ),
329 ).toBe(true);
330 expect(
331 isRejectedBootstrapCredentialError(
332 new ConnectionTransientError({ reason: "endpoint-unavailable", detail: "booting" }),
333 ),
334 ).toBe(false);
335 });
336});
337​
338describe("desktop-local bearer cache across token changes", () => {
339 it("keeps a live bearer when only the bootstrap token rotates", () => {
340 const cached = {
341 signature: "http://a|ws://a",
342 registration: {} as never,
343 expiresAtEpochMs: 20_000,
344 refreshAtEpochMs: 15_000,
345 };
346​
347 expect(canReuseCachedPlatformRegistration(cached, "http://a|ws://a", 10_000)).toBe(true);
348 expect(
349 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, "http://a|ws://a", 16_000),
350 ).toBe(true);
351 expect(canReuseCachedPlatformRegistration(cached, "http://b|ws://b", 10_000)).toBe(false);
352 });
353});
354​
355describe("primary topology cache", () => {
356 const registration = {} as never;
357 const cached = {
358 signature: "primary|http://127.0.0.1:3773/|ws://127.0.0.1:3773/",
359 registration,
360 };
361 const previous = new Map([[PRIMARY_LOCAL_ENVIRONMENT_ID, cached]]);
362​
363 it("captures synchronous primary target read failures", () => {
364 const cause = new Error("invalid primary target");
365​
366 expect(
367 readPrimaryEnvironmentTargetResult(() => {
368 throw cause;
369 }),
370 ).toEqual({ _tag: "Failure", cause });
371 });
372​
373 it("retains the cached primary after a transient topology read failure", () => {
374 expect(
375 primaryRegistrationToRetainAfterTopologyRead(previous, {
376 _tag: "Failure",
377 cause: new Error("IPC unavailable"),
378 }),
379 ).toBe(cached);
380 });
381​
382 it("treats a successful primary absence as authoritative removal", () => {
383 expect(
384 primaryRegistrationToRetainAfterTopologyRead(previous, {
385 _tag: "Success",
386 target: null,
387 }),
388 ).toBeUndefined();
389 });
390});