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