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

resolver.test.ts

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