Open History to see the last commit
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 exchangeRemoteDpopAccessToken,
12 fetchRemoteDpopSessionState,
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("allows a client to explicitly narrow a pairing grant", () =>
213 Effect.gen(function* () {
214 const fetch = recordedFetch(
215 Response.json(
216 {
217 access_token: "read-only-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 );
226
227 yield* bootstrapRemoteBearerSession({
228 httpBaseUrl: "https://remote.example.com/",
229 credential: "pairing-token",
230 scopes: ["orchestration:read"],
231 }).pipe(provideRemoteHttp(fetch.fetchFn));
232
233 expectFetchCall(fetch.calls, 1, {
234 url: "https://remote.example.com/oauth/token",
235 method: "POST",
236 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",
237 });
238 }),
239 );
240
241 it.effect("loads remote session state and websocket tickets over bearer auth", () =>
242 Effect.gen(function* () {
243 const fetch = recordedFetch(
244 Response.json(
245 {
246 environmentId: "environment-remote",
247 label: "Remote environment",
248 platform: {
249 os: "linux",
250 arch: "x64",
251 },
252 serverVersion: "0.0.0-test",
253 capabilities: {
254 repositoryIdentity: true,
255 },
256 },
257 { status: 200 },
258 ),
259 Response.json(
260 {
261 authenticated: true,
262 auth: {
263 policy: "remote-reachable",
264 bootstrapMethods: ["one-time-token"],
265 sessionMethods: ["browser-session-cookie", "bearer-access-token"],
266 sessionCookieName: "t3_session",
267 },
268 scopes: [
269 "orchestration:read",
270 "orchestration:operate",
271 "terminal:operate",
272 "review:write",
273 "relay:read",
274 ],
275 sessionMethod: "bearer-access-token",
276 expiresAt: "2026-05-01T12:00:00.000Z",
277 },
278 { status: 200 },
279 ),
280 Response.json(
281 {
282 ticket: "ws-ticket",
283 expiresAt: "2026-05-01T12:05:00.000Z",
284 },
285 { status: 200 },
286 ),
287 );
288
289 const environment = yield* fetchRemoteEnvironmentDescriptor({
290 httpBaseUrl: "https://remote.example.com/",
291 }).pipe(provideRemoteHttp(fetch.fetchFn));
292 expect(environment).toMatchObject({
293 environmentId: "environment-remote",
294 label: "Remote environment",
295 });
296
297 const session = yield* fetchRemoteSessionState({
298 httpBaseUrl: "https://remote.example.com/",
299 bearerToken: "bearer-token",
300 }).pipe(provideRemoteHttp(fetch.fetchFn));
301 expect(session).toMatchObject({
302 authenticated: true,
303 scopes: [
304 "orchestration:read",
305 "orchestration:operate",
306 "terminal:operate",
307 "review:write",
308 "relay:read",
309 ],
310 });
311
312 const ticket = yield* issueRemoteWebSocketTicket({
313 httpBaseUrl: "https://remote.example.com/",
314 bearerToken: "bearer-token",
315 }).pipe(provideRemoteHttp(fetch.fetchFn));
316 expect(ticket).toMatchObject({
317 ticket: "ws-ticket",
318 });
319
320 expectFetchCall(fetch.calls, 1, {
321 url: "https://remote.example.com/.well-known/t3/environment",
322 method: "GET",
323 });
324 expectFetchCall(fetch.calls, 2, {
325 url: "https://remote.example.com/api/auth/session",
326 method: "GET",
327 headers: {
328 authorization: "Bearer bearer-token",
329 },
330 });
331 expectFetchCall(fetch.calls, 3, {
332 url: "https://remote.example.com/api/auth/websocket-ticket",
333 method: "POST",
334 headers: {
335 authorization: "Bearer bearer-token",
336 },
337 });
338 }),
339 );
340
341 it.effect("loads remote session state with a DPoP-bound access token", () =>
342 Effect.gen(function* () {
343 const fetch = recordedFetch(
344 Response.json({
345 authenticated: true,
346 auth: {
347 policy: "remote-reachable",
348 bootstrapMethods: ["one-time-token"],
349 sessionMethods: ["dpop-access-token"],
350 sessionCookieName: "t3_session",
351 },
352 sessionMethod: "dpop-access-token",
353 scopes: [
354 "orchestration:read",
355 "orchestration:operate",
356 "terminal:operate",
357 "review:write",
358 ],
359 expiresAt: "2026-05-01T12:00:00.000Z",
360 }),
361 );
362
363 yield* fetchRemoteDpopSessionState({
364 httpBaseUrl: "https://remote.example.com/",
365 accessToken: "dpop-access-token",
366 dpopProof: "dpop-proof",
367 }).pipe(provideRemoteHttp(fetch.fetchFn));
368
369 expectFetchCall(fetch.calls, 1, {
370 url: "https://remote.example.com/api/auth/session",
371 method: "GET",
372 headers: {
373 authorization: "DPoP dpop-access-token",
374 dpop: "dpop-proof",
375 },
376 });
377 }),
378 );
379
380 it.effect("fails hung fetch requests on the configured timeout", () =>
381 Effect.gen(function* () {
382 const fetch = hangingFetch();
383
384 const errorFiber = yield* fetchRemoteEnvironmentDescriptor({
385 httpBaseUrl: "http://remote.example.com/",
386 timeoutMs: 25,
387 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip, Effect.forkScoped);
388 yield* Effect.yieldNow;
389 yield* TestClock.adjust(Duration.millis(25));
390 const error = yield* Fiber.join(errorFiber);
391
392 expect(error).toBeInstanceOf(RemoteEnvironmentAuthTimeoutError);
393 expect(error.message).toBe(
394 "Remote environment endpoint http://remote.example.com/.well-known/t3/environment timed out after 25ms.",
395 );
396 }).pipe(Effect.provide(TestClock.layer())),
397 );
398
399 it.effect("revives declared typed errors from remote auth failures", () =>
400 Effect.gen(function* () {
401 const fetch = recordedFetch(
402 Response.json(
403 {
404 _tag: "EnvironmentAuthInvalidError",
405 code: "auth_invalid",
406 reason: "missing_credential",
407 traceId: "trace-auth-test",
408 },
409 { status: 401 },
410 ),
411 );
412
413 const error = yield* issueRemoteWebSocketTicket({
414 httpBaseUrl: "https://remote.example.com/",
415 bearerToken: "expired-token",
416 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
417
418 expect(isEnvironmentAuthInvalidError(error)).toBe(true);
419 if (isEnvironmentAuthInvalidError(error)) {
420 expect(error.reason).toBe("missing_credential");
421 expect(error.traceId).toBe("trace-auth-test");
422 }
423 }),
424 );
425
426 it.effect("classifies malformed successful remote auth responses as invalid responses", () =>
427 Effect.gen(function* () {
428 const fetch = recordedFetch(
429 Response.json(
430 {
431 access_token: "",
432 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
433 token_type: "Bearer",
434 expires_in: 3600,
435 scope:
436 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
437 },
438 { status: 200 },
439 ),
440 );
441
442 const error = yield* bootstrapRemoteBearerSession({
443 httpBaseUrl: "https://remote.example.com/",
444 credential: "pairing-token",
445 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
446
447 expect(error).toBeInstanceOf(RemoteEnvironmentAuthInvalidJsonError);
448 expect(error.message).toBe(
449 "Remote environment endpoint returned an invalid response from https://remote.example.com/oauth/token.",
450 );
451 }),
452 );
453
454 it.effect("mints a websocket url that targets the rpc route with a short-lived ticket", () =>
455 Effect.gen(function* () {
456 const fetch = recordedFetch(
457 Response.json(
458 {
459 ticket: "ws-ticket",
460 expiresAt: "2026-05-01T12:05:00.000Z",
461 },
462 { status: 200 },
463 ),
464 );
465
466 const url = yield* resolveRemoteWebSocketConnectionUrl({
467 wsBaseUrl: "wss://remote.example.com/",
468 httpBaseUrl: "https://remote.example.com/",
469 bearerToken: "bearer-token",
470 }).pipe(provideRemoteHttp(fetch.fetchFn));
471
472 expect(url).toBe("wss://remote.example.com/ws?wsTicket=ws-ticket");
473 }),
474 );
475});