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

resolver.test.ts

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