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

onboarding.test.ts

335 lines11.0 KB

1import {
2 AuthStandardClientScopes,
3 EnvironmentId,
4 ORCHESTRATION_PROTOCOL_VERSION,
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";
10​
11import { remoteHttpClientLayer } from "../rpc/http.ts";
12import * as ClientCapabilities from "../platform/capabilities.ts";
13import { BearerConnectionCredential, BearerConnectionProfile } from "./catalog.ts";
14import { BearerConnectionTarget } from "./model.ts";
15import {
16 prepareBearerConnectionUpdate,
17 preparePairingRegistration,
18 prepareSshRegistration,
19} from "./onboarding.ts";
20​
21const CLIENT_PRESENTATION_LAYER = Layer.succeed(
22 ClientCapabilities.ClientPresentation,
23 ClientCapabilities.ClientPresentation.of({
24 metadata: {
25 label: "T3 Code Test",
26 deviceType: "desktop",
27 os: "Test OS",
28 },
29 scopes: AuthStandardClientScopes,
30 }),
31);
32​
33function pairingHttpLayer(
34 calls: Array<{ readonly url: string; readonly init: RequestInit }>,
35 options?: {
36 readonly failDescriptor?: boolean;
37 readonly protocolVersion?: number;
38 readonly selfUpdate?: boolean;
39 },
40) {
41 const fetchFn = ((input, init = {}) => {
42 const url = String(input);
43 calls.push({ url, init });
44​
45 if (url.endsWith("/.well-known/t3/environment")) {
46 if (options?.failDescriptor === true) {
47 return Promise.resolve(
48 Response.json({ message: "descriptor unavailable" }, { status: 503 }),
49 );
50 }
51 return Promise.resolve(
52 Response.json({
53 environmentId: "environment-paired",
54 label: "Paired environment",
55 platform: {
56 os: "linux",
57 arch: "x64",
58 },
59 serverVersion: "0.0.0-test",
60 orchestrationProtocolVersion: options?.protocolVersion ?? ORCHESTRATION_PROTOCOL_VERSION,
61 capabilities: {
62 repositoryIdentity: true,
63 ...(options?.selfUpdate === true ? { serverSelfUpdate: "boot-service" } : {}),
64 },
65 }),
66 );
67 }
68​
69 if (url.endsWith("/oauth/token")) {
70 return Promise.resolve(
71 Response.json({
72 access_token: "bearer-token",
73 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
74 token_type: "Bearer",
75 expires_in: 3600,
76 scope: AuthStandardClientScopes.join(" "),
77 }),
78 );
79 }
80​
81 return Promise.reject(new Error(`Unexpected request: ${url}`));
82 }) satisfies typeof fetch;
83​
84 return remoteHttpClientLayer(fetchFn);
86​
87describe("connection onboarding", () => {
88 it.effect("prepares a persisted bearer registration from pairing details", () =>
89 Effect.gen(function* () {
90 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
91 const registration = yield* preparePairingRegistration({
92 host: "remote.example.test",
93 pairingCode: "pairing-token",
94 }).pipe(Effect.provide(Layer.mergeAll(CLIENT_PRESENTATION_LAYER, pairingHttpLayer(calls))));
95​
96 expect(registration).toMatchObject({
97 _tag: "BearerConnectionRegistration",
98 target: {
99 environmentId: "environment-paired",
100 label: "Paired environment",
101 connectionId: "bearer:environment-paired",
102 },
103 profile: {
104 environmentId: "environment-paired",
105 label: "Paired environment",
106 connectionId: "bearer:environment-paired",
107 httpBaseUrl: "https://remote.example.test/",
108 wsBaseUrl: "wss://remote.example.test/",
109 },
110 credential: {
111 token: "bearer-token",
112 },
113 });
114 expect(calls.map((call) => call.url)).toEqual([
115 "https://remote.example.test/.well-known/t3/environment",
116 "https://remote.example.test/oauth/token",
117 ]);
118​
119 const tokenRequest = calls.find((call) => call.url.endsWith("/oauth/token"));
120 const tokenBody =
121 tokenRequest?.init.body instanceof Uint8Array
122 ? new TextDecoder().decode(tokenRequest.init.body)
123 : String(tokenRequest?.init.body);
124 const tokenParams = new URLSearchParams(tokenBody);
125 expect(tokenParams.get("subject_token")).toBe("pairing-token");
126 expect(tokenParams.get("scope")).toBe(AuthStandardClientScopes.join(" "));
127 expect(tokenParams.get("client_label")).toBe("T3 Code Test");
128 }),
129 );
130​
131 it.effect("rejects an incompatible server without consuming the pairing credential", () =>
132 Effect.gen(function* () {
133 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
134 const error = yield* preparePairingRegistration({
135 host: "remote.example.test",
136 pairingCode: "pairing-token",
137 }).pipe(
138 Effect.provide(
139 Layer.mergeAll(
140 CLIENT_PRESENTATION_LAYER,
141 pairingHttpLayer(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }),
142 ),
143 ),
144 Effect.flip,
145 );
146 expect(error).toMatchObject({ reason: "unsupported" });
147 expect(calls.map((call) => call.url)).toEqual([
148 "https://remote.example.test/.well-known/t3/environment",
149 ]);
150 }),
151 );
152​
153 it.effect("pairs an outdated server so it can be updated from this client", () =>
154 Effect.gen(function* () {
155 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
156 const registration = yield* preparePairingRegistration({
157 host: "remote.example.test",
158 pairingCode: "pairing-token",
159 }).pipe(
160 Effect.provide(
161 Layer.mergeAll(
162 CLIENT_PRESENTATION_LAYER,
163 pairingHttpLayer(calls, {
164 protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1,
165 selfUpdate: true,
166 }),
167 ),
168 ),
169 );
170 expect(registration.target.environmentId).toBe("environment-paired");
171 expect(calls.map((call) => call.url)).toContain("https://remote.example.test/oauth/token");
172 }),
173 );
174​
175 it.effect("refuses an outdated server that cannot update itself", () =>
176 Effect.gen(function* () {
177 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
178 const error = yield* preparePairingRegistration({
179 host: "remote.example.test",
180 pairingCode: "pairing-token",
181 }).pipe(
182 Effect.provide(
183 Layer.mergeAll(
184 CLIENT_PRESENTATION_LAYER,
185 pairingHttpLayer(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1 }),
186 ),
187 ),
188 Effect.flip,
189 );
190 expect(error).toMatchObject({ reason: "unsupported" });
191 expect(error).not.toHaveProperty("serverUpdateRequired");
192 expect(calls.map((call) => call.url)).toEqual([
193 "https://remote.example.test/.well-known/t3/environment",
194 ]);
195 }),
196 );
197​
198 it.effect("does not consume a pairing credential when descriptor discovery fails", () =>
199 Effect.gen(function* () {
200 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
201​
202 yield* preparePairingRegistration({
203 host: "remote.example.test",
204 pairingCode: "pairing-token",
205 }).pipe(
206 Effect.provide(
207 Layer.mergeAll(
208 CLIENT_PRESENTATION_LAYER,
209 pairingHttpLayer(calls, { failDescriptor: true }),
210 ),
211 ),
212 Effect.flip,
213 );
214​
215 expect(calls.map((call) => call.url)).toEqual([
216 "https://remote.example.test/.well-known/t3/environment",
217 ]);
218 }),
219 );
220​
221 it.effect("rejects invalid pairing details before making a request", () =>
222 Effect.gen(function* () {
223 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
224 const error = yield* preparePairingRegistration({
225 host: "",
226 pairingCode: "",
227 }).pipe(
228 Effect.provide(Layer.mergeAll(CLIENT_PRESENTATION_LAYER, pairingHttpLayer(calls))),
229 Effect.flip,
230 );
231​
232 expect(error).toMatchObject({
233 _tag: "ConnectionBlockedError",
234 reason: "configuration",
235 message: "Enter a backend URL.",
236 });
237 expect(calls).toEqual([]);
238 }),
239 );
240​
241 it.effect("updates bearer metadata while preserving the credential and identity", () =>
242 Effect.gen(function* () {
243 const environmentId = EnvironmentId.make("environment-paired");
244 const registration = yield* prepareBearerConnectionUpdate({
245 input: {
246 environmentId,
247 label: " Renamed environment ",
248 httpBaseUrl: "http://100.65.180.100:3773/path",
249 },
250 entry: Option.some({
251 target: new BearerConnectionTarget({
252 environmentId,
253 label: "Old label",
254 connectionId: "bearer:environment-paired",
255 }),
256 profile: Option.some(
257 new BearerConnectionProfile({
258 connectionId: "bearer:environment-paired",
259 environmentId,
260 label: "Old label",
261 httpBaseUrl: "http://old.example.test/",
262 wsBaseUrl: "ws://old.example.test/",
263 }),
264 ),
265 enabled: true,
266 }),
267 credential: Option.some(new BearerConnectionCredential({ token: "bearer-token" })),
268 });
269​
270 expect(registration).toMatchObject({
271 target: {
272 environmentId,
273 label: "Renamed environment",
274 connectionId: "bearer:environment-paired",
275 },
276 profile: {
277 environmentId,
278 label: "Renamed environment",
279 httpBaseUrl: "http://100.65.180.100:3773/",
280 wsBaseUrl: "ws://100.65.180.100:3773/",
281 },
282 credential: { token: "bearer-token" },
283 });
284 }),
285 );
286​
287 it.effect("prepares an SSH registration from the provisioned platform environment", () =>
288 Effect.gen(function* () {
289 const target = {
290 alias: "devbox",
291 hostname: "devbox.example.test",
292 username: "developer",
293 port: 22,
294 };
295 const registration = yield* prepareSshRegistration({
296 target,
297 }).pipe(
298 Effect.provideService(
299 ClientCapabilities.SshEnvironmentGateway,
300 ClientCapabilities.SshEnvironmentGateway.of({
301 provision: () =>
302 Effect.succeed({
303 environmentId: EnvironmentId.make("environment-ssh"),
304 label: "Remote development box",
305 bootstrap: {
306 target,
307 httpBaseUrl: "http://127.0.0.1:3201",
308 wsBaseUrl: "ws://127.0.0.1:3201",
309 pairingToken: "pairing-token",
310 },
311 bearerToken: "bearer-token",
312 }),
313 prepare: () => Effect.die("unused"),
314 disconnect: () => Effect.die("unused"),
315 }),
316 ),
317 );
318​
319 expect(registration).toMatchObject({
320 _tag: "SshConnectionRegistration",
321 target: {
322 environmentId: "environment-ssh",
323 label: "Remote development box",
324 connectionId: "ssh:environment-ssh",
325 },
326 profile: {
327 environmentId: "environment-ssh",
328 label: "Remote development box",
329 connectionId: "ssh:environment-ssh",
330 target,
331 },
332 });
333 }),
334 );
335});