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

remote.test.ts

386 lines12.5 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 bootstrapRemoteBearerSession,
11 fetchRemoteEnvironmentDescriptor,
12 fetchRemoteSessionState,
13 issueRemoteWebSocketTicket,
14 remoteHttpClientLayer,
15 RemoteEnvironmentAuthInvalidJsonError,
16 RemoteEnvironmentAuthTimeoutError,
17 resolveRemoteWebSocketConnectionUrl,
18} from "./remote.ts";
19​
20const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
21​
22type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
23​
24const recordedFetch = (...responses: ReadonlyArray<Response>) => {
25 const calls: Array<FetchCall> = [];
26 let responseIndex = 0;
27 const fetchFn = ((input, init) => {
28 calls.push([input, init ?? {}]);
29 const response = responses[responseIndex++];
30 if (!response) {
31 return Promise.reject(new Error("Unexpected fetch call"));
32 }
33 return Promise.resolve(response);
34 }) satisfies typeof fetch;
35​
36 return { fetchFn, calls };
37};
38​
39const hangingFetch = () => {
40 const calls: Array<FetchCall> = [];
41 const fetchFn = ((input, init) => {
42 calls.push([input, init ?? {}]);
43 return new Promise<Response>(() => undefined);
44 }) satisfies typeof fetch;
45​
46 return { fetchFn, calls };
47};
48​
49const provideRemoteHttp = (fetchFn: typeof fetch) => Effect.provide(remoteHttpClientLayer(fetchFn));
50​
51const expectFetchCall = (
52 calls: ReadonlyArray<FetchCall>,
53 index: number,
54 expected: {
55 readonly url: string;
56 readonly method: string;
57 readonly headers?: Record<string, string>;
58 readonly body?: string;
59 },
60): void => {
61 const call = calls[index - 1];
62 expect(call).toBeDefined();
63 if (!call) {
64 return;
65 }
66​
67 const [url, init] = call;
68 expect(String(url)).toBe(expected.url);
69 expect(init).toEqual(
70 expect.objectContaining({
71 method: expected.method,
72 }),
73 );
74 expect(init.headers).toEqual(expect.objectContaining(expected.headers ?? {}));
75​
76 if ("body" in expected) {
77 const body = init.body;
78 if (typeof body === "string") {
79 expect(body).toBe(expected.body);
80 } else if (body instanceof Uint8Array) {
81 expect(new TextDecoder().decode(body)).toBe(expected.body);
82 } else {
83 throw new Error("Expected fetch request body");
84 }
85 }
86};
87​
88describe("remote", () => {
89 it.effect("bootstraps bearer auth against a remote backend", () =>
90 Effect.gen(function* () {
91 const fetch = recordedFetch(
92 Response.json(
93 {
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:
99 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
100 },
101 { status: 200 },
102 ),
103 );
104​
105 const result = yield* bootstrapRemoteBearerSession({
106 httpBaseUrl: "https://remote.example.com/",
107 credential: "pairing-token",
108 }).pipe(provideRemoteHttp(fetch.fetchFn));
109​
110 expect(result).toMatchObject({
111 token_type: "Bearer",
112 access_token: "bearer-token",
113 scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",
114 });
115 expectFetchCall(fetch.calls, 1, {
116 url: "https://remote.example.com/oauth/token",
117 method: "POST",
118 headers: {
119 "content-type": "application/x-www-form-urlencoded",
120 },
121 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",
122 });
123 }),
124 );
125​
126 it.effect("submits optional client display metadata during bearer token exchange", () =>
127 Effect.gen(function* () {
128 const fetch = recordedFetch(
129 Response.json(
130 {
131 access_token: "bearer-token",
132 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
133 token_type: "Bearer",
134 expires_in: 3600,
135 scope:
136 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
137 },
138 { status: 200 },
139 ),
140 );
141​
142 yield* bootstrapRemoteBearerSession({
143 httpBaseUrl: "https://remote.example.com/",
144 credential: "pairing-token",
145 clientMetadata: {
146 label: "T3 Code Mobile",
147 deviceType: "mobile",
148 os: "iOS",
149 },
150 }).pipe(provideRemoteHttp(fetch.fetchFn));
151​
152 expectFetchCall(fetch.calls, 1, {
153 url: "https://remote.example.com/oauth/token",
154 method: "POST",
155 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",
156 });
157 }),
158 );
159​
160 it.effect("allows a client to explicitly narrow a pairing grant", () =>
161 Effect.gen(function* () {
162 const fetch = recordedFetch(
163 Response.json(
164 {
165 access_token: "read-only-token",
166 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
167 token_type: "Bearer",
168 expires_in: 3600,
169 scope: "orchestration:read",
170 },
171 { status: 200 },
172 ),
173 );
174​
175 yield* bootstrapRemoteBearerSession({
176 httpBaseUrl: "https://remote.example.com/",
177 credential: "pairing-token",
178 scopes: ["orchestration:read"],
179 }).pipe(provideRemoteHttp(fetch.fetchFn));
180​
181 expectFetchCall(fetch.calls, 1, {
182 url: "https://remote.example.com/oauth/token",
183 method: "POST",
184 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",
185 });
186 }),
187 );
188​
189 it.effect("loads remote session state and websocket tokens over bearer auth", () =>
190 Effect.gen(function* () {
191 const fetch = recordedFetch(
192 Response.json(
193 {
194 environmentId: "environment-remote",
195 label: "Remote environment",
196 platform: {
197 os: "linux",
198 arch: "x64",
199 },
200 serverVersion: "0.0.0-test",
201 capabilities: {
202 repositoryIdentity: true,
203 },
204 },
205 { status: 200 },
206 ),
207 Response.json(
208 {
209 authenticated: true,
210 auth: {
211 policy: "remote-reachable",
212 bootstrapMethods: ["one-time-token"],
213 sessionMethods: ["browser-session-cookie", "bearer-access-token"],
214 sessionCookieName: "t3_session",
215 },
216 scopes: [
217 "orchestration:read",
218 "orchestration:operate",
219 "terminal:operate",
220 "review:write",
221 "relay:read",
222 ],
223 sessionMethod: "bearer-access-token",
224 expiresAt: "2026-05-01T12:00:00.000Z",
225 },
226 { status: 200 },
227 ),
228 Response.json(
229 {
230 ticket: "ws-ticket",
231 expiresAt: "2026-05-01T12:05:00.000Z",
232 },
233 { status: 200 },
234 ),
235 );
236​
237 const environment = yield* fetchRemoteEnvironmentDescriptor({
238 httpBaseUrl: "https://remote.example.com/",
239 }).pipe(provideRemoteHttp(fetch.fetchFn));
240 expect(environment).toMatchObject({
241 environmentId: "environment-remote",
242 label: "Remote environment",
243 });
244​
245 const session = yield* fetchRemoteSessionState({
246 httpBaseUrl: "https://remote.example.com/",
247 bearerToken: "bearer-token",
248 }).pipe(provideRemoteHttp(fetch.fetchFn));
249 expect(session).toMatchObject({
250 authenticated: true,
251 scopes: [
252 "orchestration:read",
253 "orchestration:operate",
254 "terminal:operate",
255 "review:write",
256 "relay:read",
257 ],
258 });
259​
260 const token = yield* issueRemoteWebSocketTicket({
261 httpBaseUrl: "https://remote.example.com/",
262 bearerToken: "bearer-token",
263 }).pipe(provideRemoteHttp(fetch.fetchFn));
264 expect(token).toMatchObject({
265 ticket: "ws-ticket",
266 });
267​
268 expectFetchCall(fetch.calls, 1, {
269 url: "https://remote.example.com/.well-known/t3/environment",
270 method: "GET",
271 });
272 expectFetchCall(fetch.calls, 2, {
273 url: "https://remote.example.com/api/auth/session",
274 method: "GET",
275 headers: {
276 authorization: "Bearer bearer-token",
277 },
278 });
279 expectFetchCall(fetch.calls, 3, {
280 url: "https://remote.example.com/api/auth/websocket-ticket",
281 method: "POST",
282 headers: {
283 authorization: "Bearer bearer-token",
284 },
285 });
286 }),
287 );
288​
289 it.effect("fails hung fetch requests on the configured timeout", () =>
290 Effect.gen(function* () {
291 const fetch = hangingFetch();
292​
293 const errorFiber = yield* fetchRemoteEnvironmentDescriptor({
294 httpBaseUrl: "http://remote.example.com/",
295 timeoutMs: 25,
296 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip, Effect.forkScoped);
297 yield* Effect.yieldNow;
298 yield* TestClock.adjust(Duration.millis(25));
299 const error = yield* Fiber.join(errorFiber);
300​
301 expect(error).toBeInstanceOf(RemoteEnvironmentAuthTimeoutError);
302 expect(error.message).toBe(
303 "Remote auth endpoint http://remote.example.com/.well-known/t3/environment timed out after 25ms.",
304 );
305 }).pipe(Effect.provide(TestClock.layer())),
306 );
307​
308 it.effect("revives declared typed errors from remote auth failures", () =>
309 Effect.gen(function* () {
310 const fetch = recordedFetch(
311 Response.json(
312 {
313 _tag: "EnvironmentAuthInvalidError",
314 code: "auth_invalid",
315 reason: "missing_credential",
316 traceId: "trace-auth-test",
317 },
318 { status: 401 },
319 ),
320 );
321​
322 const error = yield* issueRemoteWebSocketTicket({
323 httpBaseUrl: "https://remote.example.com/",
324 bearerToken: "expired-token",
325 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
326​
327 expect(isEnvironmentAuthInvalidError(error)).toBe(true);
328 if (isEnvironmentAuthInvalidError(error)) {
329 expect(error.reason).toBe("missing_credential");
330 expect(error.traceId).toBe("trace-auth-test");
331 }
332 }),
333 );
334​
335 it.effect("classifies malformed successful remote auth responses as invalid responses", () =>
336 Effect.gen(function* () {
337 const fetch = recordedFetch(
338 Response.json(
339 {
340 access_token: "",
341 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
342 token_type: "Bearer",
343 expires_in: 3600,
344 scope:
345 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
346 },
347 { status: 200 },
348 ),
349 );
350​
351 const error = yield* bootstrapRemoteBearerSession({
352 httpBaseUrl: "https://remote.example.com/",
353 credential: "pairing-token",
354 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
355​
356 expect(error).toBeInstanceOf(RemoteEnvironmentAuthInvalidJsonError);
357 expect(error.message).toBe(
358 "Remote auth endpoint returned an invalid response from https://remote.example.com/oauth/token.",
359 );
360 }),
361 );
362​
363 it.effect(
364 "mints a websocket url that targets the rpc route with a short-lived websocket ticket",
365 () =>
366 Effect.gen(function* () {
367 const fetch = recordedFetch(
368 Response.json(
369 {
370 ticket: "ws-ticket",
371 expiresAt: "2026-05-01T12:05:00.000Z",
372 },
373 { status: 200 },
374 ),
375 );
376​
377 const url = yield* resolveRemoteWebSocketConnectionUrl({
378 wsBaseUrl: "wss://remote.example.com/",
379 httpBaseUrl: "https://remote.example.com/",
380 bearerToken: "bearer-token",
381 }).pipe(provideRemoteHttp(fetch.fetchFn));
382​
383 expect(url).toBe("wss://remote.example.com/ws?wsTicket=ws-ticket");
384 }),
385 );
386});