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

resolver.test.ts

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