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

resolver.test.ts

563 lines21.4 KB

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 };
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 });
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("blocks an incompatible host during discovery before opening orchestration RPC", () =>
209 Effect.gen(function* () {
210 const brokerLayer = yield* makeDependencies({
211 descriptorProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1,
212 });
213 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
214 const target = new PrimaryConnectionTarget({
215 environmentId: ENVIRONMENT_ID,
216 label: "Primary",
217 httpBaseUrl: "http://127.0.0.1:3777",
218 wsBaseUrl: "ws://127.0.0.1:3777",
219 });
220​
221 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
222​
223 expect(error).toMatchObject({ reason: "unsupported" });
224 expect(error.message).toContain("This client is not supported");
225 }),
226 );
227​
228 it.effect("prepares a primary environment without remote capabilities", () =>
229 Effect.gen(function* () {
230 const brokerLayer = yield* makeDependencies();
231 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
232 const target = new PrimaryConnectionTarget({
233 environmentId: ENVIRONMENT_ID,
234 label: "Primary",
235 httpBaseUrl: "http://127.0.0.1:3777",
236 wsBaseUrl: "ws://127.0.0.1:3777",
237 });
238​
239 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
240 environmentId: ENVIRONMENT_ID,
241 label: "Primary",
242 httpBaseUrl: "http://127.0.0.1:3777",
243 socketUrl:
244 "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2",
245 httpAuthorization: null,
246 target,
247 });
248 }),
249 );
250​
251 it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
252 Effect.gen(function* () {
253 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
254 const brokerLayer = yield* makeDependencies({
255 primaryBearerToken: "desktop-bearer",
256 authorizeBearer: (input) =>
257 Ref.update(bearerInputs, (values) => [
258 ...values,
259 { token: input.bearerToken, method: input.connectionMethod },
260 ]).pipe(
261 Effect.as({
262 environmentId: input.expectedEnvironmentId,
263 label: "Primary",
264 httpBaseUrl: input.httpBaseUrl,
265 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
266 httpAuthorization: {
267 _tag: "Bearer" as const,
268 token: input.bearerToken,
269 },
270 }),
271 ),
272 });
273 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
274 const target = new PrimaryConnectionTarget({
275 environmentId: ENVIRONMENT_ID,
276 label: "Primary",
277 httpBaseUrl: "http://127.0.0.1:3777",
278 wsBaseUrl: "ws://127.0.0.1:3777",
279 });
280​
281 expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({
282 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop&orchestrationProtocol=2",
283 httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
284 target,
285 });
286 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "desktop-bearer", method: "direct" }]);
287 }),
288 );
289​
290 it.effect("uses the registered bearer profile without re-reading the profile store", () =>
291 Effect.gen(function* () {
292 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
293 const target = new BearerConnectionTarget({
294 environmentId: ENVIRONMENT_ID,
295 label: "Saved",
296 connectionId: "saved-1",
297 });
298 const profile = new BearerConnectionProfile({
299 connectionId: "saved-1",
300 environmentId: ENVIRONMENT_ID,
301 label: "Saved",
302 httpBaseUrl: ENDPOINT.httpBaseUrl,
303 wsBaseUrl: ENDPOINT.wsBaseUrl,
304 });
305 const brokerLayer = yield* makeDependencies({
306 credentials: [["saved-1", new BearerConnectionCredential({ token: "secret-bearer" })]],
307 authorizeBearer: (input) =>
308 Ref.update(bearerInputs, (values) => [
309 ...values,
310 { token: input.bearerToken, method: input.connectionMethod },
311 ]).pipe(
312 Effect.as({
313 environmentId: input.expectedEnvironmentId,
314 label: "Saved",
315 httpBaseUrl: input.httpBaseUrl,
316 socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",
317 httpAuthorization: {
318 _tag: "Bearer" as const,
319 token: input.bearerToken,
320 },
321 }),
322 ),
323 });
324 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
325​
326 expect(
327 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
328 ).toContain("wsTicket=ticket");
329 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "secret-bearer", method: "direct" }]);
330 }),
331 );
332​
333 it.effect("prepares relay connections with the authorized endpoint and credentials", () =>
334 Effect.gen(function* () {
335 const target = new RelayConnectionTarget({
336 environmentId: ENVIRONMENT_ID,
337 label: "Cloud",
338 });
339 const brokerLayer = yield* makeDependencies();
340 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
341​
342 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
343 environmentId: ENVIRONMENT_ID,
344 label: "Authorized relay environment",
345 httpBaseUrl: ENDPOINT.httpBaseUrl,
346 socketUrl: `wss://authorized.example.test/ws?wsTicket=dpop&orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}`,
347 httpAuthorization: {
348 _tag: "Dpop",
349 accessToken: "dpop-access-token",
350 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
351 },
352 target,
353 });
354 }),
355 );
356​
357 it.effect("exports the complete relay authorization flow through the product tracer", () =>
358 Effect.gen(function* () {
359 const userSpans: Array<string> = [];
360 const productSpans: Array<string> = [];
361 const target = new RelayConnectionTarget({
362 environmentId: ENVIRONMENT_ID,
363 label: "Cloud",
364 });
365 const brokerLayer = yield* makeDependencies({
366 authorizeDpop: (input) =>
367 Effect.succeed({
368 environmentId: input.expectedEnvironmentId,
369 label: "Cloud",
370 httpBaseUrl: ENDPOINT.httpBaseUrl,
371 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
372 httpAuthorization: {
373 _tag: "Dpop" as const,
374 accessToken: "dpop-access-token",
375 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
376 },
377 }).pipe(Effect.withSpan("test.remote.authorizeDpop")),
378 });
379 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
380​
381 yield* broker
382 .prepare(catalogEntry(target))
383 .pipe(
384 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
385 Effect.withTracer(collectingTracer(userSpans)),
386 );
387​
388 expect(productSpans).toContain("clientRuntime.connection.broker.relay");
389 expect(productSpans).toContain("test.remote.authorizeDpop");
390 expect(userSpans).toContain("clientRuntime.connection.broker.prepare");
391 expect(userSpans).not.toContain("test.remote.authorizeDpop");
392 }),
393 );
394​
395 it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>
396 Effect.gen(function* () {
397 const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
398 const connectionMethods = yield* Ref.make<ReadonlyArray<string>>([]);
399 const target = new SshConnectionTarget({
400 environmentId: ENVIRONMENT_ID,
401 label: "SSH",
402 connectionId: "ssh-1",
403 });
404 const profile = new SshConnectionProfile({
405 connectionId: "ssh-1",
406 environmentId: ENVIRONMENT_ID,
407 label: "SSH",
408 target: SSH_TARGET,
409 });
410 const brokerLayer = yield* makeDependencies({
411 prepareSsh: (input) =>
412 Ref.update(preparedTargets, (values) => [...values, input.target]).pipe(
413 Effect.as({
414 bootstrap: {
415 target: input.target,
416 httpBaseUrl: "http://127.0.0.1:4010",
417 wsBaseUrl: "ws://127.0.0.1:4010",
418 pairingToken: null,
419 },
420 bearerToken: "ssh-bearer",
421 }),
422 ),
423 authorizeBearer: (input) =>
424 Ref.update(connectionMethods, (methods) => [...methods, input.connectionMethod]).pipe(
425 Effect.as({
426 environmentId: input.expectedEnvironmentId,
427 label: "SSH",
428 httpBaseUrl: input.httpBaseUrl,
429 socketUrl: "wss://environment.example.test/ws?wsTicket=bearer",
430 httpAuthorization: {
431 _tag: "Bearer" as const,
432 token: input.bearerToken,
433 },
434 }),
435 ),
436 });
437 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
438​
439 expect(
440 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
441 ).toContain("wsTicket=bearer");
442 expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);
443 expect(yield* Ref.get(connectionMethods)).toEqual(["ssh"]);
444 }),
445 );
446​
447 it.effect.each(["unchanged", "changed", "revocation-failed"] as const)(
448 "handles %s SSH routing consent before saving or authorizing",
449 (scenario) =>
450 Effect.gen(function* () {
451 const calls: string[] = [];
452 const target = new SshConnectionTarget({
453 environmentId: ENVIRONMENT_ID,
454 label: "SSH",
455 connectionId: "ssh-1",
456 });
457 const profile = new SshConnectionProfile({
458 connectionId: target.connectionId,
459 environmentId: ENVIRONMENT_ID,
460 label: "SSH",
461 target: SSH_TARGET,
462 });
463 const entry = catalogEntry(target, Option.some(profile));
464 const preparedTarget =
465 scenario === "unchanged"
466 ? SSH_TARGET
467 : { ...SSH_TARGET, hostname: "replacement.example.test" };
468 const failure = new ConnectionTransientError({
469 reason: "remote-unavailable",
470 detail: "Could not persist routing consent.",
471 });
472 const permissions = yield* makeGitHubRoutingPermissions({
473 read: Effect.succeed([
474 {
475 environmentId: ENVIRONMENT_ID,
476 connectionKey: gitHubRoutingConnectionKey(entry)!,
477 permission: "read-write",
478 },
479 ]),
480 write: () =>
481 Effect.sync(() => {
482 calls.push("revoke");
483 }).pipe(
484 Effect.andThen(scenario === "revocation-failed" ? Effect.fail(failure) : Effect.void),
485 ),
486 });
487 let savedProfile: ConnectionProfile = profile;
488 const brokerLayer = yield* makeDependencies({
489 profileStore: {
490 get: () => Effect.sync(() => Option.some(savedProfile)),
491 put: (value) =>
492 Effect.sync(() => {
493 calls.push("profile");
494 savedProfile = value;
495 }),
496 remove: () => Effect.die("unused"),
497 },
498 prepareSsh: () =>
499 Effect.succeed({
500 bootstrap: {
501 target: preparedTarget,
502 httpBaseUrl: "http://127.0.0.1:4010",
503 wsBaseUrl: "ws://127.0.0.1:4010",
504 pairingToken: null,
505 },
506 bearerToken: "ssh-bearer",
507 }),
508 authorizeBearer: (input) =>
509 Effect.sync(() => {
510 calls.push("authorize");
511 return {
512 environmentId: input.expectedEnvironmentId,
513 label: "SSH",
514 httpBaseUrl: input.httpBaseUrl,
515 socketUrl: "ws://127.0.0.1:4010/ws?wsTicket=ssh",
516 httpAuthorization: { _tag: "Bearer" as const, token: input.bearerToken },
517 };
518 }),
519 });
520 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(
521 Effect.provide(brokerLayer),
522 );
523 const prepare = broker
524 .prepare(entry)
525 .pipe(Effect.provideService(GitHubRoutingPermissions, permissions));
526 if (scenario === "revocation-failed") {
527 expect(yield* Effect.flip(prepare)).toBe(failure);
528 expect(savedProfile).toBe(profile);
529 expect(calls).toEqual(["revoke"]);
530 } else {
531 expect((yield* prepare).socketUrl).toContain("wsTicket=ssh");
532 expect(savedProfile).toMatchObject({ target: preparedTarget });
533 expect(calls).toEqual(
534 scenario === "unchanged"
535 ? ["profile", "authorize"]
536 : ["revoke", "profile", "authorize"],
537 );
538 }
539 expect(yield* permissions.get(entry)).toBe(scenario === "changed" ? "off" : "read-write");
540 }),
541 );
542​
543 it.effect("preserves relay authorization failure classification and trace details", () =>
544 Effect.gen(function* () {
545 const target = new RelayConnectionTarget({
546 environmentId: ENVIRONMENT_ID,
547 label: "Cloud",
548 });
549 const authorizationError = new ConnectionTransientError({
550 reason: "timeout",
551 detail: "Relay environment connection timed out.",
552 traceId: "relay-trace",
553 });
554 const brokerLayer = yield* makeDependencies({
555 authorizeDpop: () => Effect.fail(authorizationError),
556 });
557 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
558 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
559​
560 expect(error).toBe(authorizationError);
561 }),
562 );
563});