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

environmentHttpAuth.test.ts

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