Open History to see the last commit
1import { EnvironmentId, type DesktopSshEnvironmentTarget } from "@t3tools/contracts";
2import { RelayClientTracer } from "@t3tools/shared/relayTracing";
3import { describe, expect, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Ref from "effect/Ref";
8import * as Tracer from "effect/Tracer";
9
10import * as ConnectionResolver from "./resolver.ts";
11import * as ClientCapabilities from "../platform/capabilities.ts";
12import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
13import {
14 BearerConnectionCredential,
15 BearerConnectionProfile,
16 type ConnectionCatalogEntry,
17 SshConnectionProfile,
18 type ConnectionCredential,
19 type ConnectionProfile,
20} from "./catalog.ts";
21import * as ConnectionCredentialStore from "./credentialStore.ts";
22import {
23 BearerConnectionTarget,
24 ConnectionTransientError,
25 PrimaryConnectionTarget,
26 RelayConnectionTarget,
27 SshConnectionTarget,
28 type ConnectionTarget,
29} from "./model.ts";
30import * as ConnectionProfileStore from "./profileStore.ts";
31
32const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
33const ENDPOINT = {
34 httpBaseUrl: "https://environment.example.test",
35 wsBaseUrl: "wss://environment.example.test",
36};
37const SSH_TARGET: DesktopSshEnvironmentTarget = {
38 alias: "development",
39 hostname: "development.example.test",
40 username: "developer",
41 port: 22,
42};
43
44function catalogEntry(
45 target: ConnectionTarget,
46 profile: Option.Option<ConnectionProfile> = Option.none(),
47): ConnectionCatalogEntry {
48 return { target, profile };
49}
50
51function collectingTracer(spans: Array<string>): Tracer.Tracer {
52 return Tracer.make({
53 span: (options) => {
54 const span = new Tracer.NativeSpan(options);
55 const end = span.end.bind(span);
56 span.end = (endTime, exit) => {
57 end(endTime, exit);
58 spans.push(span.name);
59 };
60 return span;
61 },
62 });
63}
64
65const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((options?: {
66 readonly profiles?: ReadonlyArray<ConnectionProfile>;
67 readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
68 readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
69 readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
70 readonly primaryBearerToken?: string;
71 readonly prepareSsh?: ClientCapabilities.SshEnvironmentGateway["Service"]["prepare"];
72}) => {
73 const profiles = new Map(
74 (options?.profiles ?? []).map((profile) => [profile.connectionId, profile]),
75 );
76 const credentials = new Map(options?.credentials ?? []);
77
78 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
79 get: (connectionId) => Effect.succeed(Option.fromNullishOr(profiles.get(connectionId))),
80 put: (profile) => Effect.sync(() => void profiles.set(profile.connectionId, profile)),
81 remove: (connectionId) => Effect.sync(() => void profiles.delete(connectionId)),
82 });
83 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
84 get: (connectionId) => Effect.succeed(Option.fromNullishOr(credentials.get(connectionId))),
85 put: (connectionId, credential) =>
86 Effect.sync(() => void credentials.set(connectionId, credential)),
87 remove: (connectionId) => Effect.sync(() => void credentials.delete(connectionId)),
88 });
89 const remote = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
90 authorizeBearer:
91 options?.authorizeBearer ??
92 ((input) =>
93 Effect.succeed({
94 environmentId: input.expectedEnvironmentId,
95 label: "Authorized bearer environment",
96 httpBaseUrl: input.httpBaseUrl,
97 socketUrl: "wss://authorized.example.test/ws?wsTicket=bearer",
98 httpAuthorization: {
99 _tag: "Bearer" as const,
100 token: input.bearerToken,
101 },
102 })),
103 authorizeDpop:
104 options?.authorizeDpop ??
105 ((input) =>
106 Effect.succeed({
107 environmentId: input.expectedEnvironmentId,
108 label: "Authorized relay environment",
109 httpBaseUrl: ENDPOINT.httpBaseUrl,
110 socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
111 httpAuthorization: {
112 _tag: "Dpop" as const,
113 accessToken: "dpop-access-token",
114 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
115 },
116 })),
117 authorizeDpopHttp: () => Effect.die("unused"),
118 });
119 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
120 provision: () => Effect.die("unused"),
121 prepare:
122 options?.prepareSsh ??
123 (() =>
124 Effect.succeed({
125 bootstrap: {
126 target: SSH_TARGET,
127 httpBaseUrl: "http://127.0.0.1:4010",
128 wsBaseUrl: "ws://127.0.0.1:4010",
129 pairingToken: null,
130 },
131 bearerToken: "ssh-bearer",
132 })),
133 disconnect: () => Effect.void,
134 });
135
136 const dependencies = Layer.mergeAll(
137 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
138 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
139 Layer.succeed(
140 ClientCapabilities.PrimaryEnvironmentAuth,
141 ClientCapabilities.PrimaryEnvironmentAuth.of({
142 bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
143 }),
144 ),
145 Layer.succeed(
146 ClientCapabilities.ClientPresentation,
147 ClientCapabilities.ClientPresentation.of({
148 metadata: { label: "Test Client", deviceType: "desktop", surface: "web" },
149 scopes: [],
150 }),
151 ),
152 Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
153 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
154 );
155
156 return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(dependencies)));
157});
158
159describe("ConnectionResolver", () => {
160 it.effect("prepares a primary environment without remote capabilities", () =>
161 Effect.gen(function* () {
162 const brokerLayer = yield* makeDependencies();
163 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
164 const target = new PrimaryConnectionTarget({
165 environmentId: ENVIRONMENT_ID,
166 label: "Primary",
167 httpBaseUrl: "http://127.0.0.1:3777",
168 wsBaseUrl: "ws://127.0.0.1:3777",
169 });
170
171 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
172 environmentId: ENVIRONMENT_ID,
173 label: "Primary",
174 httpBaseUrl: "http://127.0.0.1:3777",
175 socketUrl:
176 "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct",
177 httpAuthorization: null,
178 target,
179 });
180 }),
181 );
182
183 it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
184 Effect.gen(function* () {
185 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
186 const brokerLayer = yield* makeDependencies({
187 primaryBearerToken: "desktop-bearer",
188 authorizeBearer: (input) =>
189 Ref.update(bearerInputs, (values) => [
190 ...values,
191 { token: input.bearerToken, method: input.connectionMethod },
192 ]).pipe(
193 Effect.as({
194 environmentId: input.expectedEnvironmentId,
195 label: "Primary",
196 httpBaseUrl: input.httpBaseUrl,
197 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
198 httpAuthorization: {
199 _tag: "Bearer" as const,
200 token: input.bearerToken,
201 },
202 }),
203 ),
204 });
205 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
206 const target = new PrimaryConnectionTarget({
207 environmentId: ENVIRONMENT_ID,
208 label: "Primary",
209 httpBaseUrl: "http://127.0.0.1:3777",
210 wsBaseUrl: "ws://127.0.0.1:3777",
211 });
212
213 expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({
214 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
215 httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
216 target,
217 });
218 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "desktop-bearer", method: "direct" }]);
219 }),
220 );
221
222 it.effect("uses the registered bearer profile without re-reading the profile store", () =>
223 Effect.gen(function* () {
224 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
225 const target = new BearerConnectionTarget({
226 environmentId: ENVIRONMENT_ID,
227 label: "Saved",
228 connectionId: "saved-1",
229 });
230 const profile = new BearerConnectionProfile({
231 connectionId: "saved-1",
232 environmentId: ENVIRONMENT_ID,
233 label: "Saved",
234 httpBaseUrl: ENDPOINT.httpBaseUrl,
235 wsBaseUrl: ENDPOINT.wsBaseUrl,
236 });
237 const brokerLayer = yield* makeDependencies({
238 credentials: [["saved-1", new BearerConnectionCredential({ token: "secret-bearer" })]],
239 authorizeBearer: (input) =>
240 Ref.update(bearerInputs, (values) => [
241 ...values,
242 { token: input.bearerToken, method: input.connectionMethod },
243 ]).pipe(
244 Effect.as({
245 environmentId: input.expectedEnvironmentId,
246 label: "Saved",
247 httpBaseUrl: input.httpBaseUrl,
248 socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",
249 httpAuthorization: {
250 _tag: "Bearer" as const,
251 token: input.bearerToken,
252 },
253 }),
254 ),
255 });
256 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
257
258 expect(
259 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
260 ).toContain("wsTicket=ticket");
261 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "secret-bearer", method: "direct" }]);
262 }),
263 );
264
265 it.effect("prepares relay connections with the authorized endpoint and credentials", () =>
266 Effect.gen(function* () {
267 const target = new RelayConnectionTarget({
268 environmentId: ENVIRONMENT_ID,
269 label: "Cloud",
270 });
271 const brokerLayer = yield* makeDependencies();
272 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
273
274 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
275 environmentId: ENVIRONMENT_ID,
276 label: "Authorized relay environment",
277 httpBaseUrl: ENDPOINT.httpBaseUrl,
278 socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
279 httpAuthorization: {
280 _tag: "Dpop",
281 accessToken: "dpop-access-token",
282 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
283 },
284 target,
285 });
286 }),
287 );
288
289 it.effect("exports the complete relay authorization flow through the product tracer", () =>
290 Effect.gen(function* () {
291 const userSpans: Array<string> = [];
292 const productSpans: Array<string> = [];
293 const target = new RelayConnectionTarget({
294 environmentId: ENVIRONMENT_ID,
295 label: "Cloud",
296 });
297 const brokerLayer = yield* makeDependencies({
298 authorizeDpop: (input) =>
299 Effect.succeed({
300 environmentId: input.expectedEnvironmentId,
301 label: "Cloud",
302 httpBaseUrl: ENDPOINT.httpBaseUrl,
303 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
304 httpAuthorization: {
305 _tag: "Dpop" as const,
306 accessToken: "dpop-access-token",
307 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
308 },
309 }).pipe(Effect.withSpan("test.remote.authorizeDpop")),
310 });
311 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
312
313 yield* broker
314 .prepare(catalogEntry(target))
315 .pipe(
316 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
317 Effect.withTracer(collectingTracer(userSpans)),
318 );
319
320 expect(productSpans).toContain("clientRuntime.connection.broker.relay");
321 expect(productSpans).toContain("test.remote.authorizeDpop");
322 expect(userSpans).toContain("clientRuntime.connection.broker.prepare");
323 expect(userSpans).not.toContain("test.remote.authorizeDpop");
324 }),
325 );
326
327 it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>
328 Effect.gen(function* () {
329 const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
330 const connectionMethods = yield* Ref.make<ReadonlyArray<string>>([]);
331 const target = new SshConnectionTarget({
332 environmentId: ENVIRONMENT_ID,
333 label: "SSH",
334 connectionId: "ssh-1",
335 });
336 const profile = new SshConnectionProfile({
337 connectionId: "ssh-1",
338 environmentId: ENVIRONMENT_ID,
339 label: "SSH",
340 target: SSH_TARGET,
341 });
342 const brokerLayer = yield* makeDependencies({
343 prepareSsh: (input) =>
344 Ref.update(preparedTargets, (values) => [...values, input.target]).pipe(
345 Effect.as({
346 bootstrap: {
347 target: input.target,
348 httpBaseUrl: "http://127.0.0.1:4010",
349 wsBaseUrl: "ws://127.0.0.1:4010",
350 pairingToken: null,
351 },
352 bearerToken: "ssh-bearer",
353 }),
354 ),
355 authorizeBearer: (input) =>
356 Ref.update(connectionMethods, (methods) => [...methods, input.connectionMethod]).pipe(
357 Effect.as({
358 environmentId: input.expectedEnvironmentId,
359 label: "SSH",
360 httpBaseUrl: input.httpBaseUrl,
361 socketUrl: "wss://environment.example.test/ws?wsTicket=bearer",
362 httpAuthorization: {
363 _tag: "Bearer" as const,
364 token: input.bearerToken,
365 },
366 }),
367 ),
368 });
369 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
370
371 expect(
372 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
373 ).toContain("wsTicket=bearer");
374 expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);
375 expect(yield* Ref.get(connectionMethods)).toEqual(["ssh"]);
376 }),
377 );
378
379 it.effect("preserves relay authorization failure classification and trace details", () =>
380 Effect.gen(function* () {
381 const target = new RelayConnectionTarget({
382 environmentId: ENVIRONMENT_ID,
383 label: "Cloud",
384 });
385 const authorizationError = new ConnectionTransientError({
386 reason: "timeout",
387 detail: "Relay environment connection timed out.",
388 traceId: "relay-trace",
389 });
390 const brokerLayer = yield* makeDependencies({
391 authorizeDpop: () => Effect.fail(authorizationError),
392 });
393 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
394 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
395
396 expect(error).toBe(authorizationError);
397 }),
398 );
399});