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

resolver.test.ts

462 lines17.2 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 resetTokenCache: Effect.void,
88 });
90​
91const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((options?: {
92 readonly profiles?: ReadonlyArray<ConnectionProfile>;
93 readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
94 readonly connectEnvironment?: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"];
95 readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
96 readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
97 readonly primaryBearerToken?: string;
98 readonly prepareSsh?: ClientCapabilities.SshEnvironmentGateway["Service"]["prepare"];
99}) => {
100 const profiles = new Map(
101 (options?.profiles ?? []).map((profile) => [profile.connectionId, profile]),
102 );
103 const credentials = new Map(options?.credentials ?? []);
104​
105 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
106 get: (connectionId) => Effect.succeed(Option.fromNullishOr(profiles.get(connectionId))),
107 put: (profile) => Effect.sync(() => void profiles.set(profile.connectionId, profile)),
108 remove: (connectionId) => Effect.sync(() => void profiles.delete(connectionId)),
109 });
110 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
111 get: (connectionId) => Effect.succeed(Option.fromNullishOr(credentials.get(connectionId))),
112 put: (connectionId, credential) =>
113 Effect.sync(() => void credentials.set(connectionId, credential)),
114 remove: (connectionId) => Effect.sync(() => void credentials.delete(connectionId)),
115 });
116 const remote = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
117 authorizeBearer:
118 options?.authorizeBearer ??
119 ((input) =>
120 Effect.succeed({
121 environmentId: input.expectedEnvironmentId,
122 label: "Authorized bearer environment",
123 httpBaseUrl: input.httpBaseUrl,
124 socketUrl: "wss://authorized.example.test/ws?wsTicket=bearer",
125 httpAuthorization: {
126 _tag: "Bearer" as const,
127 token: input.bearerToken,
128 },
129 })),
130 authorizeDpop:
131 options?.authorizeDpop ??
132 ((input) =>
133 input.obtainBootstrap.pipe(
134 Effect.as({
135 environmentId: input.expectedEnvironmentId,
136 label: "Authorized relay environment",
137 httpBaseUrl: ENDPOINT.httpBaseUrl,
138 socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
139 httpAuthorization: {
140 _tag: "Dpop" as const,
141 accessToken: "dpop-access-token",
142 },
143 }),
144 )),
145 });
146 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
147 provision: () => Effect.die("unused"),
148 prepare:
149 options?.prepareSsh ??
150 (() =>
151 Effect.succeed({
152 bootstrap: {
153 target: SSH_TARGET,
154 httpBaseUrl: "http://127.0.0.1:4010",
155 wsBaseUrl: "ws://127.0.0.1:4010",
156 pairingToken: null,
157 },
158 bearerToken: "ssh-bearer",
159 })),
160 disconnect: () => Effect.void,
161 });
162​
163 const dependencies = Layer.mergeAll(
164 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
165 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
166 Layer.succeed(
167 ClientCapabilities.CloudSession,
168 ClientCapabilities.CloudSession.of({ clerkToken: Effect.succeed("clerk-session") }),
169 ),
170 Layer.succeed(
171 ClientCapabilities.PrimaryEnvironmentAuth,
172 ClientCapabilities.PrimaryEnvironmentAuth.of({
173 bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
174 }),
175 ),
176 Layer.succeed(
177 ClientCapabilities.RelayDeviceIdentity,
178 ClientCapabilities.RelayDeviceIdentity.of({
179 deviceId: Effect.succeed(Option.some("device-1")),
180 }),
181 ),
182 Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
183 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
184 Layer.succeed(
185 ManagedRelay.ManagedRelayClient,
186 relayClient(
187 options?.connectEnvironment ??
188 ((input) =>
189 Effect.succeed({
190 environmentId: input.environmentId,
191 endpoint: ENDPOINT,
192 credential: "relay-bootstrap",
193 expiresAt: "2026-06-06T00:00:00.000Z",
194 })),
195 ),
196 ),
197 );
198​
199 return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(dependencies)));
200});
201​
202describe("ConnectionResolver", () => {
203 it.effect("prepares a primary environment without remote capabilities", () =>
204 Effect.gen(function* () {
205 const brokerLayer = yield* makeDependencies();
206 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
207 const target = new PrimaryConnectionTarget({
208 environmentId: ENVIRONMENT_ID,
209 label: "Primary",
210 httpBaseUrl: "http://127.0.0.1:3777",
211 wsBaseUrl: "ws://127.0.0.1:3777",
212 });
213​
214 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
215 environmentId: ENVIRONMENT_ID,
216 label: "Primary",
217 httpBaseUrl: "http://127.0.0.1:3777",
218 socketUrl: "ws://127.0.0.1:3777/ws",
219 httpAuthorization: null,
220 target,
221 });
222 }),
223 );
224​
225 it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
226 Effect.gen(function* () {
227 const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
228 const brokerLayer = yield* makeDependencies({
229 primaryBearerToken: "desktop-bearer",
230 authorizeBearer: (input) =>
231 Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(
232 Effect.as({
233 environmentId: input.expectedEnvironmentId,
234 label: "Primary",
235 httpBaseUrl: input.httpBaseUrl,
236 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
237 httpAuthorization: {
238 _tag: "Bearer" as const,
239 token: input.bearerToken,
240 },
241 }),
242 ),
243 });
244 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
245 const target = new PrimaryConnectionTarget({
246 environmentId: ENVIRONMENT_ID,
247 label: "Primary",
248 httpBaseUrl: "http://127.0.0.1:3777",
249 wsBaseUrl: "ws://127.0.0.1:3777",
250 });
251​
252 expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({
253 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
254 httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
255 target,
256 });
257 expect(yield* Ref.get(bearerInputs)).toEqual(["desktop-bearer"]);
258 }),
259 );
260​
261 it.effect("uses the registered bearer profile without re-reading the profile store", () =>
262 Effect.gen(function* () {
263 const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
264 const target = new BearerConnectionTarget({
265 environmentId: ENVIRONMENT_ID,
266 label: "Saved",
267 connectionId: "saved-1",
268 });
269 const profile = new BearerConnectionProfile({
270 connectionId: "saved-1",
271 environmentId: ENVIRONMENT_ID,
272 label: "Saved",
273 httpBaseUrl: ENDPOINT.httpBaseUrl,
274 wsBaseUrl: ENDPOINT.wsBaseUrl,
275 });
276 const brokerLayer = yield* makeDependencies({
277 credentials: [["saved-1", new BearerConnectionCredential({ token: "secret-bearer" })]],
278 authorizeBearer: (input) =>
279 Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(
280 Effect.as({
281 environmentId: input.expectedEnvironmentId,
282 label: "Saved",
283 httpBaseUrl: input.httpBaseUrl,
284 socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",
285 httpAuthorization: {
286 _tag: "Bearer" as const,
287 token: input.bearerToken,
288 },
289 }),
290 ),
291 });
292 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
293​
294 expect(
295 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
296 ).toContain("wsTicket=ticket");
297 expect(yield* Ref.get(bearerInputs)).toEqual(["secret-bearer"]);
298 }),
299 );
300​
301 it.effect("brokers relay credentials with the current cloud session and device identity", () =>
302 Effect.gen(function* () {
303 const relayInputs = yield* Ref.make<
304 ReadonlyArray<{
305 readonly clerkToken: string;
306 readonly scopes: ReadonlyArray<string>;
307 readonly deviceId?: string;
308 }>
309 >([]);
310 const bootstrapCredentials = yield* Ref.make<ReadonlyArray<string>>([]);
311 const target = new RelayConnectionTarget({
312 environmentId: ENVIRONMENT_ID,
313 label: "Cloud",
314 });
315 const brokerLayer = yield* makeDependencies({
316 connectEnvironment: (input) =>
317 Ref.update(relayInputs, (values) => [
318 ...values,
319 {
320 clerkToken: input.clerkToken,
321 scopes: input.scopes,
322 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
323 },
324 ]).pipe(
325 Effect.as({
326 environmentId: input.environmentId,
327 endpoint: ENDPOINT,
328 credential: "relay-bootstrap",
329 expiresAt: "2026-06-06T00:00:00.000Z",
330 }),
331 ),
332 authorizeDpop: (input) =>
333 input.obtainBootstrap.pipe(
334 Effect.tap((bootstrap) =>
335 Ref.update(bootstrapCredentials, (values) => [...values, bootstrap.credential]),
336 ),
337 Effect.as({
338 environmentId: input.expectedEnvironmentId,
339 label: "Cloud",
340 httpBaseUrl: ENDPOINT.httpBaseUrl,
341 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
342 httpAuthorization: {
343 _tag: "Dpop" as const,
344 accessToken: "dpop-access-token",
345 },
346 }),
347 ),
348 });
349 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
350​
351 expect((yield* broker.prepare(catalogEntry(target))).socketUrl).toContain("wsTicket=dpop");
352 expect(yield* Ref.get(relayInputs)).toEqual([
353 {
354 clerkToken: "clerk-session",
355 scopes: [RelayEnvironmentConnectScope],
356 deviceId: "device-1",
357 },
358 ]);
359 expect(yield* Ref.get(bootstrapCredentials)).toEqual(["relay-bootstrap"]);
360 }),
361 );
362​
363 it.effect("exports the complete relay authorization flow through the product tracer", () =>
364 Effect.gen(function* () {
365 const userSpans: Array<string> = [];
366 const productSpans: Array<string> = [];
367 const target = new RelayConnectionTarget({
368 environmentId: ENVIRONMENT_ID,
369 label: "Cloud",
370 });
371 const brokerLayer = yield* makeDependencies({
372 authorizeDpop: (input) =>
373 input.obtainBootstrap.pipe(
374 Effect.as({
375 environmentId: input.expectedEnvironmentId,
376 label: "Cloud",
377 httpBaseUrl: ENDPOINT.httpBaseUrl,
378 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
379 httpAuthorization: {
380 _tag: "Dpop" as const,
381 accessToken: "dpop-access-token",
382 },
383 }),
384 Effect.withSpan("test.remote.authorizeDpop"),
385 ),
386 });
387 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
388​
389 yield* broker
390 .prepare(catalogEntry(target))
391 .pipe(
392 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
393 Effect.withTracer(collectingTracer(userSpans)),
394 );
395​
396 expect(productSpans).toContain("clientRuntime.connection.broker.relay");
397 expect(productSpans).toContain("test.remote.authorizeDpop");
398 expect(userSpans).toContain("clientRuntime.connection.broker.prepare");
399 expect(userSpans).not.toContain("test.remote.authorizeDpop");
400 }),
401 );
402​
403 it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>
404 Effect.gen(function* () {
405 const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
406 const target = new SshConnectionTarget({
407 environmentId: ENVIRONMENT_ID,
408 label: "SSH",
409 connectionId: "ssh-1",
410 });
411 const profile = new SshConnectionProfile({
412 connectionId: "ssh-1",
413 environmentId: ENVIRONMENT_ID,
414 label: "SSH",
415 target: SSH_TARGET,
416 });
417 const brokerLayer = yield* makeDependencies({
418 prepareSsh: (input) =>
419 Ref.update(preparedTargets, (values) => [...values, input.target]).pipe(
420 Effect.as({
421 bootstrap: {
422 target: input.target,
423 httpBaseUrl: "http://127.0.0.1:4010",
424 wsBaseUrl: "ws://127.0.0.1:4010",
425 pairingToken: null,
426 },
427 bearerToken: "ssh-bearer",
428 }),
429 ),
430 });
431 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
432​
433 expect(
434 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
435 ).toContain("wsTicket=bearer");
436 expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);
437 }),
438 );
439​
440 it.effect("classifies relay request timeouts as retryable connection failures", () =>
441 Effect.gen(function* () {
442 const target = new RelayConnectionTarget({
443 environmentId: ENVIRONMENT_ID,
444 label: "Cloud",
445 });
446 const brokerLayer = yield* makeDependencies({
447 connectEnvironment: () =>
448 Effect.fail(
449 new ManagedRelay.ManagedRelayRequestTimeoutError({
450 activity: "Relay environment connection",
451 timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,
452 }),
453 ),
454 });
455 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
456 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
457​
458 expect(error).toBeInstanceOf(ConnectionTransientError);
459 expect(error).toMatchObject({ reason: "timeout" });
460 }),
461 );
462});