Open History to see the last commit
1import {
2 EnvironmentId,
3 ORCHESTRATION_PROTOCOL_VERSION,
4 type DesktopSshEnvironmentTarget,
5} from "@t3tools/contracts";
6import { RelayClientTracer } from "@t3tools/shared/relayTracing";
7import { describe, expect, it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Ref from "effect/Ref";
12import * as Tracer from "effect/Tracer";
13
14import * as ConnectionResolver from "./resolver.ts";
15import * as ClientCapabilities from "../platform/capabilities.ts";
16import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
17import {
18 BearerConnectionCredential,
19 BearerConnectionProfile,
20 type ConnectionCatalogEntry,
21 SshConnectionProfile,
22 type ConnectionCredential,
23 type ConnectionProfile,
24} from "./catalog.ts";
25import * as ConnectionCredentialStore from "./credentialStore.ts";
26import {
27 BearerConnectionTarget,
28 ConnectionTransientError,
29 PrimaryConnectionTarget,
30 RelayConnectionTarget,
31 SshConnectionTarget,
32 type ConnectionTarget,
33} from "./model.ts";
34import * as ConnectionProfileStore from "./profileStore.ts";
35import { remoteHttpClientLayer } from "../rpc/http.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 };
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 credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
73 readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
74 readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
75 readonly primaryBearerToken?: string;
76 readonly prepareSsh?: ClientCapabilities.SshEnvironmentGateway["Service"]["prepare"];
77 readonly descriptorProtocolVersion?: number | null | undefined;
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 remoteHttpClientLayer((() =>
144 Promise.resolve(
145 Response.json({
146 environmentId: ENVIRONMENT_ID,
147 label: "Compatible environment",
148 platform: { os: "linux", arch: "x64" },
149 serverVersion: "0.0.0-test",
150 ...(options?.descriptorProtocolVersion === undefined
151 ? { orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION }
152 : options.descriptorProtocolVersion === null
153 ? {}
154 : { orchestrationProtocolVersion: options.descriptorProtocolVersion }),
155 capabilities: { repositoryIdentity: true },
156 }),
157 )) satisfies typeof fetch),
158 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
159 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
160 Layer.succeed(
161 ClientCapabilities.PrimaryEnvironmentAuth,
162 ClientCapabilities.PrimaryEnvironmentAuth.of({
163 bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
164 }),
165 ),
166 Layer.succeed(
167 ClientCapabilities.ClientPresentation,
168 ClientCapabilities.ClientPresentation.of({
169 metadata: { label: "Test Client", deviceType: "desktop", surface: "web" },
170 scopes: [],
171 }),
172 ),
173 Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
174 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
175 );
176
177 return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(dependencies)));
178});
179
180describe("ConnectionResolver", () => {
181 it.effect("blocks an old host during discovery before opening orchestration RPC", () =>
182 Effect.gen(function* () {
183 const brokerLayer = yield* makeDependencies({ descriptorProtocolVersion: null });
184 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
185 const target = new PrimaryConnectionTarget({
186 environmentId: ENVIRONMENT_ID,
187 label: "Primary",
188 httpBaseUrl: "http://127.0.0.1:3777",
189 wsBaseUrl: "ws://127.0.0.1:3777",
190 });
191
192 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
193
194 expect(error).toMatchObject({ reason: "unsupported" });
195 expect(error.message).toContain("Update T3 Code on Compatible environment");
196 }),
197 );
198
199 it.effect("prepares a primary environment without remote capabilities", () =>
200 Effect.gen(function* () {
201 const brokerLayer = yield* makeDependencies();
202 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
203 const target = new PrimaryConnectionTarget({
204 environmentId: ENVIRONMENT_ID,
205 label: "Primary",
206 httpBaseUrl: "http://127.0.0.1:3777",
207 wsBaseUrl: "ws://127.0.0.1:3777",
208 });
209
210 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
211 environmentId: ENVIRONMENT_ID,
212 label: "Primary",
213 httpBaseUrl: "http://127.0.0.1:3777",
214 socketUrl:
215 "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2",
216 httpAuthorization: null,
217 target,
218 });
219 }),
220 );
221
222 it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
223 Effect.gen(function* () {
224 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
225 const brokerLayer = yield* makeDependencies({
226 primaryBearerToken: "desktop-bearer",
227 authorizeBearer: (input) =>
228 Ref.update(bearerInputs, (values) => [
229 ...values,
230 { token: input.bearerToken, method: input.connectionMethod },
231 ]).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&orchestrationProtocol=2",
254 httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
255 target,
256 });
257 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "desktop-bearer", method: "direct" }]);
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<{ token: string; method: 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) => [
280 ...values,
281 { token: input.bearerToken, method: input.connectionMethod },
282 ]).pipe(
283 Effect.as({
284 environmentId: input.expectedEnvironmentId,
285 label: "Saved",
286 httpBaseUrl: input.httpBaseUrl,
287 socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",
288 httpAuthorization: {
289 _tag: "Bearer" as const,
290 token: input.bearerToken,
291 },
292 }),
293 ),
294 });
295 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
296
297 expect(
298 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
299 ).toContain("wsTicket=ticket");
300 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "secret-bearer", method: "direct" }]);
301 }),
302 );
303
304 it.effect("prepares relay connections with the authorized endpoint and credentials", () =>
305 Effect.gen(function* () {
306 const target = new RelayConnectionTarget({
307 environmentId: ENVIRONMENT_ID,
308 label: "Cloud",
309 });
310 const brokerLayer = yield* makeDependencies();
311 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
312
313 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
314 environmentId: ENVIRONMENT_ID,
315 label: "Authorized relay environment",
316 httpBaseUrl: ENDPOINT.httpBaseUrl,
317 socketUrl: `wss://authorized.example.test/ws?wsTicket=dpop&orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}`,
318 httpAuthorization: {
319 _tag: "Dpop",
320 accessToken: "dpop-access-token",
321 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
322 },
323 target,
324 });
325 }),
326 );
327
328 it.effect("exports the complete relay authorization flow through the product tracer", () =>
329 Effect.gen(function* () {
330 const userSpans: Array<string> = [];
331 const productSpans: Array<string> = [];
332 const target = new RelayConnectionTarget({
333 environmentId: ENVIRONMENT_ID,
334 label: "Cloud",
335 });
336 const brokerLayer = yield* makeDependencies({
337 authorizeDpop: (input) =>
338 Effect.succeed({
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 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
347 },
348 }).pipe(Effect.withSpan("test.remote.authorizeDpop")),
349 });
350 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
351
352 yield* broker
353 .prepare(catalogEntry(target))
354 .pipe(
355 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
356 Effect.withTracer(collectingTracer(userSpans)),
357 );
358
359 expect(productSpans).toContain("clientRuntime.connection.broker.relay");
360 expect(productSpans).toContain("test.remote.authorizeDpop");
361 expect(userSpans).toContain("clientRuntime.connection.broker.prepare");
362 expect(userSpans).not.toContain("test.remote.authorizeDpop");
363 }),
364 );
365
366 it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>
367 Effect.gen(function* () {
368 const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
369 const connectionMethods = yield* Ref.make<ReadonlyArray<string>>([]);
370 const target = new SshConnectionTarget({
371 environmentId: ENVIRONMENT_ID,
372 label: "SSH",
373 connectionId: "ssh-1",
374 });
375 const profile = new SshConnectionProfile({
376 connectionId: "ssh-1",
377 environmentId: ENVIRONMENT_ID,
378 label: "SSH",
379 target: SSH_TARGET,
380 });
381 const brokerLayer = yield* makeDependencies({
382 prepareSsh: (input) =>
383 Ref.update(preparedTargets, (values) => [...values, input.target]).pipe(
384 Effect.as({
385 bootstrap: {
386 target: input.target,
387 httpBaseUrl: "http://127.0.0.1:4010",
388 wsBaseUrl: "ws://127.0.0.1:4010",
389 pairingToken: null,
390 },
391 bearerToken: "ssh-bearer",
392 }),
393 ),
394 authorizeBearer: (input) =>
395 Ref.update(connectionMethods, (methods) => [...methods, input.connectionMethod]).pipe(
396 Effect.as({
397 environmentId: input.expectedEnvironmentId,
398 label: "SSH",
399 httpBaseUrl: input.httpBaseUrl,
400 socketUrl: "wss://environment.example.test/ws?wsTicket=bearer",
401 httpAuthorization: {
402 _tag: "Bearer" as const,
403 token: input.bearerToken,
404 },
405 }),
406 ),
407 });
408 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
409
410 expect(
411 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
412 ).toContain("wsTicket=bearer");
413 expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);
414 expect(yield* Ref.get(connectionMethods)).toEqual(["ssh"]);
415 }),
416 );
417
418 it.effect("preserves relay authorization failure classification and trace details", () =>
419 Effect.gen(function* () {
420 const target = new RelayConnectionTarget({
421 environmentId: ENVIRONMENT_ID,
422 label: "Cloud",
423 });
424 const authorizationError = new ConnectionTransientError({
425 reason: "timeout",
426 detail: "Relay environment connection timed out.",
427 traceId: "relay-trace",
428 });
429 const brokerLayer = yield* makeDependencies({
430 authorizeDpop: () => Effect.fail(authorizationError),
431 });
432 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
433 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
434
435 expect(error).toBe(authorizationError);
436 }),
437 );
438});