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