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

resolver.test.ts

348 lines13.3 KB

1import {
2 EnvironmentId,
3 ORCHESTRATION_PROTOCOL_VERSION,
4 type DesktopSshEnvironmentTarget,
5} from "@t3tools/contracts";
6import { describe, expect, it } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Ref from "effect/Ref";
11​
12import * as ConnectionResolver from "./resolver.ts";
13import * as ClientCapabilities from "../platform/capabilities.ts";
14import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
15import {
16 BearerConnectionCredential,
17 type ConnectionCatalogEntry,
18 SshConnectionProfile,
19 type ConnectionCredential,
20 type ConnectionProfile,
21} from "./catalog.ts";
22import * as ConnectionCredentialStore from "./credentialStore.ts";
23import {
24 ConnectionTransientError,
25 PrimaryConnectionTarget,
26 SshConnectionTarget,
27 type ConnectionTarget,
28} from "./model.ts";
29import * as ConnectionProfileStore from "./profileStore.ts";
30import * as RpcHttp from "../rpc/http.ts";
31import {
32 PullRequestRoutingPermissions,
33 pullRequestRoutingConnectionKey,
34 makePullRequestRoutingPermissions,
35} from "./pullRequestRoutingPermissions.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, enabled: true };
55​
56const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((options?: {
57 readonly profiles?: ReadonlyArray<ConnectionProfile>;
58 readonly profileStore?: ConnectionProfileStore.ConnectionProfileStore["Service"];
59 readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
60 readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
61 readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
62 readonly primaryBearerToken?: string;
63 readonly prepareSsh?: ClientCapabilities.SshEnvironmentGateway["Service"]["prepare"];
64 readonly descriptorProtocolVersion?: number | null | undefined;
65}) => {
66 const profiles = new Map(
67 (options?.profiles ?? []).map((profile) => [profile.connectionId, profile]),
68 );
69 const credentials = new Map(options?.credentials ?? []);
70​
71 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
72 get: (connectionId) => Effect.succeed(Option.fromNullishOr(profiles.get(connectionId))),
73 put: (profile) => Effect.sync(() => void profiles.set(profile.connectionId, profile)),
74 remove: (connectionId) => Effect.sync(() => void profiles.delete(connectionId)),
75 });
76 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
77 get: (connectionId) => Effect.succeed(Option.fromNullishOr(credentials.get(connectionId))),
78 put: (connectionId, credential) =>
79 Effect.sync(() => void credentials.set(connectionId, credential)),
80 remove: (connectionId) => Effect.sync(() => void credentials.delete(connectionId)),
81 });
82 const remote = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
83 authorizeBearer:
84 options?.authorizeBearer ??
85 ((input) =>
86 Effect.succeed({
87 environmentId: input.expectedEnvironmentId,
88 label: "Authorized bearer environment",
89 httpBaseUrl: input.httpBaseUrl,
90 socketUrl: "wss://authorized.example.test/ws?wsTicket=bearer",
91 httpAuthorization: {
92 _tag: "Bearer" as const,
93 token: input.bearerToken,
94 },
95 })),
96 authorizeDpop:
97 options?.authorizeDpop ??
98 ((input) =>
99 Effect.succeed({
100 environmentId: input.expectedEnvironmentId,
101 label: "Authorized relay environment",
102 httpBaseUrl: ENDPOINT.httpBaseUrl,
103 socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
104 httpAuthorization: {
105 _tag: "Dpop" as const,
106 accessToken: "dpop-access-token",
107 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
108 },
109 })),
110 authorizeDpopHttp: () => Effect.die("unused"),
111 });
112 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
113 provision: () => Effect.die("unused"),
114 prepare:
115 options?.prepareSsh ??
116 (() =>
117 Effect.succeed({
118 bootstrap: {
119 target: SSH_TARGET,
120 httpBaseUrl: "http://127.0.0.1:4010",
121 wsBaseUrl: "ws://127.0.0.1:4010",
122 pairingToken: null,
123 },
124 bearerToken: "ssh-bearer",
125 })),
126 disconnect: () => Effect.void,
127 });
128​
129 const layerDependencies = Layer.mergeAll(
130 RpcHttp.layerRemoteHttpClient((() =>
131 Promise.resolve(
132 Response.json({
133 environmentId: ENVIRONMENT_ID,
134 label: "Compatible environment",
135 platform: { os: "linux", arch: "x64" },
136 serverVersion: "0.0.0-test",
137 ...(options?.descriptorProtocolVersion === undefined
138 ? { orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION }
139 : options.descriptorProtocolVersion === null
140 ? {}
141 : { orchestrationProtocolVersion: options.descriptorProtocolVersion }),
142 capabilities: { repositoryIdentity: true },
143 }),
144 )) satisfies typeof fetch),
145 Layer.succeed(
146 ConnectionProfileStore.ConnectionProfileStore,
147 options?.profileStore ?? profileStore,
148 ),
149 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
150 Layer.succeed(
151 ClientCapabilities.PrimaryEnvironmentAuth,
152 ClientCapabilities.PrimaryEnvironmentAuth.of({
153 bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
154 }),
155 ),
156 Layer.succeed(
157 ClientCapabilities.ClientPresentation,
158 ClientCapabilities.ClientPresentation.of({
159 metadata: { label: "Test Client", deviceType: "desktop", surface: "web" },
160 }),
161 ),
162 Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
163 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
164 );
165​
166 return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(layerDependencies)));
167});
168​
169describe("ConnectionResolver", () => {
170 it.effect("blocks an old host during discovery before opening orchestration RPC", () =>
171 Effect.gen(function* () {
172 const layerBroker = yield* makeDependencies({ descriptorProtocolVersion: null });
173 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
174 const target = new PrimaryConnectionTarget({
175 environmentId: ENVIRONMENT_ID,
176 label: "Primary",
177 httpBaseUrl: "http://127.0.0.1:3777",
178 wsBaseUrl: "ws://127.0.0.1:3777",
179 });
180​
181 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
182​
183 expect(error).toMatchObject({ reason: "unsupported" });
184 expect(error.message).toContain("Update T3 Code on Compatible environment");
185 }),
186 );
187​
188 it.effect("prepares a primary environment without remote capabilities", () =>
189 Effect.gen(function* () {
190 const layerBroker = yield* makeDependencies();
191 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
192 const target = new PrimaryConnectionTarget({
193 environmentId: ENVIRONMENT_ID,
194 label: "Primary",
195 httpBaseUrl: "http://127.0.0.1:3777",
196 wsBaseUrl: "ws://127.0.0.1:3777",
197 });
198​
199 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
200 environmentId: ENVIRONMENT_ID,
201 label: "Primary",
202 httpBaseUrl: "http://127.0.0.1:3777",
203 socketUrl:
204 "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2",
205 httpAuthorization: null,
206 target,
207 });
208 }),
209 );
210​
211 it.effect("offers the saved SSH token on each connect and saves the one it gets back", () =>
212 Effect.gen(function* () {
213 const offeredTokens = yield* Ref.make<ReadonlyArray<string | undefined>>([]);
214 const target = new SshConnectionTarget({
215 environmentId: ENVIRONMENT_ID,
216 label: "SSH",
217 connectionId: "ssh-1",
218 });
219 const profile = new SshConnectionProfile({
220 connectionId: "ssh-1",
221 environmentId: ENVIRONMENT_ID,
222 label: "SSH",
223 target: SSH_TARGET,
224 });
225 const layerBroker = yield* makeDependencies({
226 credentials: [["ssh-1", new BearerConnectionCredential({ token: "revoked-token" })]],
227 // The host accepts only the token it paired last; anything else pairs again.
228 prepareSsh: (input) =>
229 Ref.update(offeredTokens, (tokens) => [...tokens, input.bearerToken]).pipe(
230 Effect.as({
231 bootstrap: {
232 target: input.target,
233 httpBaseUrl: "http://127.0.0.1:4010",
234 wsBaseUrl: "ws://127.0.0.1:4010",
235 pairingToken: null,
236 },
237 bearerToken: "paired-token",
238 }),
239 ),
240 });
241 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
242 const entry = catalogEntry(target, Option.some(profile));
243​
244 const first = yield* broker.prepare(entry);
245 const second = yield* broker.prepare(entry);
246​
247 expect(yield* Ref.get(offeredTokens)).toEqual(["revoked-token", "paired-token"]);
248 expect(first.httpAuthorization).toMatchObject({ token: "paired-token" });
249 expect(second.httpAuthorization).toMatchObject({ token: "paired-token" });
250 }),
251 );
252​
253 it.effect.each(["unchanged", "changed", "revocation-failed"] as const)(
254 "handles %s SSH routing consent before saving or authorizing",
255 (scenario) =>
256 Effect.gen(function* () {
257 const calls: string[] = [];
258 const target = new SshConnectionTarget({
259 environmentId: ENVIRONMENT_ID,
260 label: "SSH",
261 connectionId: "ssh-1",
262 });
263 const profile = new SshConnectionProfile({
264 connectionId: target.connectionId,
265 environmentId: ENVIRONMENT_ID,
266 label: "SSH",
267 target: SSH_TARGET,
268 });
269 const entry = catalogEntry(target, Option.some(profile));
270 const preparedTarget =
271 scenario === "unchanged"
272 ? SSH_TARGET
273 : { ...SSH_TARGET, hostname: "replacement.example.test" };
274 const failure = new ConnectionTransientError({
275 reason: "remote-unavailable",
276 detail: "Could not persist routing consent.",
277 });
278 const permissions = yield* makePullRequestRoutingPermissions({
279 read: Effect.succeed([
280 {
281 environmentId: ENVIRONMENT_ID,
282 connectionKey: pullRequestRoutingConnectionKey(entry)!,
283 permission: "read-write",
284 },
285 ]),
286 write: () =>
287 Effect.sync(() => {
288 calls.push("revoke");
289 }).pipe(
290 Effect.andThen(scenario === "revocation-failed" ? Effect.fail(failure) : Effect.void),
291 ),
292 });
293 let savedProfile: ConnectionProfile = profile;
294 const layerBroker = yield* makeDependencies({
295 profileStore: {
296 get: () => Effect.sync(() => Option.some(savedProfile)),
297 put: (value) =>
298 Effect.sync(() => {
299 calls.push("profile");
300 savedProfile = value;
301 }),
302 remove: () => Effect.die("unused"),
303 },
304 prepareSsh: () =>
305 Effect.succeed({
306 bootstrap: {
307 target: preparedTarget,
308 httpBaseUrl: "http://127.0.0.1:4010",
309 wsBaseUrl: "ws://127.0.0.1:4010",
310 pairingToken: null,
311 },
312 bearerToken: "ssh-bearer",
313 }),
314 authorizeBearer: (input) =>
315 Effect.sync(() => {
316 calls.push("authorize");
317 return {
318 environmentId: input.expectedEnvironmentId,
319 label: "SSH",
320 httpBaseUrl: input.httpBaseUrl,
321 socketUrl: "ws://127.0.0.1:4010/ws?wsTicket=ssh",
322 httpAuthorization: { _tag: "Bearer" as const, token: input.bearerToken },
323 };
324 }),
325 });
326 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(
327 Effect.provide(layerBroker),
328 );
329 const prepare = broker
330 .prepare(entry)
331 .pipe(Effect.provideService(PullRequestRoutingPermissions, permissions));
332 if (scenario === "revocation-failed") {
333 expect(yield* Effect.flip(prepare)).toBe(failure);
334 expect(savedProfile).toBe(profile);
335 expect(calls).toEqual(["revoke"]);
336 } else {
337 expect((yield* prepare).socketUrl).toContain("wsTicket=ssh");
338 expect(savedProfile).toMatchObject({ target: preparedTarget });
339 expect(calls).toEqual(
340 scenario === "unchanged"
341 ? ["profile", "authorize"]
342 : ["revoke", "profile", "authorize"],
343 );
344 }
345 expect(yield* permissions.get(entry)).toBe(scenario === "changed" ? "off" : "read-write");
346 }),
347 );
348});