Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 EnvironmentId,
4 ProjectId,
5 ProviderInstanceId,
6 ThreadId,
7 type AuthSessionState,
8 type OrchestrationShellSnapshot,
9 type OrchestrationThreadDetailSnapshot,
10} from "@t3tools/contracts";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Fiber from "effect/Fiber";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import { TestClock } from "effect/testing";
17import type { HttpClient } from "effect/unstable/http";
18
19import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
20import {
21 ConnectionTransientError,
22 RelayConnectionTarget,
23 type PreparedConnection,
24 type PreparedHttpAuthorization,
25} from "../connection/model.ts";
26import { ManagedRelayDpopSigner, type ManagedRelayDpopProofInput } from "../relay/managedRelay.ts";
27import { remoteHttpClientLayer, type RemoteEnvironmentRequestError } from "../rpc/http.ts";
28import {
29 fetchEnvironmentPullRequestDiff,
30 type PullRequestDiffCredentialRejectedError,
31 PullRequestDiffLoader,
32 pullRequestDiffLoaderLayer,
33} from "./pullRequestDiffHttp.ts";
34import { fetchEnvironmentSessionState } from "./session.ts";
35import { fetchEnvironmentShellSnapshot } from "./shellSnapshotHttp.ts";
36import { fetchEnvironmentThreadSnapshot } from "./threadSnapshotHttp.ts";
37
38const TARGET = new RelayConnectionTarget({
39 environmentId: EnvironmentId.make("environment-1"),
40 label: "Remote environment",
41});
42const PREPARED: PreparedConnection = {
43 environmentId: TARGET.environmentId,
44 label: TARGET.label,
45 httpBaseUrl: "https://previous.example.test",
46 socketUrl: "wss://previous.example.test/ws",
47 httpAuthorization: { _tag: "Dpop", accessToken: "expired-token", expiresAtEpochMs: 0 },
48 target: TARGET,
49};
50const CURRENT_ORIGIN = "https://current.example.test";
51const RENEWED_ORIGIN = "https://renewed.example.test";
52const DIFF = {
53 projectId: ProjectId.make("project-1"),
54 repository: "owner/repository",
55 number: 42,
56};
57const DIFF_RESULT = { patch: "diff --git a/file.ts b/file.ts", truncated: false, nextCursor: null };
58const AUTH = {
59 policy: "remote-reachable",
60 bootstrapMethods: ["one-time-token"],
61 sessionMethods: ["dpop-access-token"],
62 sessionCookieName: "t3_session",
63} satisfies AuthSessionState["auth"];
64const SESSION = {
65 authenticated: true,
66 auth: AUTH,
67 scopes: ["orchestration:read", "orchestration:operate"],
68 sessionMethod: "dpop-access-token",
69} satisfies AuthSessionState;
70const UNAUTHENTICATED_SESSION = { authenticated: false, auth: AUTH } satisfies AuthSessionState;
71const SHELL = {
72 snapshotSequence: 1,
73 projects: [],
74 threads: [],
75 updatedAt: "2026-09-04T00:00:00.000Z",
76} satisfies OrchestrationShellSnapshot;
77const THREAD = {
78 snapshotSequence: 2,
79 thread: {
80 id: ThreadId.make("thread-1"),
81 projectId: ProjectId.make("project-1"),
82 title: "Thread",
83 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
84 runtimeMode: "full-access",
85 interactionMode: "default",
86 branch: null,
87 pullRequests: [],
88 worktreePath: null,
89 latestTurn: null,
90 createdAt: "2026-09-04T00:00:00.000Z",
91 updatedAt: "2026-09-04T00:00:00.000Z",
92 archivedAt: null,
93 settledOverride: null,
94 settledAt: null,
95 deletedAt: null,
96 messages: [],
97 proposedPlans: [],
98 activities: [],
99 checkpoints: [],
100 session: null,
101 },
102 page: { beforeCursor: null, hasMore: false, snapshotSequence: 2 },
103} satisfies OrchestrationThreadDetailSnapshot;
104
105function credentialRejectedResponse(reason = "invalid_credential") {
106 return Response.json(
107 {
108 _tag: "EnvironmentAuthInvalidError",
109 code: "auth_invalid",
110 reason,
111 traceId: "trace-rejected",
112 },
113 { status: 401 },
114 );
115}
116
117function makeHarness(reply: (requestNumber: number) => Response | Promise<Response>) {
118 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
119 const authorizations: Array<
120 Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0]
121 > = [];
122 const proofs: Array<ManagedRelayDpopProofInput> = [];
123 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
124 authorizeBearer: () => Effect.die("Unexpected bearer connection preparation."),
125 authorizeDpop: () => Effect.die("HTTP requests must not prepare a WebSocket connection."),
126 authorizeDpopHttp: (input) =>
127 Effect.sync(() => {
128 authorizations.push(input);
129 const rejected = input.rejectedAccessToken !== undefined;
130 return {
131 environmentId: TARGET.environmentId,
132 label: TARGET.label,
133 httpBaseUrl: rejected ? RENEWED_ORIGIN : CURRENT_ORIGIN,
134 httpAuthorization: {
135 _tag: "Dpop" as const,
136 accessToken: rejected ? "renewed-token" : "current-token",
137 expiresAtEpochMs: 3_600_000,
138 },
139 };
140 }),
141 });
142 const signer = ManagedRelayDpopSigner.of({
143 thumbprint: Effect.succeed("test-thumbprint"),
144 createProof: (input) =>
145 Effect.sync(() => {
146 proofs.push(input);
147 return `proof-${proofs.length}`;
148 }),
149 });
150 const fetchFn: typeof fetch = async (request, init) => {
151 calls.push({ url: String(request), init: init ?? {} });
152 return reply(calls.length);
153 };
154 return {
155 calls,
156 authorizations,
157 proofs,
158 remoteAuthorization,
159 input: {
160 prepared: PREPARED,
161 signer: Option.some(signer),
162 remoteAuthorization: Option.some(remoteAuthorization),
163 },
164 httpLayer: remoteHttpClientLayer(fetchFn),
165 };
166}
167
168type HttpInput = ReturnType<typeof makeHarness>["input"];
169const LOADERS: ReadonlyArray<{
170 readonly name: string;
171 readonly method: string;
172 readonly path: string;
173 readonly response: unknown;
174 readonly load: (
175 input: HttpInput,
176 ) => Effect.Effect<
177 unknown,
178 RemoteEnvironmentRequestError | PullRequestDiffCredentialRejectedError,
179 HttpClient.HttpClient
180 >;
181}> = [
182 {
183 name: "PR diff",
184 method: "POST",
185 path: "/api/pull-requests/diff",
186 response: DIFF_RESULT,
187 load: (input: HttpInput) => fetchEnvironmentPullRequestDiff({ ...input, diff: DIFF }),
188 },
189 {
190 name: "session permissions",
191 method: "GET",
192 path: "/api/auth/session",
193 response: SESSION,
194 load: fetchEnvironmentSessionState,
195 },
196 {
197 name: "shell snapshot",
198 method: "GET",
199 path: "/api/orchestration/shell",
200 response: SHELL,
201 load: fetchEnvironmentShellSnapshot,
202 },
203 {
204 name: "older thread history",
205 method: "GET",
206 path: "/api/orchestration/threads/thread-1",
207 response: THREAD,
208 load: (input: HttpInput) =>
209 fetchEnvironmentThreadSnapshot({
210 ...input,
211 threadId: THREAD.thread.id,
212 window: { turnLimit: 20, beforeCursor: "older-page" },
213 }),
214 },
215];
216
217describe("authenticated environment HTTP requests", () => {
218 it.effect.each(LOADERS)("rejects an invalid $name response", (loader) =>
219 Effect.gen(function* () {
220 const harness = makeHarness(() => Response.json({}));
221 const result = yield* loader
222 .load(harness.input)
223 .pipe(Effect.provide(harness.httpLayer), Effect.asVoid, Effect.flip);
224 expect(result._tag).toBe("RemoteEnvironmentAuthInvalidJsonError");
225 expect(harness.calls).toHaveLength(1);
226 }),
227 );
228
229 it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
230 Effect.gen(function* () {
231 const harness = makeHarness(() => Response.json(loader.response));
232 const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
233
234 expect(result).toEqual(loader.response);
235 expect(harness.calls).toHaveLength(1);
236 const call = harness.calls[0]!;
237 const url = new URL(call.url);
238 expect(url.origin).toBe(CURRENT_ORIGIN);
239 expect(url.pathname).toBe(loader.path);
240 expect(call.init.method).toBe(loader.method);
241 expect(new Headers(call.init.headers).get("authorization")).toBe("DPoP current-token");
242 expect(new Headers(call.init.headers).get("dpop")).toBe("proof-1");
243 expect(call.init.credentials).toBeUndefined();
244 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
245 expect(harness.proofs).toEqual([
246 {
247 method: loader.method,
248 url: `${CURRENT_ORIGIN}${loader.path}`,
249 accessToken: "current-token",
250 },
251 ]);
252 if (loader.name === "older thread history") {
253 expect(url.searchParams.get("turnLimit")).toBe("20");
254 expect(url.searchParams.get("beforeCursor")).toBe("older-page");
255 }
256 expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
257 }),
258 );
259
260 it.effect("retries a rejected diff once with a new token, endpoint, and proof", () =>
261 Effect.gen(function* () {
262 const harness = makeHarness((requestNumber) =>
263 requestNumber === 1 ? credentialRejectedResponse() : Response.json(DIFF_RESULT),
264 );
265 const result = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
266 Effect.provide(harness.httpLayer),
267 );
268
269 expect(result).toEqual(DIFF_RESULT);
270 expect(harness.authorizations).toEqual([
271 { expectedEnvironmentId: TARGET.environmentId },
272 { expectedEnvironmentId: TARGET.environmentId, rejectedAccessToken: "current-token" },
273 ]);
274 expect(harness.calls.map((call) => call.url)).toEqual([
275 `${CURRENT_ORIGIN}/api/pull-requests/diff`,
276 `${RENEWED_ORIGIN}/api/pull-requests/diff`,
277 ]);
278 expect(
279 harness.calls.map((call) => new Headers(call.init.headers).get("authorization")),
280 ).toEqual(["DPoP current-token", "DPoP renewed-token"]);
281 expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual([
282 "proof-1",
283 "proof-2",
284 ]);
285 expect(harness.proofs[1]).toEqual({
286 method: "POST",
287 url: `${RENEWED_ORIGIN}/api/pull-requests/diff`,
288 accessToken: "renewed-token",
289 });
290 expect(harness.calls[1]!.init.body).toEqual(harness.calls[0]!.init.body);
291 }),
292 );
293
294 it.effect("uses the authorization service captured by the diff loader layer", () =>
295 Effect.gen(function* () {
296 const harness = makeHarness(() => Response.json(DIFF_RESULT));
297 const loaderLayer = pullRequestDiffLoaderLayer.pipe(
298 Layer.provide(
299 Layer.mergeAll(
300 harness.httpLayer,
301 Layer.succeed(ManagedRelayDpopSigner, Option.getOrThrow(harness.input.signer)),
302 Layer.succeed(RemoteEnvironmentAuthorization, harness.remoteAuthorization),
303 ),
304 ),
305 );
306 const loader = yield* PullRequestDiffLoader.pipe(Effect.provide(loaderLayer));
307 const result = yield* loader.load(PREPARED, DIFF);
308
309 expect(result).toEqual(DIFF_RESULT);
310 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
311 "DPoP current-token",
312 );
313 }),
314 );
315
316 it.effect("preserves the credential rejection after the one recovery attempt fails", () =>
317 Effect.gen(function* () {
318 const harness = makeHarness(() => credentialRejectedResponse());
319 const error = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
320 Effect.provide(harness.httpLayer),
321 Effect.flip,
322 );
323
324 expect(error).toMatchObject({
325 _tag: "PullRequestDiffCredentialRejectedError",
326 traceId: "trace-rejected",
327 });
328 expect(harness.calls).toHaveLength(2);
329 expect(harness.authorizations).toHaveLength(2);
330 }),
331 );
332
333 it.effect.each([
334 {
335 name: "insufficient scope",
336 reply: () =>
337 Response.json(
338 {
339 _tag: "EnvironmentScopeRequiredError",
340 code: "insufficient_scope",
341 requiredScope: "orchestration:read",
342 traceId: "trace-scope",
343 },
344 { status: 403 },
345 ),
346 errorTag: "EnvironmentScopeRequiredError",
347 },
348 {
349 name: "missing credential",
350 reply: () => credentialRejectedResponse("missing_credential"),
351 errorTag: "EnvironmentAuthInvalidError",
352 },
353 {
354 name: "Cloudflare 530",
355 reply: () => new Response("error code: 1033", { status: 530 }),
356 errorTag: "RemoteEnvironmentAuthUndeclaredStatusError",
357 },
358 {
359 name: "network failure",
360 reply: () => Promise.reject(new Error("Network unreachable")),
361 errorTag: "RemoteEnvironmentAuthFetchError",
362 },
363 ])("does not renew or retry on $name", ({ reply, errorTag }) =>
364 Effect.gen(function* () {
365 const harness = makeHarness(reply);
366 const error = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
367 Effect.provide(harness.httpLayer),
368 Effect.flip,
369 );
370
371 expect(error._tag).toBe(errorTag);
372 expect(harness.calls).toHaveLength(1);
373 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
374 }),
375 );
376
377 it.effect("recovers a session's unauthenticated 200 response before checking permissions", () =>
378 Effect.gen(function* () {
379 const harness = makeHarness((requestNumber) =>
380 Response.json(requestNumber === 1 ? UNAUTHENTICATED_SESSION : SESSION),
381 );
382 const result = yield* fetchEnvironmentSessionState(harness.input).pipe(
383 Effect.provide(harness.httpLayer),
384 );
385
386 expect(result).toEqual(SESSION);
387 expect(harness.authorizations[1]).toEqual({
388 expectedEnvironmentId: TARGET.environmentId,
389 rejectedAccessToken: "current-token",
390 });
391 expect(harness.calls).toHaveLength(2);
392 }),
393 );
394
395 it.effect("reports persistent session rejection instead of showing missing permissions", () =>
396 Effect.gen(function* () {
397 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
398 const error = yield* fetchEnvironmentSessionState(harness.input).pipe(
399 Effect.provide(harness.httpLayer),
400 Effect.flip,
401 );
402
403 expect(error).toMatchObject({
404 _tag: "RemoteEnvironmentAuthFetchError",
405 message: "The environment rejected the renewed session authorization.",
406 });
407 expect(harness.calls).toHaveLength(2);
408 }),
409 );
410
411 it.effect.each([
412 { name: "cookie", authorization: null },
413 { name: "bearer", authorization: { _tag: "Bearer", token: "bearer-token" } },
414 ] satisfies ReadonlyArray<{ name: string; authorization: PreparedHttpAuthorization | null }>)(
415 "leaves $name sessions unchanged without relay services",
416 ({ authorization }) =>
417 Effect.gen(function* () {
418 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
419 const result = yield* fetchEnvironmentSessionState({
420 prepared: { ...PREPARED, httpAuthorization: authorization },
421 signer: Option.none(),
422 }).pipe(Effect.provide(harness.httpLayer));
423
424 expect(result).toEqual(UNAUTHENTICATED_SESSION);
425 expect(harness.calls).toHaveLength(1);
426 expect(harness.authorizations).toEqual([]);
427 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
428 authorization === null ? null : "Bearer bearer-token",
429 );
430 expect(harness.calls[0]!.init.credentials).toBe(
431 authorization === null ? "include" : undefined,
432 );
433 }),
434 );
435
436 it.effect("keeps the caller's timeout while waiting for renewal", () =>
437 Effect.gen(function* () {
438 const harness = makeHarness(() => Response.json(SESSION));
439 const authorizing = yield* Deferred.make<void>();
440 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
441 ...harness.remoteAuthorization,
442 authorizeDpopHttp: () =>
443 Deferred.succeed(authorizing, undefined).pipe(Effect.andThen(Effect.never)),
444 });
445 const pending = yield* fetchEnvironmentSessionState({
446 ...harness.input,
447 remoteAuthorization: Option.some(remoteAuthorization),
448 timeoutMs: 100,
449 }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
450 yield* Deferred.await(authorizing);
451 yield* TestClock.adjust(100);
452
453 expect(yield* Fiber.join(pending)).toMatchObject({
454 _tag: "RemoteEnvironmentAuthTimeoutError",
455 requestUrl: `${PREPARED.httpBaseUrl}/api/auth/session`,
456 timeoutMs: 100,
457 });
458 expect(harness.calls).toEqual([]);
459 }),
460 );
461
462 it.effect("reports the current endpoint when the total timeout expires during HTTP", () =>
463 Effect.gen(function* () {
464 const requested = Promise.withResolvers<void>();
465 const response = Promise.withResolvers<Response>();
466 const harness = makeHarness(() => {
467 requested.resolve();
468 return response.promise;
469 });
470 const authorizing = yield* Deferred.make<void>();
471 const authorize = yield* Deferred.make<void>();
472 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
473 ...harness.remoteAuthorization,
474 authorizeDpopHttp: (input) =>
475 Deferred.succeed(authorizing, undefined).pipe(
476 Effect.andThen(Deferred.await(authorize)),
477 Effect.andThen(harness.remoteAuthorization.authorizeDpopHttp(input)),
478 ),
479 });
480 const pending = yield* fetchEnvironmentSessionState({
481 ...harness.input,
482 remoteAuthorization: Option.some(remoteAuthorization),
483 timeoutMs: 100,
484 }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
485 yield* Deferred.await(authorizing);
486 yield* TestClock.adjust(25);
487 yield* Deferred.succeed(authorize, undefined);
488 yield* Effect.promise(() => requested.promise);
489 yield* TestClock.adjust(75);
490
491 expect(yield* Fiber.join(pending)).toMatchObject({
492 _tag: "RemoteEnvironmentAuthTimeoutError",
493 requestUrl: `${CURRENT_ORIGIN}/api/auth/session`,
494 timeoutMs: 100,
495 });
496 expect(harness.calls.map((call) => call.url)).toEqual([`${CURRENT_ORIGIN}/api/auth/session`]);
497 expect(harness.authorizations).toHaveLength(1);
498 response.resolve(Response.json(SESSION));
499 }),
500 );
501
502 it.effect("reports renewal failure without sending the expired prepared token", () =>
503 Effect.gen(function* () {
504 const harness = makeHarness(() => Response.json(SESSION));
505 const failure = new ConnectionTransientError({
506 reason: "transport",
507 detail: "Relay unavailable",
508 });
509 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
510 ...harness.remoteAuthorization,
511 authorizeDpopHttp: () => Effect.fail(failure),
512 });
513 const error = yield* fetchEnvironmentSessionState({
514 ...harness.input,
515 remoteAuthorization: Option.some(remoteAuthorization),
516 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
517
518 expect(error).toMatchObject({
519 _tag: "RemoteEnvironmentAuthFetchError",
520 message: "Could not authorize the environment request.",
521 cause: failure,
522 });
523 expect(harness.calls).toEqual([]);
524 expect(harness.proofs).toEqual([]);
525 }),
526 );
527
528 it.effect("does not fall back to a captured DPoP token when authorization is unavailable", () =>
529 Effect.gen(function* () {
530 const harness = makeHarness(() => Response.json(SESSION));
531 const error = yield* fetchEnvironmentSessionState({
532 prepared: PREPARED,
533 signer: harness.input.signer,
534 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
535
536 expect(error).toMatchObject({
537 _tag: "RemoteEnvironmentAuthFetchError",
538 message: "No relay authorization service is available for the environment request.",
539 });
540 expect(harness.calls).toEqual([]);
541 }),
542 );
543});