Open History to see the last commit
1import {
2 AuthAdministrativeScopes,
3 AuthStandardClientScopes,
4 EnvironmentId,
5 type AuthEnvironmentScope,
6 ORCHESTRATION_PROTOCOL_VERSION,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12
13import * as RpcHttp from "../rpc/http.ts";
14import * as ClientCapabilities from "../platform/capabilities.ts";
15import { fetchRemoteSessionState } from "../authorization/remote.ts";
16import { BearerConnectionCredential, BearerConnectionProfile } from "./catalog.ts";
17import { BearerConnectionTarget } from "./model.ts";
18import {
19 prepareBearerConnectionUpdate,
20 preparePairingRegistration,
21 prepareSshRegistration,
22} from "./onboarding.ts";
23
24const layerClientPresentation = Layer.succeed(
25 ClientCapabilities.ClientPresentation,
26 ClientCapabilities.ClientPresentation.of({
27 metadata: {
28 label: "T3 Code Test",
29 deviceType: "desktop",
30 os: "Test OS",
31 },
32 }),
33);
34
35function layerPairingHttp(
36 calls: Array<{ readonly url: string; readonly init: RequestInit }>,
37 options?: {
38 readonly failDescriptor?: boolean;
39 readonly protocolVersion?: number;
40 readonly selfUpdate?: boolean;
41 readonly grantScopes?: ReadonlyArray<AuthEnvironmentScope>;
42 },
43) {
44 const grantScopes = options?.grantScopes ?? AuthStandardClientScopes;
45 let sessionScopes: ReadonlyArray<string> = [];
46 const fetchFn = ((input, init = {}) => {
47 const url = String(input);
48 calls.push({ url, init });
49
50 if (url.endsWith("/.well-known/t3/environment")) {
51 if (options?.failDescriptor === true) {
52 return Promise.resolve(
53 Response.json({ message: "descriptor unavailable" }, { status: 503 }),
54 );
55 }
56 return Promise.resolve(
57 Response.json({
58 environmentId: "environment-paired",
59 label: "Paired environment",
60 platform: {
61 os: "linux",
62 arch: "x64",
63 },
64 serverVersion: "0.0.0-test",
65 orchestrationProtocolVersion: options?.protocolVersion ?? ORCHESTRATION_PROTOCOL_VERSION,
66 capabilities: {
67 repositoryIdentity: true,
68 ...(options?.selfUpdate === true ? { serverSelfUpdate: "boot-service" } : {}),
69 },
70 }),
71 );
72 }
73
74 if (url.endsWith("/oauth/token")) {
75 const body =
76 init.body instanceof Uint8Array ? new TextDecoder().decode(init.body) : String(init.body);
77 const requestedScope = new URLSearchParams(body).get("scope");
78 sessionScopes = requestedScope === null ? grantScopes : requestedScope.split(" ");
79 if (!sessionScopes.every((scope) => grantScopes.some((granted) => granted === scope))) {
80 return Promise.resolve(
81 Response.json(
82 {
83 _tag: "EnvironmentRequestInvalidError",
84 code: "invalid_request",
85 reason: "scope_not_granted",
86 traceId: "pairing-scope-test",
87 },
88 { status: 400 },
89 ),
90 );
91 }
92 return Promise.resolve(
93 Response.json({
94 access_token: "bearer-token",
95 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
96 token_type: "Bearer",
97 expires_in: 3600,
98 scope: sessionScopes.join(" "),
99 }),
100 );
101 }
102
103 if (url.endsWith("/api/auth/session")) {
104 return Promise.resolve(
105 Response.json({
106 authenticated: true,
107 auth: {
108 policy: "remote-reachable",
109 bootstrapMethods: ["one-time-token"],
110 sessionMethods: ["bearer-access-token"],
111 sessionCookieName: "t3_session",
112 },
113 scopes: sessionScopes,
114 sessionMethod: "bearer-access-token",
115 }),
116 );
117 }
118
119 return Promise.reject(new Error(`Unexpected request: ${url}`));
120 }) satisfies typeof fetch;
121
122 return RpcHttp.layerRemoteHttpClient(fetchFn);
123}
124
125describe("connection onboarding", () => {
126 it.effect("prepares a persisted bearer registration from pairing details", () =>
127 Effect.gen(function* () {
128 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
129 const registration = yield* preparePairingRegistration({
130 host: "remote.example.test",
131 pairingCode: "pairing-token",
132 }).pipe(Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))));
133
134 expect(registration).toMatchObject({
135 _tag: "BearerConnectionRegistration",
136 target: {
137 environmentId: "environment-paired",
138 label: "Paired environment",
139 connectionId: "bearer:environment-paired:https://remote.example.test",
140 },
141 profile: {
142 environmentId: "environment-paired",
143 label: "Paired environment",
144 connectionId: "bearer:environment-paired:https://remote.example.test",
145 httpBaseUrl: "https://remote.example.test/",
146 wsBaseUrl: "wss://remote.example.test/",
147 },
148 credential: {
149 token: "bearer-token",
150 },
151 });
152 expect(calls.map((call) => call.url)).toEqual([
153 "https://remote.example.test/.well-known/t3/environment",
154 "https://remote.example.test/oauth/token",
155 ]);
156
157 const tokenRequest = calls.find((call) => call.url.endsWith("/oauth/token"));
158 const tokenBody =
159 tokenRequest?.init.body instanceof Uint8Array
160 ? new TextDecoder().decode(tokenRequest.init.body)
161 : String(tokenRequest?.init.body);
162 const tokenParams = new URLSearchParams(tokenBody);
163 expect(tokenParams.get("subject_token")).toBe("pairing-token");
164 expect(tokenParams.has("scope")).toBe(false);
165 expect(tokenParams.get("client_label")).toBe("T3 Code Test");
166 expect(tokenParams.get("client_device_type")).toBe("desktop");
167 expect(tokenParams.get("client_os")).toBe("Test OS");
168 }),
169 );
170
171 it.effect("rejects an incompatible server without consuming the pairing credential", () =>
172 Effect.gen(function* () {
173 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
174 const error = yield* preparePairingRegistration({
175 host: "remote.example.test",
176 pairingCode: "pairing-token",
177 }).pipe(
178 Effect.provide(
179 Layer.mergeAll(
180 layerClientPresentation,
181 layerPairingHttp(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }),
182 ),
183 ),
184 Effect.flip,
185 );
186 expect(error).toMatchObject({ reason: "unsupported" });
187 expect(calls.map((call) => call.url)).toEqual([
188 "https://remote.example.test/.well-known/t3/environment",
189 ]);
190 }),
191 );
192 it.effect.each([
193 { label: "read-only", scopes: ["orchestration:read"] },
194 { label: "administrative", scopes: AuthAdministrativeScopes },
195 ] as const)("preserves the $label grant when pairing a remote environment", ({ scopes }) =>
196 Effect.gen(function* () {
197 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
198 const httpLayer = layerPairingHttp(calls, { grantScopes: scopes });
199 const registration = yield* preparePairingRegistration({
200 host: "remote.example.test",
201 pairingCode: "pairing-token",
202 }).pipe(Effect.provide(Layer.mergeAll(layerClientPresentation, httpLayer)));
203
204 const session = yield* fetchRemoteSessionState({
205 httpBaseUrl: registration.profile.httpBaseUrl,
206 bearerToken: registration.credential.token,
207 }).pipe(Effect.provide(httpLayer));
208
209 expect(session.authenticated).toBe(true);
210 expect(session.scopes).toEqual(scopes);
211 }),
212 );
213
214 it.effect("refuses to add a route that reaches a different machine, keeping the code", () =>
215 Effect.gen(function* () {
216 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
217 const error = yield* preparePairingRegistration({
218 host: "remote.example.test",
219 pairingCode: "pairing-token",
220 expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
221 }).pipe(
222 Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))),
223 Effect.flip,
224 );
225 expect(error).toMatchObject({ reason: "configuration" });
226 expect(error.message).toContain("different machine");
227 expect(calls.map((call) => call.url)).toEqual([
228 "https://remote.example.test/.well-known/t3/environment",
229 ]);
230 }),
231 );
232
233 it.effect("pairs an outdated server so it can be updated from this client", () =>
234 Effect.gen(function* () {
235 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
236 const registration = yield* preparePairingRegistration({
237 host: "remote.example.test",
238 pairingCode: "pairing-token",
239 }).pipe(
240 Effect.provide(
241 Layer.mergeAll(
242 layerClientPresentation,
243 layerPairingHttp(calls, {
244 protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1,
245 selfUpdate: true,
246 }),
247 ),
248 ),
249 );
250 expect(registration.target.environmentId).toBe("environment-paired");
251 expect(calls.map((call) => call.url)).toContain("https://remote.example.test/oauth/token");
252 }),
253 );
254
255 it.effect("refuses an outdated server that cannot update itself", () =>
256 Effect.gen(function* () {
257 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
258 const error = yield* preparePairingRegistration({
259 host: "remote.example.test",
260 pairingCode: "pairing-token",
261 }).pipe(
262 Effect.provide(
263 Layer.mergeAll(
264 layerClientPresentation,
265 layerPairingHttp(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1 }),
266 ),
267 ),
268 Effect.flip,
269 );
270 expect(error).toMatchObject({ reason: "unsupported" });
271 expect(error).not.toHaveProperty("serverUpdateRequired");
272 expect(calls.map((call) => call.url)).toEqual([
273 "https://remote.example.test/.well-known/t3/environment",
274 ]);
275 }),
276 );
277
278 it.effect("does not consume a pairing credential when descriptor discovery fails", () =>
279 Effect.gen(function* () {
280 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
281
282 yield* preparePairingRegistration({
283 host: "remote.example.test",
284 pairingCode: "pairing-token",
285 }).pipe(
286 Effect.provide(
287 Layer.mergeAll(
288 layerClientPresentation,
289 layerPairingHttp(calls, { failDescriptor: true }),
290 ),
291 ),
292 Effect.flip,
293 );
294
295 expect(calls.map((call) => call.url)).toEqual([
296 "https://remote.example.test/.well-known/t3/environment",
297 ]);
298 }),
299 );
300
301 it.effect("rejects invalid pairing details before making a request", () =>
302 Effect.gen(function* () {
303 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
304 const error = yield* preparePairingRegistration({
305 host: "",
306 pairingCode: "",
307 }).pipe(
308 Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))),
309 Effect.flip,
310 );
311
312 expect(error).toMatchObject({
313 _tag: "ConnectionBlockedError",
314 reason: "configuration",
315 message: "Enter a backend URL.",
316 });
317 expect(calls).toEqual([]);
318 }),
319 );
320
321 it.effect("updates bearer metadata while preserving the credential and identity", () =>
322 Effect.gen(function* () {
323 const environmentId = EnvironmentId.make("environment-paired");
324 const registration = yield* prepareBearerConnectionUpdate({
325 input: {
326 environmentId,
327 label: " Renamed environment ",
328 httpBaseUrl: "http://100.65.180.100:3773/path",
329 },
330 entry: Option.some({
331 target: new BearerConnectionTarget({
332 environmentId,
333 label: "Old label",
334 connectionId: "bearer:environment-paired",
335 }),
336 profile: Option.some(
337 new BearerConnectionProfile({
338 connectionId: "bearer:environment-paired",
339 environmentId,
340 label: "Old label",
341 httpBaseUrl: "http://old.example.test/",
342 wsBaseUrl: "ws://old.example.test/",
343 }),
344 ),
345 enabled: true,
346 }),
347 credential: Option.some(new BearerConnectionCredential({ token: "bearer-token" })),
348 });
349
350 expect(registration).toMatchObject({
351 target: {
352 environmentId,
353 label: "Renamed environment",
354 connectionId: "bearer:environment-paired",
355 },
356 profile: {
357 environmentId,
358 label: "Renamed environment",
359 httpBaseUrl: "http://100.65.180.100:3773/",
360 wsBaseUrl: "ws://100.65.180.100:3773/",
361 },
362 credential: { token: "bearer-token" },
363 });
364 }),
365 );
366
367 it.effect("prepares an SSH registration from the provisioned platform environment", () =>
368 Effect.gen(function* () {
369 const target = {
370 alias: "devbox",
371 hostname: "devbox.example.test",
372 username: "developer",
373 port: 22,
374 };
375 const registration = yield* prepareSshRegistration({
376 target,
377 }).pipe(
378 Effect.provideService(
379 ClientCapabilities.SshEnvironmentGateway,
380 ClientCapabilities.SshEnvironmentGateway.of({
381 provision: () =>
382 Effect.succeed({
383 environmentId: EnvironmentId.make("environment-ssh"),
384 label: "Remote development box",
385 bootstrap: {
386 target,
387 httpBaseUrl: "http://127.0.0.1:3201",
388 wsBaseUrl: "ws://127.0.0.1:3201",
389 pairingToken: "pairing-token",
390 },
391 bearerToken: "bearer-token",
392 }),
393 prepare: () => Effect.die("unused"),
394 disconnect: () => Effect.die("unused"),
395 }),
396 ),
397 );
398
399 expect(registration).toMatchObject({
400 _tag: "SshConnectionRegistration",
401 target: {
402 environmentId: "environment-ssh",
403 label: "Remote development box",
404 connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
405 },
406 profile: {
407 environmentId: "environment-ssh",
408 label: "Remote development box",
409 connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
410 target,
411 },
412 });
413 }),
414 );
415});