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

environmentHttpAuth.test.ts

532 lines18.9 KB

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 );
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 };
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)("uses current relay authorization and endpoint for $name", (loader) =>
219 Effect.gen(function* () {
220 const harness = makeHarness(() => Response.json(loader.response));
221 const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
222​
223 expect(result).toEqual(loader.response);
224 expect(harness.calls).toHaveLength(1);
225 const call = harness.calls[0]!;
226 const url = new URL(call.url);
227 expect(url.origin).toBe(CURRENT_ORIGIN);
228 expect(url.pathname).toBe(loader.path);
229 expect(call.init.method).toBe(loader.method);
230 expect(new Headers(call.init.headers).get("authorization")).toBe("DPoP current-token");
231 expect(new Headers(call.init.headers).get("dpop")).toBe("proof-1");
232 expect(call.init.credentials).toBeUndefined();
233 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
234 expect(harness.proofs).toEqual([
235 {
236 method: loader.method,
237 url: `${CURRENT_ORIGIN}${loader.path}`,
238 accessToken: "current-token",
239 },
240 ]);
241 if (loader.name === "older thread history") {
242 expect(url.searchParams.get("turnLimit")).toBe("20");
243 expect(url.searchParams.get("beforeCursor")).toBe("older-page");
244 }
245 expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
246 }),
247 );
248​
249 it.effect("retries a rejected diff once with a new token, endpoint, and proof", () =>
250 Effect.gen(function* () {
251 const harness = makeHarness((requestNumber) =>
252 requestNumber === 1 ? credentialRejectedResponse() : Response.json(DIFF_RESULT),
253 );
254 const result = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
255 Effect.provide(harness.httpLayer),
256 );
257​
258 expect(result).toEqual(DIFF_RESULT);
259 expect(harness.authorizations).toEqual([
260 { expectedEnvironmentId: TARGET.environmentId },
261 { expectedEnvironmentId: TARGET.environmentId, rejectedAccessToken: "current-token" },
262 ]);
263 expect(harness.calls.map((call) => call.url)).toEqual([
264 `${CURRENT_ORIGIN}/api/pull-requests/diff`,
265 `${RENEWED_ORIGIN}/api/pull-requests/diff`,
266 ]);
267 expect(
268 harness.calls.map((call) => new Headers(call.init.headers).get("authorization")),
269 ).toEqual(["DPoP current-token", "DPoP renewed-token"]);
270 expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual([
271 "proof-1",
272 "proof-2",
273 ]);
274 expect(harness.proofs[1]).toEqual({
275 method: "POST",
276 url: `${RENEWED_ORIGIN}/api/pull-requests/diff`,
277 accessToken: "renewed-token",
278 });
279 expect(harness.calls[1]!.init.body).toEqual(harness.calls[0]!.init.body);
280 }),
281 );
282​
283 it.effect("uses the authorization service captured by the diff loader layer", () =>
284 Effect.gen(function* () {
285 const harness = makeHarness(() => Response.json(DIFF_RESULT));
286 const loaderLayer = pullRequestDiffLoaderLayer.pipe(
287 Layer.provide(
288 Layer.mergeAll(
289 harness.httpLayer,
290 Layer.succeed(ManagedRelayDpopSigner, Option.getOrThrow(harness.input.signer)),
291 Layer.succeed(RemoteEnvironmentAuthorization, harness.remoteAuthorization),
292 ),
293 ),
294 );
295 const loader = yield* PullRequestDiffLoader.pipe(Effect.provide(loaderLayer));
296 const result = yield* loader.load(PREPARED, DIFF);
297​
298 expect(result).toEqual(DIFF_RESULT);
299 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
300 "DPoP current-token",
301 );
302 }),
303 );
304​
305 it.effect("preserves the credential rejection after the one recovery attempt fails", () =>
306 Effect.gen(function* () {
307 const harness = makeHarness(() => credentialRejectedResponse());
308 const error = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
309 Effect.provide(harness.httpLayer),
310 Effect.flip,
311 );
312​
313 expect(error).toMatchObject({
314 _tag: "PullRequestDiffCredentialRejectedError",
315 traceId: "trace-rejected",
316 });
317 expect(harness.calls).toHaveLength(2);
318 expect(harness.authorizations).toHaveLength(2);
319 }),
320 );
321​
322 it.effect.each([
323 {
324 name: "insufficient scope",
325 reply: () =>
326 Response.json(
327 {
328 _tag: "EnvironmentScopeRequiredError",
329 code: "insufficient_scope",
330 requiredScope: "orchestration:read",
331 traceId: "trace-scope",
332 },
333 { status: 403 },
334 ),
335 errorTag: "EnvironmentScopeRequiredError",
336 },
337 {
338 name: "missing credential",
339 reply: () => credentialRejectedResponse("missing_credential"),
340 errorTag: "EnvironmentAuthInvalidError",
341 },
342 {
343 name: "Cloudflare 530",
344 reply: () => new Response("error code: 1033", { status: 530 }),
345 errorTag: "RemoteEnvironmentAuthUndeclaredStatusError",
346 },
347 {
348 name: "network failure",
349 reply: () => Promise.reject(new Error("Network unreachable")),
350 errorTag: "RemoteEnvironmentAuthFetchError",
351 },
352 ])("does not renew or retry on $name", ({ reply, errorTag }) =>
353 Effect.gen(function* () {
354 const harness = makeHarness(reply);
355 const error = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
356 Effect.provide(harness.httpLayer),
357 Effect.flip,
358 );
359​
360 expect(error._tag).toBe(errorTag);
361 expect(harness.calls).toHaveLength(1);
362 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
363 }),
364 );
365​
366 it.effect("recovers a session's unauthenticated 200 response before checking permissions", () =>
367 Effect.gen(function* () {
368 const harness = makeHarness((requestNumber) =>
369 Response.json(requestNumber === 1 ? UNAUTHENTICATED_SESSION : SESSION),
370 );
371 const result = yield* fetchEnvironmentSessionState(harness.input).pipe(
372 Effect.provide(harness.httpLayer),
373 );
374​
375 expect(result).toEqual(SESSION);
376 expect(harness.authorizations[1]).toEqual({
377 expectedEnvironmentId: TARGET.environmentId,
378 rejectedAccessToken: "current-token",
379 });
380 expect(harness.calls).toHaveLength(2);
381 }),
382 );
383​
384 it.effect("reports persistent session rejection instead of showing missing permissions", () =>
385 Effect.gen(function* () {
386 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
387 const error = yield* fetchEnvironmentSessionState(harness.input).pipe(
388 Effect.provide(harness.httpLayer),
389 Effect.flip,
390 );
391​
392 expect(error).toMatchObject({
393 _tag: "RemoteEnvironmentAuthFetchError",
394 message: "The environment rejected the renewed session authorization.",
395 });
396 expect(harness.calls).toHaveLength(2);
397 }),
398 );
399​
400 it.effect.each([
401 { name: "cookie", authorization: null },
402 { name: "bearer", authorization: { _tag: "Bearer", token: "bearer-token" } },
403 ] satisfies ReadonlyArray<{ name: string; authorization: PreparedHttpAuthorization | null }>)(
404 "leaves $name sessions unchanged without relay services",
405 ({ authorization }) =>
406 Effect.gen(function* () {
407 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
408 const result = yield* fetchEnvironmentSessionState({
409 prepared: { ...PREPARED, httpAuthorization: authorization },
410 signer: Option.none(),
411 }).pipe(Effect.provide(harness.httpLayer));
412​
413 expect(result).toEqual(UNAUTHENTICATED_SESSION);
414 expect(harness.calls).toHaveLength(1);
415 expect(harness.authorizations).toEqual([]);
416 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
417 authorization === null ? null : "Bearer bearer-token",
418 );
419 expect(harness.calls[0]!.init.credentials).toBe(
420 authorization === null ? "include" : undefined,
421 );
422 }),
423 );
424​
425 it.effect("keeps the caller's timeout while waiting for renewal", () =>
426 Effect.gen(function* () {
427 const harness = makeHarness(() => Response.json(SESSION));
428 const authorizing = yield* Deferred.make<void>();
429 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
430 ...harness.remoteAuthorization,
431 authorizeDpopHttp: () =>
432 Deferred.succeed(authorizing, undefined).pipe(Effect.andThen(Effect.never)),
433 });
434 const pending = yield* fetchEnvironmentSessionState({
435 ...harness.input,
436 remoteAuthorization: Option.some(remoteAuthorization),
437 timeoutMs: 100,
438 }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
439 yield* Deferred.await(authorizing);
440 yield* TestClock.adjust(100);
441​
442 expect(yield* Fiber.join(pending)).toMatchObject({
443 _tag: "RemoteEnvironmentAuthTimeoutError",
444 requestUrl: `${PREPARED.httpBaseUrl}/api/auth/session`,
445 timeoutMs: 100,
446 });
447 expect(harness.calls).toEqual([]);
448 }),
449 );
450​
451 it.effect("reports the current endpoint when the total timeout expires during HTTP", () =>
452 Effect.gen(function* () {
453 const requested = Promise.withResolvers<void>();
454 const response = Promise.withResolvers<Response>();
455 const harness = makeHarness(() => {
456 requested.resolve();
457 return response.promise;
458 });
459 const authorizing = yield* Deferred.make<void>();
460 const authorize = yield* Deferred.make<void>();
461 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
462 ...harness.remoteAuthorization,
463 authorizeDpopHttp: (input) =>
464 Deferred.succeed(authorizing, undefined).pipe(
465 Effect.andThen(Deferred.await(authorize)),
466 Effect.andThen(harness.remoteAuthorization.authorizeDpopHttp(input)),
467 ),
468 });
469 const pending = yield* fetchEnvironmentSessionState({
470 ...harness.input,
471 remoteAuthorization: Option.some(remoteAuthorization),
472 timeoutMs: 100,
473 }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
474 yield* Deferred.await(authorizing);
475 yield* TestClock.adjust(25);
476 yield* Deferred.succeed(authorize, undefined);
477 yield* Effect.promise(() => requested.promise);
478 yield* TestClock.adjust(75);
479​
480 expect(yield* Fiber.join(pending)).toMatchObject({
481 _tag: "RemoteEnvironmentAuthTimeoutError",
482 requestUrl: `${CURRENT_ORIGIN}/api/auth/session`,
483 timeoutMs: 100,
484 });
485 expect(harness.calls.map((call) => call.url)).toEqual([`${CURRENT_ORIGIN}/api/auth/session`]);
486 expect(harness.authorizations).toHaveLength(1);
487 response.resolve(Response.json(SESSION));
488 }),
489 );
490​
491 it.effect("reports renewal failure without sending the expired prepared token", () =>
492 Effect.gen(function* () {
493 const harness = makeHarness(() => Response.json(SESSION));
494 const failure = new ConnectionTransientError({
495 reason: "transport",
496 detail: "Relay unavailable",
497 });
498 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
499 ...harness.remoteAuthorization,
500 authorizeDpopHttp: () => Effect.fail(failure),
501 });
502 const error = yield* fetchEnvironmentSessionState({
503 ...harness.input,
504 remoteAuthorization: Option.some(remoteAuthorization),
505 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
506​
507 expect(error).toMatchObject({
508 _tag: "RemoteEnvironmentAuthFetchError",
509 message: "Could not authorize the environment request.",
510 cause: failure,
511 });
512 expect(harness.calls).toEqual([]);
513 expect(harness.proofs).toEqual([]);
514 }),
515 );
516​
517 it.effect("does not fall back to a captured DPoP token when authorization is unavailable", () =>
518 Effect.gen(function* () {
519 const harness = makeHarness(() => Response.json(SESSION));
520 const error = yield* fetchEnvironmentSessionState({
521 prepared: PREPARED,
522 signer: harness.input.signer,
523 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
524​
525 expect(error).toMatchObject({
526 _tag: "RemoteEnvironmentAuthFetchError",
527 message: "No relay authorization service is available for the environment request.",
528 });
529 expect(harness.calls).toEqual([]);
530 }),
531 );
532});