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

environmentHttpAuth.test.ts

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