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

remote.test.ts

488 lines16.4 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Schema from "effect/Schema";
6import * as TestClock from "effect/testing/TestClock";
7​
8import { EnvironmentAuthInvalidError } from "@t3tools/contracts";
9import {
10 appendClientConnectionParams,
11 bootstrapRemoteBearerSession,
12 exchangeRemoteDpopAccessToken,
13 fetchRemoteSessionState,
14 issueRemoteDpopWebSocketTicket,
15 issueRemoteWebSocketTicket,
16 RemoteEnvironmentAuthInvalidJsonError,
17 RemoteEnvironmentAuthTimeoutError,
18 resolveRemoteWebSocketConnectionUrl,
19} from "./remote.ts";
20import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
21import { remoteHttpClientLayer } from "../rpc/http.ts";
22​
23const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
24​
25type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
26​
27const recordedFetch = (...responses: ReadonlyArray<Response>) => {
28 const calls: Array<FetchCall> = [];
29 let responseIndex = 0;
30 const fetchFn = ((input, init) => {
31 calls.push([input, init ?? {}]);
32 const response = responses[responseIndex++];
33 if (!response) {
34 return Promise.reject(new Error("Unexpected fetch call"));
35 }
36 return Promise.resolve(response);
37 }) satisfies typeof fetch;
38​
39 return { fetchFn, calls };
40};
41​
42const hangingFetch = () => {
43 const calls: Array<FetchCall> = [];
44 const fetchFn = ((input, init) => {
45 calls.push([input, init ?? {}]);
46 return new Promise<Response>(() => undefined);
47 }) satisfies typeof fetch;
48​
49 return { fetchFn, calls };
50};
51​
52const provideRemoteHttp = (fetchFn: typeof fetch) => Effect.provide(remoteHttpClientLayer(fetchFn));
53​
54const expectFetchCall = (
55 calls: ReadonlyArray<FetchCall>,
56 index: number,
57 expected: {
58 readonly url: string;
59 readonly method: string;
60 readonly headers?: Record<string, string>;
61 readonly body?: string;
62 },
63): void => {
64 const call = calls[index - 1];
65 expect(call).toBeDefined();
66 if (!call) {
67 return;
68 }
69​
70 const [url, init] = call;
71 expect(String(url)).toBe(expected.url);
72 expect(init).toEqual(
73 expect.objectContaining({
74 method: expected.method,
75 }),
76 );
77 expect(init.headers).toEqual(expect.objectContaining(expected.headers ?? {}));
78​
79 if ("body" in expected) {
80 const body = init.body;
81 if (typeof body === "string") {
82 expect(body).toBe(expected.body);
83 } else if (body instanceof Uint8Array) {
84 expect(new TextDecoder().decode(body)).toBe(expected.body);
85 } else {
86 throw new Error("Expected fetch request body");
87 }
88 }
89};
90​
91describe("remote environment authorization", () => {
92 it.effect("bootstraps bearer auth against a remote backend", () =>
93 Effect.gen(function* () {
94 const fetch = recordedFetch(
95 Response.json(
96 {
97 access_token: "bearer-token",
98 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
99 token_type: "Bearer",
100 expires_in: 3600,
101 scope:
102 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
103 },
104 { status: 200 },
105 ),
106 );
107​
108 const result = yield* bootstrapRemoteBearerSession({
109 httpBaseUrl: "https://remote.example.com/",
110 credential: "pairing-token",
111 }).pipe(provideRemoteHttp(fetch.fetchFn));
112​
113 expect(result).toMatchObject({
114 token_type: "Bearer",
115 access_token: "bearer-token",
116 scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",
117 });
118 expectFetchCall(fetch.calls, 1, {
119 url: "https://remote.example.com/oauth/token",
120 method: "POST",
121 headers: {
122 "content-type": "application/x-www-form-urlencoded",
123 },
124 body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token",
125 });
126 }),
127 );
128​
129 it.effect("exchanges managed credentials and admits websocket requests with DPoP", () =>
130 Effect.gen(function* () {
131 const fetch = recordedFetch(
132 Response.json({
133 access_token: "dpop-access-token",
134 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
135 token_type: "DPoP",
136 expires_in: 3600,
137 scope: "orchestration:read orchestration:operate terminal:operate review:write",
138 }),
139 Response.json({
140 ticket: "ws-ticket",
141 expiresAt: "2026-05-01T12:05:00.000Z",
142 }),
143 );
144​
145 const token = yield* exchangeRemoteDpopAccessToken({
146 httpBaseUrl: "https://remote.example.com/",
147 credential: "one-time-credential",
148 dpopProof: "token-proof",
149 clientMetadata: {
150 label: "T3 Code Mobile",
151 deviceType: "mobile",
152 os: "iOS",
153 },
154 }).pipe(provideRemoteHttp(fetch.fetchFn));
155 yield* issueRemoteDpopWebSocketTicket({
156 httpBaseUrl: "https://remote.example.com/",
157 accessToken: token.access_token,
158 dpopProof: "resource-proof",
159 }).pipe(provideRemoteHttp(fetch.fetchFn));
160​
161 expectFetchCall(fetch.calls, 1, {
162 url: "https://remote.example.com/oauth/token",
163 method: "POST",
164 headers: { dpop: "token-proof", "content-type": "application/x-www-form-urlencoded" },
165 body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=one-time-credential&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&client_label=T3+Code+Mobile&client_device_type=mobile&client_os=iOS",
166 });
167 expectFetchCall(fetch.calls, 2, {
168 url: "https://remote.example.com/api/auth/websocket-ticket",
169 method: "POST",
170 headers: {
171 authorization: "DPoP dpop-access-token",
172 dpop: "resource-proof",
173 },
174 });
175 }),
176 );
177​
178 it.effect("submits optional client display metadata during bearer token exchange", () =>
179 Effect.gen(function* () {
180 const fetch = recordedFetch(
181 Response.json(
182 {
183 access_token: "bearer-token",
184 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
185 token_type: "Bearer",
186 expires_in: 3600,
187 scope:
188 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
189 },
190 { status: 200 },
191 ),
192 );
193​
194 yield* bootstrapRemoteBearerSession({
195 httpBaseUrl: "https://remote.example.com/",
196 credential: "pairing-token",
197 clientMetadata: {
198 label: "T3 Code Mobile",
199 deviceType: "mobile",
200 os: "iOS",
201 },
202 }).pipe(provideRemoteHttp(fetch.fetchFn));
203​
204 expectFetchCall(fetch.calls, 1, {
205 url: "https://remote.example.com/oauth/token",
206 method: "POST",
207 body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&client_label=T3+Code+Mobile&client_device_type=mobile&client_os=iOS",
208 });
209 }),
210 );
211​
212 it.effect("keeps OS sentinels in telemetry but out of display metadata", () =>
213 Effect.gen(function* () {
214 const tokenResponse = () =>
215 Response.json(
216 {
217 access_token: "bearer-token",
218 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
219 token_type: "Bearer",
220 expires_in: 3600,
221 scope: "orchestration:read",
222 },
223 { status: 200 },
224 );
225 const fetch = recordedFetch(tokenResponse(), tokenResponse());
226​
227 for (const os of ["unknown", "other"] as const) {
228 yield* bootstrapRemoteBearerSession({
229 httpBaseUrl: "https://remote.example.com/",
230 credential: "pairing-token",
231 clientMetadata: {
232 label: "T3 Code Web",
233 deviceType: "desktop",
234 os,
235 },
236 }).pipe(provideRemoteHttp(fetch.fetchFn));
237 }
238​
239 for (const [, init] of fetch.calls) {
240 expect(String(init.body)).not.toContain("client_os=");
241 }
242​
243 const websocketUrl = new URL("wss://remote.example.com/ws");
244 appendClientConnectionParams(websocketUrl, {
245 surface: "web",
246 deviceType: "desktop",
247 os: "unknown",
248 });
249 expect(websocketUrl.searchParams.get("clientOs")).toBe("unknown");
250 }),
251 );
252​
253 it.effect("allows a client to explicitly narrow a pairing grant", () =>
254 Effect.gen(function* () {
255 const fetch = recordedFetch(
256 Response.json(
257 {
258 access_token: "read-only-token",
259 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
260 token_type: "Bearer",
261 expires_in: 3600,
262 scope: "orchestration:read",
263 },
264 { status: 200 },
265 ),
266 );
267​
268 yield* bootstrapRemoteBearerSession({
269 httpBaseUrl: "https://remote.example.com/",
270 credential: "pairing-token",
271 scopes: ["orchestration:read"],
272 }).pipe(provideRemoteHttp(fetch.fetchFn));
273​
274 expectFetchCall(fetch.calls, 1, {
275 url: "https://remote.example.com/oauth/token",
276 method: "POST",
277 body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&scope=orchestration%3Aread",
278 });
279 }),
280 );
281​
282 it.effect("loads remote session state and websocket tickets over bearer auth", () =>
283 Effect.gen(function* () {
284 const fetch = recordedFetch(
285 Response.json(
286 {
287 environmentId: "environment-remote",
288 label: "Remote environment",
289 platform: {
290 os: "linux",
291 arch: "x64",
292 },
293 serverVersion: "0.0.0-test",
294 capabilities: {
295 repositoryIdentity: true,
296 },
297 },
298 { status: 200 },
299 ),
300 Response.json(
301 {
302 authenticated: true,
303 auth: {
304 policy: "remote-reachable",
305 bootstrapMethods: ["one-time-token"],
306 sessionMethods: ["browser-session-cookie", "bearer-access-token"],
307 sessionCookieName: "t3_session",
308 },
309 scopes: [
310 "orchestration:read",
311 "orchestration:operate",
312 "terminal:operate",
313 "review:write",
314 "relay:read",
315 ],
316 sessionMethod: "bearer-access-token",
317 expiresAt: "2026-05-01T12:00:00.000Z",
318 },
319 { status: 200 },
320 ),
321 Response.json(
322 {
323 ticket: "ws-ticket",
324 expiresAt: "2026-05-01T12:05:00.000Z",
325 },
326 { status: 200 },
327 ),
328 );
329​
330 const environment = yield* fetchRemoteEnvironmentDescriptor({
331 httpBaseUrl: "https://remote.example.com/",
332 }).pipe(provideRemoteHttp(fetch.fetchFn));
333 expect(environment).toMatchObject({
334 environmentId: "environment-remote",
335 label: "Remote environment",
336 });
337​
338 const session = yield* fetchRemoteSessionState({
339 httpBaseUrl: "https://remote.example.com/",
340 bearerToken: "bearer-token",
341 }).pipe(provideRemoteHttp(fetch.fetchFn));
342 expect(session).toMatchObject({
343 authenticated: true,
344 scopes: [
345 "orchestration:read",
346 "orchestration:operate",
347 "terminal:operate",
348 "review:write",
349 "relay:read",
350 ],
351 });
352​
353 const ticket = yield* issueRemoteWebSocketTicket({
354 httpBaseUrl: "https://remote.example.com/",
355 bearerToken: "bearer-token",
356 }).pipe(provideRemoteHttp(fetch.fetchFn));
357 expect(ticket).toMatchObject({
358 ticket: "ws-ticket",
359 });
360​
361 expectFetchCall(fetch.calls, 1, {
362 url: "https://remote.example.com/.well-known/t3/environment",
363 method: "GET",
364 });
365 expectFetchCall(fetch.calls, 2, {
366 url: "https://remote.example.com/api/auth/session",
367 method: "GET",
368 headers: {
369 authorization: "Bearer bearer-token",
370 },
371 });
372 expectFetchCall(fetch.calls, 3, {
373 url: "https://remote.example.com/api/auth/websocket-ticket",
374 method: "POST",
375 headers: {
376 authorization: "Bearer bearer-token",
377 },
378 });
379 }),
380 );
381​
382 it.effect("fails hung fetch requests on the configured timeout", () =>
383 Effect.gen(function* () {
384 const fetch = hangingFetch();
385​
386 const errorFiber = yield* fetchRemoteEnvironmentDescriptor({
387 httpBaseUrl: "http://remote.example.com/",
388 timeoutMs: 25,
389 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip, Effect.forkScoped);
390 yield* Effect.yieldNow;
391 yield* TestClock.adjust(Duration.millis(25));
392 const error = yield* Fiber.join(errorFiber);
393​
394 expect(error).toBeInstanceOf(RemoteEnvironmentAuthTimeoutError);
395 expect(error.message).toBe(
396 "Remote environment endpoint http://remote.example.com/.well-known/t3/environment timed out after 25ms.",
397 );
398 }).pipe(Effect.provide(TestClock.layer())),
399 );
400​
401 it.effect("revives declared typed errors from remote auth failures", () =>
402 Effect.gen(function* () {
403 const fetch = recordedFetch(
404 Response.json(
405 {
406 _tag: "EnvironmentAuthInvalidError",
407 code: "auth_invalid",
408 reason: "missing_credential",
409 traceId: "trace-auth-test",
410 },
411 { status: 401 },
412 ),
413 );
414​
415 const error = yield* issueRemoteWebSocketTicket({
416 httpBaseUrl: "https://remote.example.com/",
417 bearerToken: "expired-token",
418 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
419​
420 expect(isEnvironmentAuthInvalidError(error)).toBe(true);
421 if (isEnvironmentAuthInvalidError(error)) {
422 expect(error.reason).toBe("missing_credential");
423 expect(error.traceId).toBe("trace-auth-test");
424 }
425 }),
426 );
427​
428 it.effect("classifies malformed successful remote auth responses as invalid responses", () =>
429 Effect.gen(function* () {
430 const fetch = recordedFetch(
431 Response.json(
432 {
433 access_token: "",
434 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
435 token_type: "Bearer",
436 expires_in: 3600,
437 scope:
438 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
439 },
440 { status: 200 },
441 ),
442 );
443​
444 const error = yield* bootstrapRemoteBearerSession({
445 httpBaseUrl: "https://remote.example.com/",
446 credential: "pairing-token",
447 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
448​
449 expect(error).toBeInstanceOf(RemoteEnvironmentAuthInvalidJsonError);
450 expect(error.message).toBe(
451 "Remote environment endpoint returned an invalid response from https://remote.example.com/oauth/token.",
452 );
453 }),
454 );
455​
456 it.effect("mints a websocket url that targets the rpc route with a short-lived ticket", () =>
457 Effect.gen(function* () {
458 const fetch = recordedFetch(
459 Response.json(
460 {
461 ticket: "ws-ticket",
462 expiresAt: "2026-05-01T12:05:00.000Z",
463 },
464 { status: 200 },
465 ),
466 );
467​
468 const url = yield* resolveRemoteWebSocketConnectionUrl({
469 wsBaseUrl: "wss://remote.example.com/",
470 httpBaseUrl: "https://remote.example.com/",
471 bearerToken: "bearer-token",
472 clientMetadata: {
473 surface: "mobile",
474 appVersion: "1.2.3",
475 deviceType: "mobile",
476 os: "Android",
477 osMajorVersion: 15,
478 deviceModel: "Pixel 9",
479 },
480 connectionMethod: "relay",
481 }).pipe(provideRemoteHttp(fetch.fetchFn));
482​
483 expect(url).toBe(
484 "wss://remote.example.com/ws?wsTicket=ws-ticket&clientSurface=mobile&clientAppVersion=1.2.3&clientDeviceType=phone&clientOs=Android&clientOsMajorVersion=15&clientDeviceModel=Pixel+9&connectionMethod=relay",
485 );
486 }),
487 );
488});