Open History to see the last commit
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 };
54}
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 renewDpopBeforeExpiry: () => Effect.die("unused"),
112 });
113 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
114 provision: () => Effect.die("unused"),
115 prepare:
116 options?.prepareSsh ??
117 (() =>
118 Effect.succeed({
119 bootstrap: {
120 target: SSH_TARGET,
121 httpBaseUrl: "http://127.0.0.1:4010",
122 wsBaseUrl: "ws://127.0.0.1:4010",
123 pairingToken: null,
124 },
125 bearerToken: "ssh-bearer",
126 })),
127 disconnect: () => Effect.void,
128 });
129
130 const layerDependencies = Layer.mergeAll(
131 RpcHttp.layerRemoteHttpClient((() =>
132 Promise.resolve(
133 Response.json({
134 environmentId: ENVIRONMENT_ID,
135 label: "Compatible environment",
136 platform: { os: "linux", arch: "x64" },
137 serverVersion: "0.0.0-test",
138 ...(options?.descriptorProtocolVersion === undefined
139 ? { orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION }
140 : options.descriptorProtocolVersion === null
141 ? {}
142 : { orchestrationProtocolVersion: options.descriptorProtocolVersion }),
143 capabilities: { repositoryIdentity: true },
144 }),
145 )) satisfies typeof fetch),
146 Layer.succeed(
147 ConnectionProfileStore.ConnectionProfileStore,
148 options?.profileStore ?? profileStore,
149 ),
150 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
151 Layer.succeed(
152 ClientCapabilities.PrimaryEnvironmentAuth,
153 ClientCapabilities.PrimaryEnvironmentAuth.of({
154 bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
155 }),
156 ),
157 Layer.succeed(
158 ClientCapabilities.ClientPresentation,
159 ClientCapabilities.ClientPresentation.of({
160 metadata: { label: "Test Client", deviceType: "desktop", surface: "web" },
161 }),
162 ),
163 Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
164 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
165 );
166
167 return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(layerDependencies)));
168});
169
170describe("ConnectionResolver", () => {
171 it.effect("blocks an old host during discovery before opening orchestration RPC", () =>
172 Effect.gen(function* () {
173 const layerBroker = yield* makeDependencies({ descriptorProtocolVersion: null });
174 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
175 const target = new PrimaryConnectionTarget({
176 environmentId: ENVIRONMENT_ID,
177 label: "Primary",
178 httpBaseUrl: "http://127.0.0.1:3777",
179 wsBaseUrl: "ws://127.0.0.1:3777",
180 });
181
182 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
183
184 expect(error).toMatchObject({ reason: "unsupported" });
185 expect(error.message).toContain("Update T3 Code on Compatible environment");
186 }),
187 );
188
189 it.effect("prepares a primary environment without remote capabilities", () =>
190 Effect.gen(function* () {
191 const layerBroker = yield* makeDependencies();
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 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
201 environmentId: ENVIRONMENT_ID,
202 label: "Primary",
203 httpBaseUrl: "http://127.0.0.1:3777",
204 socketUrl:
205 "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2",
206 httpAuthorization: null,
207 target,
208 });
209 }),
210 );
211
212 it.effect("offers the saved SSH token on each connect and saves the one it gets back", () =>
213 Effect.gen(function* () {
214 const offeredTokens = yield* Ref.make<ReadonlyArray<string | undefined>>([]);
215 const target = new SshConnectionTarget({
216 environmentId: ENVIRONMENT_ID,
217 label: "SSH",
218 connectionId: "ssh-1",
219 });
220 const profile = new SshConnectionProfile({
221 connectionId: "ssh-1",
222 environmentId: ENVIRONMENT_ID,
223 label: "SSH",
224 target: SSH_TARGET,
225 });
226 const layerBroker = yield* makeDependencies({
227 credentials: [["ssh-1", new BearerConnectionCredential({ token: "revoked-token" })]],
228 // The host accepts only the token it paired last; anything else pairs again.
229 prepareSsh: (input) =>
230 Ref.update(offeredTokens, (tokens) => [...tokens, input.bearerToken]).pipe(
231 Effect.as({
232 bootstrap: {
233 target: input.target,
234 httpBaseUrl: "http://127.0.0.1:4010",
235 wsBaseUrl: "ws://127.0.0.1:4010",
236 pairingToken: null,
237 },
238 bearerToken: "paired-token",
239 }),
240 ),
241 });
242 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
243 const entry = catalogEntry(target, Option.some(profile));
244
245 const first = yield* broker.prepare(entry);
246 const second = yield* broker.prepare(entry);
247
248 expect(yield* Ref.get(offeredTokens)).toEqual(["revoked-token", "paired-token"]);
249 expect(first.httpAuthorization).toMatchObject({ token: "paired-token" });
250 expect(second.httpAuthorization).toMatchObject({ token: "paired-token" });
251 }),
252 );
253
254 it.effect.each(["unchanged", "changed", "revocation-failed"] as const)(
255 "handles %s SSH routing consent before saving or authorizing",
256 (scenario) =>
257 Effect.gen(function* () {
258 const calls: string[] = [];
259 const target = new SshConnectionTarget({
260 environmentId: ENVIRONMENT_ID,
261 label: "SSH",
262 connectionId: "ssh-1",
263 });
264 const profile = new SshConnectionProfile({
265 connectionId: target.connectionId,
266 environmentId: ENVIRONMENT_ID,
267 label: "SSH",
268 target: SSH_TARGET,
269 });
270 const entry = catalogEntry(target, Option.some(profile));
271 const preparedTarget =
272 scenario === "unchanged"
273 ? SSH_TARGET
274 : { ...SSH_TARGET, hostname: "replacement.example.test" };
275 const failure = new ConnectionTransientError({
276 reason: "remote-unavailable",
277 detail: "Could not persist routing consent.",
278 });
279 const permissions = yield* makePullRequestRoutingPermissions({
280 read: Effect.succeed([
281 {
282 environmentId: ENVIRONMENT_ID,
283 connectionKey: pullRequestRoutingConnectionKey(entry)!,
284 permission: "read-write",
285 },
286 ]),
287 write: () =>
288 Effect.sync(() => {
289 calls.push("revoke");
290 }).pipe(
291 Effect.andThen(scenario === "revocation-failed" ? Effect.fail(failure) : Effect.void),
292 ),
293 });
294 let savedProfile: ConnectionProfile = profile;
295 const layerBroker = yield* makeDependencies({
296 profileStore: {
297 get: () => Effect.sync(() => Option.some(savedProfile)),
298 put: (value) =>
299 Effect.sync(() => {
300 calls.push("profile");
301 savedProfile = value;
302 }),
303 remove: () => Effect.die("unused"),
304 },
305 prepareSsh: () =>
306 Effect.succeed({
307 bootstrap: {
308 target: preparedTarget,
309 httpBaseUrl: "http://127.0.0.1:4010",
310 wsBaseUrl: "ws://127.0.0.1:4010",
311 pairingToken: null,
312 },
313 bearerToken: "ssh-bearer",
314 }),
315 authorizeBearer: (input) =>
316 Effect.sync(() => {
317 calls.push("authorize");
318 return {
319 environmentId: input.expectedEnvironmentId,
320 label: "SSH",
321 httpBaseUrl: input.httpBaseUrl,
322 socketUrl: "ws://127.0.0.1:4010/ws?wsTicket=ssh",
323 httpAuthorization: { _tag: "Bearer" as const, token: input.bearerToken },
324 };
325 }),
326 });
327 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(
328 Effect.provide(layerBroker),
329 );
330 const prepare = broker
331 .prepare(entry)
332 .pipe(Effect.provideService(PullRequestRoutingPermissions, permissions));
333 if (scenario === "revocation-failed") {
334 expect(yield* Effect.flip(prepare)).toBe(failure);
335 expect(savedProfile).toBe(profile);
336 expect(calls).toEqual(["revoke"]);
337 } else {
338 expect((yield* prepare).socketUrl).toContain("wsTicket=ssh");
339 expect(savedProfile).toMatchObject({ target: preparedTarget });
340 expect(calls).toEqual(
341 scenario === "unchanged"
342 ? ["profile", "authorize"]
343 : ["revoke", "profile", "authorize"],
344 );
345 }
346 expect(yield* permissions.get(entry)).toBe(scenario === "changed" ? "off" : "read-write");
347 }),
348 );
349});