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

resolver.test.ts

496 lines18.7 KB

1import { EnvironmentId, type DesktopSshEnvironmentTarget } from "@t3tools/contracts";
2import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
3import { RelayClientTracer } from "@t3tools/shared/relayTracing";
4import { describe, expect, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Ref from "effect/Ref";
9import * as Tracer from "effect/Tracer";
10​
11import * as ManagedRelay from "../relay/managedRelay.ts";
12import * as ConnectionResolver from "./resolver.ts";
13import * as ClientCapabilities from "../platform/capabilities.ts";
14import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
15import {
16 BearerConnectionCredential,
17 BearerConnectionProfile,
18 type ConnectionCatalogEntry,
19 SshConnectionProfile,
20 type ConnectionCredential,
21 type ConnectionProfile,
22} from "./catalog.ts";
23import * as ConnectionCredentialStore from "./credentialStore.ts";
24import {
25 BearerConnectionTarget,
26 ConnectionTransientError,
27 PrimaryConnectionTarget,
28 RelayConnectionTarget,
29 SshConnectionTarget,
30 type ConnectionTarget,
31} from "./model.ts";
32import * as ConnectionProfileStore from "./profileStore.ts";
33​
34const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
35const ENDPOINT = {
36 httpBaseUrl: "https://environment.example.test",
37 wsBaseUrl: "wss://environment.example.test",
38 providerKind: "cloudflare_tunnel" as const,
39};
40const SSH_TARGET: DesktopSshEnvironmentTarget = {
41 alias: "development",
42 hostname: "development.example.test",
43 username: "developer",
44 port: 22,
45};
46​
47function catalogEntry(
48 target: ConnectionTarget,
49 profile: Option.Option<ConnectionProfile> = Option.none(),
50): ConnectionCatalogEntry {
51 return { target, profile };
53​
54function unsupported<A>(name: string): Effect.Effect<A> {
55 return Effect.die(new Error(`Unexpected relay call: ${name}`));
57​
58function collectingTracer(spans: Array<string>): Tracer.Tracer {
59 return Tracer.make({
60 span: (options) => {
61 const span = new Tracer.NativeSpan(options);
62 const end = span.end.bind(span);
63 span.end = (endTime, exit) => {
64 end(endTime, exit);
65 spans.push(span.name);
66 };
67 return span;
68 },
69 });
71​
72function relayClient(
73 connectEnvironment: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"],
74) {
75 return ManagedRelay.ManagedRelayClient.of({
76 relayUrl: "https://relay.example.test",
77 listEnvironments: () => unsupported("listEnvironments"),
78 listDevices: () => unsupported("listDevices"),
79 createEnvironmentLinkChallenge: () => unsupported("createEnvironmentLinkChallenge"),
80 linkEnvironment: () => unsupported("linkEnvironment"),
81 unlinkEnvironment: () => unsupported("unlinkEnvironment"),
82 getEnvironmentStatus: () => unsupported("getEnvironmentStatus"),
83 connectEnvironment,
84 registerDevice: () => unsupported("registerDevice"),
85 unregisterDevice: () => unsupported("unregisterDevice"),
86 registerLiveActivity: () => unsupported("registerLiveActivity"),
87 getAgentActivitySnapshot: () => unsupported("getAgentActivitySnapshot"),
88 resetTokenCache: Effect.void,
89 });
91​
92const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((options?: {
93 readonly profiles?: ReadonlyArray<ConnectionProfile>;
94 readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
95 readonly connectEnvironment?: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"];
96 readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
97 readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
98 readonly primaryBearerToken?: string;
99 readonly prepareSsh?: ClientCapabilities.SshEnvironmentGateway["Service"]["prepare"];
100}) => {
101 const profiles = new Map(
102 (options?.profiles ?? []).map((profile) => [profile.connectionId, profile]),
103 );
104 const credentials = new Map(options?.credentials ?? []);
105​
106 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
107 get: (connectionId) => Effect.succeed(Option.fromNullishOr(profiles.get(connectionId))),
108 put: (profile) => Effect.sync(() => void profiles.set(profile.connectionId, profile)),
109 remove: (connectionId) => Effect.sync(() => void profiles.delete(connectionId)),
110 });
111 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
112 get: (connectionId) => Effect.succeed(Option.fromNullishOr(credentials.get(connectionId))),
113 put: (connectionId, credential) =>
114 Effect.sync(() => void credentials.set(connectionId, credential)),
115 remove: (connectionId) => Effect.sync(() => void credentials.delete(connectionId)),
116 });
117 const remote = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
118 authorizeBearer:
119 options?.authorizeBearer ??
120 ((input) =>
121 Effect.succeed({
122 environmentId: input.expectedEnvironmentId,
123 label: "Authorized bearer environment",
124 httpBaseUrl: input.httpBaseUrl,
125 socketUrl: "wss://authorized.example.test/ws?wsTicket=bearer",
126 httpAuthorization: {
127 _tag: "Bearer" as const,
128 token: input.bearerToken,
129 },
130 })),
131 authorizeDpop:
132 options?.authorizeDpop ??
133 ((input) =>
134 input.obtainBootstrap.pipe(
135 Effect.as({
136 environmentId: input.expectedEnvironmentId,
137 label: "Authorized relay environment",
138 httpBaseUrl: ENDPOINT.httpBaseUrl,
139 socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
140 httpAuthorization: {
141 _tag: "Dpop" as const,
142 accessToken: "dpop-access-token",
143 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
144 },
145 }),
146 )),
147 });
148 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
149 provision: () => Effect.die("unused"),
150 prepare:
151 options?.prepareSsh ??
152 (() =>
153 Effect.succeed({
154 bootstrap: {
155 target: SSH_TARGET,
156 httpBaseUrl: "http://127.0.0.1:4010",
157 wsBaseUrl: "ws://127.0.0.1:4010",
158 pairingToken: null,
159 },
160 bearerToken: "ssh-bearer",
161 })),
162 disconnect: () => Effect.void,
163 });
164​
165 const dependencies = Layer.mergeAll(
166 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
167 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
168 Layer.succeed(
169 ClientCapabilities.CloudSession,
170 ClientCapabilities.CloudSession.of({ clerkToken: Effect.succeed("clerk-session") }),
171 ),
172 Layer.succeed(
173 ClientCapabilities.PrimaryEnvironmentAuth,
174 ClientCapabilities.PrimaryEnvironmentAuth.of({
175 bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
176 }),
177 ),
178 Layer.succeed(
179 ClientCapabilities.ClientPresentation,
180 ClientCapabilities.ClientPresentation.of({
181 metadata: { label: "Test Client", deviceType: "desktop", surface: "web" },
182 scopes: [],
183 }),
184 ),
185 Layer.succeed(
186 ClientCapabilities.RelayDeviceIdentity,
187 ClientCapabilities.RelayDeviceIdentity.of({
188 deviceId: Effect.succeed(Option.some("device-1")),
189 }),
190 ),
191 Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
192 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
193 Layer.succeed(
194 ManagedRelay.ManagedRelayClient,
195 relayClient(
196 options?.connectEnvironment ??
197 ((input) =>
198 Effect.succeed({
199 environmentId: input.environmentId,
200 endpoint: ENDPOINT,
201 credential: "relay-bootstrap",
202 expiresAt: "2026-06-06T00:00:00.000Z",
203 })),
204 ),
205 ),
206 );
207​
208 return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(dependencies)));
209});
210​
211describe("ConnectionResolver", () => {
212 it.effect("prepares a primary environment without remote capabilities", () =>
213 Effect.gen(function* () {
214 const brokerLayer = yield* makeDependencies();
215 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
216 const target = new PrimaryConnectionTarget({
217 environmentId: ENVIRONMENT_ID,
218 label: "Primary",
219 httpBaseUrl: "http://127.0.0.1:3777",
220 wsBaseUrl: "ws://127.0.0.1:3777",
221 });
222​
223 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
224 environmentId: ENVIRONMENT_ID,
225 label: "Primary",
226 httpBaseUrl: "http://127.0.0.1:3777",
227 socketUrl:
228 "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct",
229 httpAuthorization: null,
230 target,
231 });
232 }),
233 );
234​
235 it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
236 Effect.gen(function* () {
237 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
238 const brokerLayer = yield* makeDependencies({
239 primaryBearerToken: "desktop-bearer",
240 authorizeBearer: (input) =>
241 Ref.update(bearerInputs, (values) => [
242 ...values,
243 { token: input.bearerToken, method: input.connectionMethod },
244 ]).pipe(
245 Effect.as({
246 environmentId: input.expectedEnvironmentId,
247 label: "Primary",
248 httpBaseUrl: input.httpBaseUrl,
249 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
250 httpAuthorization: {
251 _tag: "Bearer" as const,
252 token: input.bearerToken,
253 },
254 }),
255 ),
256 });
257 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
258 const target = new PrimaryConnectionTarget({
259 environmentId: ENVIRONMENT_ID,
260 label: "Primary",
261 httpBaseUrl: "http://127.0.0.1:3777",
262 wsBaseUrl: "ws://127.0.0.1:3777",
263 });
264​
265 expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({
266 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
267 httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
268 target,
269 });
270 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "desktop-bearer", method: "direct" }]);
271 }),
272 );
273​
274 it.effect("uses the registered bearer profile without re-reading the profile store", () =>
275 Effect.gen(function* () {
276 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
277 const target = new BearerConnectionTarget({
278 environmentId: ENVIRONMENT_ID,
279 label: "Saved",
280 connectionId: "saved-1",
281 });
282 const profile = new BearerConnectionProfile({
283 connectionId: "saved-1",
284 environmentId: ENVIRONMENT_ID,
285 label: "Saved",
286 httpBaseUrl: ENDPOINT.httpBaseUrl,
287 wsBaseUrl: ENDPOINT.wsBaseUrl,
288 });
289 const brokerLayer = yield* makeDependencies({
290 credentials: [["saved-1", new BearerConnectionCredential({ token: "secret-bearer" })]],
291 authorizeBearer: (input) =>
292 Ref.update(bearerInputs, (values) => [
293 ...values,
294 { token: input.bearerToken, method: input.connectionMethod },
295 ]).pipe(
296 Effect.as({
297 environmentId: input.expectedEnvironmentId,
298 label: "Saved",
299 httpBaseUrl: input.httpBaseUrl,
300 socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",
301 httpAuthorization: {
302 _tag: "Bearer" as const,
303 token: input.bearerToken,
304 },
305 }),
306 ),
307 });
308 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
309​
310 expect(
311 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
312 ).toContain("wsTicket=ticket");
313 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "secret-bearer", method: "direct" }]);
314 }),
315 );
316​
317 it.effect("brokers relay credentials with the current cloud session and device identity", () =>
318 Effect.gen(function* () {
319 const relayInputs = yield* Ref.make<
320 ReadonlyArray<{
321 readonly clerkToken: string;
322 readonly scopes: ReadonlyArray<string>;
323 readonly deviceId?: string;
324 }>
325 >([]);
326 const bootstrapCredentials = yield* Ref.make<ReadonlyArray<string>>([]);
327 const target = new RelayConnectionTarget({
328 environmentId: ENVIRONMENT_ID,
329 label: "Cloud",
330 });
331 const brokerLayer = yield* makeDependencies({
332 connectEnvironment: (input) =>
333 Ref.update(relayInputs, (values) => [
334 ...values,
335 {
336 clerkToken: input.clerkToken,
337 scopes: input.scopes,
338 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
339 },
340 ]).pipe(
341 Effect.as({
342 environmentId: input.environmentId,
343 endpoint: ENDPOINT,
344 credential: "relay-bootstrap",
345 expiresAt: "2026-06-06T00:00:00.000Z",
346 }),
347 ),
348 authorizeDpop: (input) =>
349 input.obtainBootstrap.pipe(
350 Effect.tap((bootstrap) =>
351 Ref.update(bootstrapCredentials, (values) => [...values, bootstrap.credential]),
352 ),
353 Effect.as({
354 environmentId: input.expectedEnvironmentId,
355 label: "Cloud",
356 httpBaseUrl: ENDPOINT.httpBaseUrl,
357 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
358 httpAuthorization: {
359 _tag: "Dpop" as const,
360 accessToken: "dpop-access-token",
361 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
362 },
363 }),
364 ),
365 });
366 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
367​
368 expect((yield* broker.prepare(catalogEntry(target))).socketUrl).toContain("wsTicket=dpop");
369 expect(yield* Ref.get(relayInputs)).toEqual([
370 {
371 clerkToken: "clerk-session",
372 scopes: [RelayEnvironmentConnectScope],
373 deviceId: "device-1",
374 },
375 ]);
376 expect(yield* Ref.get(bootstrapCredentials)).toEqual(["relay-bootstrap"]);
377 }),
378 );
379​
380 it.effect("exports the complete relay authorization flow through the product tracer", () =>
381 Effect.gen(function* () {
382 const userSpans: Array<string> = [];
383 const productSpans: Array<string> = [];
384 const target = new RelayConnectionTarget({
385 environmentId: ENVIRONMENT_ID,
386 label: "Cloud",
387 });
388 const brokerLayer = yield* makeDependencies({
389 authorizeDpop: (input) =>
390 input.obtainBootstrap.pipe(
391 Effect.as({
392 environmentId: input.expectedEnvironmentId,
393 label: "Cloud",
394 httpBaseUrl: ENDPOINT.httpBaseUrl,
395 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
396 httpAuthorization: {
397 _tag: "Dpop" as const,
398 accessToken: "dpop-access-token",
399 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
400 },
401 }),
402 Effect.withSpan("test.remote.authorizeDpop"),
403 ),
404 });
405 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
406​
407 yield* broker
408 .prepare(catalogEntry(target))
409 .pipe(
410 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
411 Effect.withTracer(collectingTracer(userSpans)),
412 );
413​
414 expect(productSpans).toContain("clientRuntime.connection.broker.relay");
415 expect(productSpans).toContain("test.remote.authorizeDpop");
416 expect(userSpans).toContain("clientRuntime.connection.broker.prepare");
417 expect(userSpans).not.toContain("test.remote.authorizeDpop");
418 }),
419 );
420​
421 it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>
422 Effect.gen(function* () {
423 const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
424 const connectionMethods = yield* Ref.make<ReadonlyArray<string>>([]);
425 const target = new SshConnectionTarget({
426 environmentId: ENVIRONMENT_ID,
427 label: "SSH",
428 connectionId: "ssh-1",
429 });
430 const profile = new SshConnectionProfile({
431 connectionId: "ssh-1",
432 environmentId: ENVIRONMENT_ID,
433 label: "SSH",
434 target: SSH_TARGET,
435 });
436 const brokerLayer = yield* makeDependencies({
437 prepareSsh: (input) =>
438 Ref.update(preparedTargets, (values) => [...values, input.target]).pipe(
439 Effect.as({
440 bootstrap: {
441 target: input.target,
442 httpBaseUrl: "http://127.0.0.1:4010",
443 wsBaseUrl: "ws://127.0.0.1:4010",
444 pairingToken: null,
445 },
446 bearerToken: "ssh-bearer",
447 }),
448 ),
449 authorizeBearer: (input) =>
450 Ref.update(connectionMethods, (methods) => [...methods, input.connectionMethod]).pipe(
451 Effect.as({
452 environmentId: input.expectedEnvironmentId,
453 label: "SSH",
454 httpBaseUrl: input.httpBaseUrl,
455 socketUrl: "wss://environment.example.test/ws?wsTicket=bearer",
456 httpAuthorization: {
457 _tag: "Bearer" as const,
458 token: input.bearerToken,
459 },
460 }),
461 ),
462 });
463 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
464​
465 expect(
466 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
467 ).toContain("wsTicket=bearer");
468 expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);
469 expect(yield* Ref.get(connectionMethods)).toEqual(["ssh"]);
470 }),
471 );
472​
473 it.effect("classifies relay request timeouts as retryable connection failures", () =>
474 Effect.gen(function* () {
475 const target = new RelayConnectionTarget({
476 environmentId: ENVIRONMENT_ID,
477 label: "Cloud",
478 });
479 const brokerLayer = yield* makeDependencies({
480 connectEnvironment: () =>
481 Effect.fail(
482 new ManagedRelay.ManagedRelayRequestTimeoutError({
483 activity: "Relay environment connection",
484 timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,
485 traceId: null,
486 }),
487 ),
488 });
489 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
490 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
491​
492 expect(error).toBeInstanceOf(ConnectionTransientError);
493 expect(error).toMatchObject({ reason: "timeout" });
494 }),
495 );
496});