Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 EnvironmentId,
4 ORCHESTRATION_PROTOCOL_HEADER,
5 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
6 ProjectId,
7 ThreadId,
8 type AuthSessionState,
9 type OrchestrationV2ShellSnapshot,
10 OrchestrationV2ThreadDetailSnapshot,
11 OrchestrationV2ThreadBoundedSnapshot,
12 OrchestrationV2ThreadTranscript,
13 type OrchestrationV2ThreadHistoryPage,
14} from "@t3tools/contracts";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Schema from "effect/Schema";
22import * as TestClock from "effect/testing/TestClock";
23import type { HttpClient } from "effect/http";
24
25import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
26import {
27 ConnectionTransientError,
28 RelayConnectionTarget,
29 type PreparedConnection,
30 type PreparedHttpAuthorization,
31} from "../connection/model.ts";
32import * as ManagedRelay from "../relay/managedRelay.ts";
33import { type RemoteEnvironmentRequestError } from "../rpc/http.ts";
34import * as RpcHttp from "../rpc/http.ts";
35import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
36import { fetchEnvironmentSessionState } from "./session.ts";
37import { fetchEnvironmentShellSnapshot } from "./shellSnapshotHttp.ts";
38import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
39import { fetchEnvironmentThreadTranscript } from "./threadTranscriptHttp.ts";
40import { fetchEnvironmentBoundedThreadSnapshot } from "./boundedThreadSnapshotHttp.ts";
41import * as BoundedThreadSnapshotHttp from "./boundedThreadSnapshotHttp.ts";
42import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts";
43import { v2Projection } from "./orchestrationV2TestFixtures.ts";
44
45const encodeThreadSnapshot = Schema.encodeSync(OrchestrationV2ThreadDetailSnapshot);
46const encodeBoundedSnapshot = Schema.encodeSync(OrchestrationV2ThreadBoundedSnapshot);
47const encodeThreadTranscript = Schema.encodeSync(OrchestrationV2ThreadTranscript);
48
49const TARGET = new RelayConnectionTarget({
50 environmentId: EnvironmentId.make("environment-1"),
51 label: "Remote environment",
52});
53const PREPARED: PreparedConnection = {
54 environmentId: TARGET.environmentId,
55 label: TARGET.label,
56 httpBaseUrl: "https://previous.example.test",
57 socketUrl: "wss://previous.example.test/ws",
58 httpAuthorization: { _tag: "Dpop", accessToken: "expired-token", expiresAtEpochMs: 0 },
59 target: TARGET,
60};
61const CURRENT_ORIGIN = "https://current.example.test";
62const RENEWED_ORIGIN = "https://renewed.example.test";
63const DIFF = {
64 projectId: ProjectId.make("project-1"),
65 repository: "owner/repository",
66 number: 42,
67};
68const DIFF_RESULT = { patch: "diff --git a/file.ts b/file.ts", truncated: false, nextCursor: null };
69const AUTH = {
70 policy: "remote-reachable",
71 bootstrapMethods: ["one-time-token"],
72 sessionMethods: ["dpop-access-token"],
73 sessionCookieName: "t3_session",
74} satisfies AuthSessionState["auth"];
75const SESSION = {
76 authenticated: true,
77 auth: AUTH,
78 scopes: ["orchestration:read", "orchestration:operate"],
79 sessionMethod: "dpop-access-token",
80} satisfies AuthSessionState;
81const UNAUTHENTICATED_SESSION = { authenticated: false, auth: AUTH } satisfies AuthSessionState;
82const SHELL = {
83 schemaVersion: 1,
84 snapshotSequence: 1,
85 projects: [],
86 threads: [],
87 archivedThreads: [],
88} satisfies OrchestrationV2ShellSnapshot;
89const THREAD = {
90 snapshotSequence: 2,
91 projection: v2Projection,
92} satisfies OrchestrationV2ThreadDetailSnapshot;
93const TRANSCRIPT = {
94 threadId: v2Projection.thread.id,
95 title: v2Projection.thread.title,
96 updatedAt: v2Projection.updatedAt,
97 items: v2Projection.visibleTurnItems,
98} satisfies OrchestrationV2ThreadTranscript;
99const BOUNDED_THREAD = {
100 ...THREAD,
101 historyCursor: "older-page",
102 hasMoreHistory: true,
103 latestLocalTurnOrdinal: 3,
104} satisfies OrchestrationV2ThreadBoundedSnapshot;
105const THREAD_HISTORY = {
106 snapshotSequence: 2,
107 items: [],
108 nextCursor: null,
109 hasMoreHistory: false,
110} satisfies OrchestrationV2ThreadHistoryPage;
111
112function credentialRejectedResponse(reason = "invalid_credential") {
113 return Response.json(
114 {
115 _tag: "EnvironmentAuthInvalidError",
116 code: "auth_invalid",
117 reason,
118 traceId: "trace-rejected",
119 },
120 { status: 401 },
121 );
122}
123
124function makeHarness(reply: (requestNumber: number) => Response | Promise<Response>) {
125 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
126 const authorizations: Array<
127 Parameters<
128 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]
129 >[0]
130 > = [];
131 const proofs: Array<ManagedRelay.ManagedRelayDpopProofInput> = [];
132 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
133 authorizeBearer: () => Effect.die("Unexpected bearer connection preparation."),
134 authorizeDpop: () => Effect.die("HTTP requests must not prepare a WebSocket connection."),
135 authorizeDpopHttp: (input) =>
136 Effect.sync(() => {
137 authorizations.push(input);
138 const rejected = input.rejectedAccessToken !== undefined;
139 return {
140 environmentId: TARGET.environmentId,
141 label: TARGET.label,
142 httpBaseUrl: rejected ? RENEWED_ORIGIN : CURRENT_ORIGIN,
143 httpAuthorization: {
144 _tag: "Dpop" as const,
145 accessToken: rejected ? "renewed-token" : "current-token",
146 expiresAtEpochMs: 3_600_000,
147 },
148 };
149 }),
150 });
151 const signer = ManagedRelay.ManagedRelayDpopSigner.of({
152 thumbprint: Effect.succeed("test-thumbprint"),
153 createProof: (input) =>
154 Effect.sync(() => {
155 proofs.push(input);
156 return `proof-${proofs.length}`;
157 }),
158 });
159 const fetchFn: typeof fetch = async (request, init) => {
160 calls.push({ url: String(request), init: init ?? {} });
161 return reply(calls.length);
162 };
163 return {
164 calls,
165 authorizations,
166 proofs,
167 remoteAuthorization,
168 input: {
169 prepared: PREPARED,
170 signer: Option.some(signer),
171 remoteAuthorization: Option.some(remoteAuthorization),
172 },
173 httpLayer: RpcHttp.layerRemoteHttpClient(fetchFn),
174 };
175}
176
177// Resolves "settled" instead of hanging when the load finishes without sending another request.
178function nextRequestOrSettled(requests: Queue.Queue<number>, load: Fiber.Fiber<unknown, unknown>) {
179 return Effect.raceFirst(
180 Queue.take(requests).pipe(Effect.as("sent" as const)),
181 Fiber.await(load).pipe(Effect.as("settled" as const)),
182 );
183}
184
185type HttpInput = ReturnType<typeof makeHarness>["input"];
186const LOADERS: ReadonlyArray<{
187 readonly name: string;
188 readonly method: string;
189 readonly path: string;
190 readonly response: unknown;
191 readonly expected: unknown;
192 readonly load: (
193 input: HttpInput,
194 ) => Effect.Effect<
195 unknown,
196 RemoteEnvironmentRequestError | PullRequestDiffLoader.PullRequestDiffCredentialRejectedError,
197 HttpClient.HttpClient
198 >;
199}> = [
200 {
201 name: "PR diff",
202 method: "POST",
203 path: "/api/pull-requests/diff",
204 response: DIFF_RESULT,
205 expected: DIFF_RESULT,
206 load: (input: HttpInput) =>
207 PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({ ...input, diff: DIFF }),
208 },
209 {
210 name: "session permissions",
211 method: "GET",
212 path: "/api/auth/session",
213 response: SESSION,
214 expected: SESSION,
215 load: fetchEnvironmentSessionState,
216 },
217 {
218 name: "shell snapshot",
219 method: "GET",
220 path: "/api/orchestration/shell",
221 response: SHELL,
222 expected: SHELL,
223 load: (input: HttpInput) =>
224 fetchEnvironmentShellSnapshot(input).pipe(
225 Effect.map(({ loadPullRequests: _links, ...snapshot }) => snapshot),
226 ),
227 },
228 {
229 name: "thread snapshot",
230 method: "GET",
231 path: `/api/orchestration/threads/${THREAD.projection.thread.id}`,
232 response: encodeThreadSnapshot(THREAD),
233 expected: THREAD,
234 load: (input: HttpInput) =>
235 ThreadSnapshotLoader.fetchEnvironmentThreadSnapshot({
236 ...input,
237 threadId: THREAD.projection.thread.id,
238 }),
239 },
240 {
241 name: "thread transcript",
242 method: "GET",
243 path: `/api/orchestration/threads/${TRANSCRIPT.threadId}/transcript`,
244 response: encodeThreadTranscript(TRANSCRIPT),
245 expected: TRANSCRIPT,
246 load: (input: HttpInput) =>
247 fetchEnvironmentThreadTranscript({ ...input, threadId: TRANSCRIPT.threadId }),
248 },
249 {
250 name: "bounded thread snapshot",
251 method: "GET",
252 path: `/api/orchestration/threads/${THREAD.projection.thread.id}/bounded`,
253 response: encodeBoundedSnapshot(BOUNDED_THREAD),
254 expected: BOUNDED_THREAD,
255 load: (input: HttpInput) =>
256 fetchEnvironmentBoundedThreadSnapshot({ ...input, threadId: THREAD.projection.thread.id }),
257 },
258 {
259 name: "older thread history",
260 method: "GET",
261 path: `/api/orchestration/threads/${THREAD.projection.thread.id}/history`,
262 response: THREAD_HISTORY,
263 expected: THREAD_HISTORY,
264 load: (input: HttpInput) =>
265 fetchEnvironmentThreadHistoryPage({
266 ...input,
267 threadId: THREAD.projection.thread.id,
268 cursor: "older-page",
269 }),
270 },
271];
272
273describe("authenticated environment HTTP requests", () => {
274 it.effect.each(LOADERS)("rejects an invalid $name response", (loader) =>
275 Effect.gen(function* () {
276 const harness = makeHarness(() => Response.json({}));
277 const result = yield* loader
278 .load(harness.input)
279 .pipe(Effect.provide(harness.httpLayer), Effect.asVoid, Effect.flip);
280 expect(result._tag).toBe("RemoteEnvironmentAuthInvalidJsonError");
281 expect(harness.calls).toHaveLength(1);
282 }),
283 );
284
285 it.effect("keeps the status of a shell snapshot error that is not a declared error", () =>
286 Effect.gen(function* () {
287 const harness = makeHarness(() => Response.json({ error: "bad_gateway" }, { status: 502 }));
288 const error = yield* fetchEnvironmentShellSnapshot(harness.input).pipe(
289 Effect.provide(harness.httpLayer),
290 Effect.flip,
291 );
292 expect(error).toMatchObject({
293 _tag: "RemoteEnvironmentAuthUndeclaredStatusError",
294 status: 502,
295 });
296 }),
297 );
298
299 it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
300 Effect.gen(function* () {
301 const harness = makeHarness(() => Response.json(loader.response));
302 const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
303
304 expect(result).toEqual(loader.expected);
305 expect(harness.calls).toHaveLength(1);
306 const call = harness.calls[0]!;
307 const url = new URL(call.url);
308 expect(url.origin).toBe(CURRENT_ORIGIN);
309 expect(url.pathname).toBe(loader.path);
310 expect(call.init.method).toBe(loader.method);
311 expect(new Headers(call.init.headers).get("authorization")).toBe("DPoP current-token");
312 expect(new Headers(call.init.headers).get("dpop")).toBe("proof-1");
313 expect(call.init.credentials).toBeUndefined();
314 if (loader.path.startsWith("/api/orchestration/")) {
315 expect(new Headers(call.init.headers).get(ORCHESTRATION_PROTOCOL_HEADER)).toBe(
316 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
317 );
318 }
319 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
320 // The proof signs exactly the URL sent; signers drop the query for `htu`.
321 expect(harness.proofs).toEqual([
322 { method: loader.method, url: call.url, accessToken: "current-token" },
323 ]);
324 if (loader.name === "older thread history") {
325 expect(url.searchParams.get("cursor")).toBe("older-page");
326 }
327 expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
328 }),
329 );
330
331 // MCP-created thread ids contain ":", which the request path percent-encodes.
332 // The DPoP proof must sign the URL that is actually sent, or the environment
333 // rejects it as a URL mismatch.
334 const MCP_THREAD_ID = ThreadId.make("mcp:3534bc83-1c17-4a1e-9118-601c2766d355");
335 const MCP_THREAD_LOADERS: ReadonlyArray<
336 Pick<(typeof LOADERS)[number], "name" | "response" | "load">
337 > = [
338 {
339 name: "thread transcript",
340 response: encodeThreadTranscript(TRANSCRIPT),
341 load: (input: HttpInput) =>
342 fetchEnvironmentThreadTranscript({ ...input, threadId: MCP_THREAD_ID }),
343 },
344 {
345 name: "thread snapshot",
346 response: encodeThreadSnapshot(THREAD),
347 load: (input: HttpInput) =>
348 ThreadSnapshotLoader.fetchEnvironmentThreadSnapshot({ ...input, threadId: MCP_THREAD_ID }),
349 },
350 {
351 name: "bounded thread snapshot",
352 response: encodeBoundedSnapshot(BOUNDED_THREAD),
353 load: (input: HttpInput) =>
354 fetchEnvironmentBoundedThreadSnapshot({ ...input, threadId: MCP_THREAD_ID }),
355 },
356 {
357 name: "older thread history",
358 response: THREAD_HISTORY,
359 load: (input: HttpInput) =>
360 fetchEnvironmentThreadHistoryPage({
361 ...input,
362 threadId: MCP_THREAD_ID,
363 cursor: "older-page",
364 }),
365 },
366 ];
367 it.effect.each(MCP_THREAD_LOADERS)(
368 "signs the sent URL for a $name of a thread id that needs encoding",
369 (loader) =>
370 Effect.gen(function* () {
371 const harness = makeHarness(() => Response.json(loader.response));
372 yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
373
374 const sent = harness.calls[0]!.url;
375 expect(new URL(sent).pathname).toContain("/mcp%3A3534bc83-");
376 expect(harness.proofs.map((proof) => proof.url)).toEqual([sent]);
377 }),
378 );
379
380 it.effect("retries a rejected diff once with a new token, endpoint, and proof", () =>
381 Effect.gen(function* () {
382 const harness = makeHarness((requestNumber) =>
383 requestNumber === 1 ? credentialRejectedResponse() : Response.json(DIFF_RESULT),
384 );
385 const result = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
386 ...harness.input,
387 diff: DIFF,
388 }).pipe(Effect.provide(harness.httpLayer));
389
390 expect(result).toEqual(DIFF_RESULT);
391 expect(harness.authorizations).toEqual([
392 { expectedEnvironmentId: TARGET.environmentId },
393 { expectedEnvironmentId: TARGET.environmentId, rejectedAccessToken: "current-token" },
394 ]);
395 expect(harness.calls.map((call) => call.url)).toEqual([
396 `${CURRENT_ORIGIN}/api/pull-requests/diff`,
397 `${RENEWED_ORIGIN}/api/pull-requests/diff`,
398 ]);
399 expect(
400 harness.calls.map((call) => new Headers(call.init.headers).get("authorization")),
401 ).toEqual(["DPoP current-token", "DPoP renewed-token"]);
402 expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual([
403 "proof-1",
404 "proof-2",
405 ]);
406 expect(harness.proofs[1]).toEqual({
407 method: "POST",
408 url: `${RENEWED_ORIGIN}/api/pull-requests/diff`,
409 accessToken: "renewed-token",
410 });
411 expect(harness.calls[1]!.init.body).toEqual(harness.calls[0]!.init.body);
412 }),
413 );
414
415 it.effect("renews credentials captured by the bounded snapshot loader", () =>
416 Effect.gen(function* () {
417 const harness = makeHarness((requestNumber) =>
418 requestNumber === 1
419 ? credentialRejectedResponse()
420 : Response.json(encodeBoundedSnapshot(BOUNDED_THREAD)),
421 );
422 const layerLoader = BoundedThreadSnapshotHttp.layer.pipe(
423 Layer.provide(
424 Layer.mergeAll(
425 harness.httpLayer,
426 Layer.succeed(
427 ManagedRelay.ManagedRelayDpopSigner,
428 Option.getOrThrow(harness.input.signer),
429 ),
430 Layer.succeed(
431 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
432 harness.remoteAuthorization,
433 ),
434 ),
435 ),
436 );
437 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader.pipe(
438 Effect.provide(layerLoader),
439 );
440 const result = yield* loader.load(PREPARED, THREAD.projection.thread.id);
441 expect(result).toEqual({
442 _tag: "present",
443 snapshot: { ...THREAD, latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal },
444 history: {
445 historyCursor: BOUNDED_THREAD.historyCursor,
446 hasMoreHistory: true,
447 latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal,
448 },
449 });
450 expect(harness.calls).toHaveLength(2);
451 expect(new Headers(harness.calls[1]!.init.headers).get("authorization")).toBe(
452 "DPoP renewed-token",
453 );
454 }),
455 );
456
457 it.effect("preserves the credential rejection after the one recovery attempt fails", () =>
458 Effect.gen(function* () {
459 const harness = makeHarness(() => credentialRejectedResponse());
460 const error = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
461 ...harness.input,
462 diff: DIFF,
463 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
464
465 expect(error).toMatchObject({
466 _tag: "PullRequestDiffCredentialRejectedError",
467 traceId: "trace-rejected",
468 });
469 expect(harness.calls).toHaveLength(2);
470 expect(harness.authorizations).toHaveLength(2);
471 }),
472 );
473
474 it.effect.each([
475 {
476 name: "insufficient scope",
477 reply: () =>
478 Response.json(
479 {
480 _tag: "EnvironmentScopeRequiredError",
481 code: "insufficient_scope",
482 requiredScope: "orchestration:read",
483 traceId: "trace-scope",
484 },
485 { status: 403 },
486 ),
487 errorTag: "EnvironmentScopeRequiredError",
488 },
489 {
490 name: "missing credential",
491 reply: () => credentialRejectedResponse("missing_credential"),
492 errorTag: "EnvironmentAuthInvalidError",
493 },
494 {
495 name: "Cloudflare 530",
496 reply: () => new Response("error code: 1033", { status: 530 }),
497 errorTag: "RemoteEnvironmentAuthUndeclaredStatusError",
498 },
499 {
500 name: "network failure",
501 reply: () => Promise.reject(new Error("Network unreachable")),
502 errorTag: "RemoteEnvironmentAuthFetchError",
503 },
504 ])("does not renew or retry on $name", ({ reply, errorTag }) =>
505 Effect.gen(function* () {
506 const harness = makeHarness(reply);
507 const error = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
508 ...harness.input,
509 diff: DIFF,
510 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
511
512 expect(error._tag).toBe(errorTag);
513 expect(harness.calls).toHaveLength(1);
514 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
515 }),
516 );
517
518 it.effect("recovers a session's unauthenticated 200 response before checking permissions", () =>
519 Effect.gen(function* () {
520 const harness = makeHarness((requestNumber) =>
521 Response.json(requestNumber === 1 ? UNAUTHENTICATED_SESSION : SESSION),
522 );
523 const result = yield* fetchEnvironmentSessionState(harness.input).pipe(
524 Effect.provide(harness.httpLayer),
525 );
526
527 expect(result).toEqual(SESSION);
528 expect(harness.authorizations[1]).toEqual({
529 expectedEnvironmentId: TARGET.environmentId,
530 rejectedAccessToken: "current-token",
531 });
532 expect(harness.calls).toHaveLength(2);
533 }),
534 );
535
536 it.effect(
537 "waits longer for session permissions after the environment is too slow to answer",
538 () =>
539 Effect.gen(function* () {
540 const requests = yield* Queue.unbounded<number>();
541 let answer: () => void = () => {};
542 const answered = new Promise<void>((resolve) => {
543 answer = resolve;
544 });
545 const harness = makeHarness((requestNumber) => {
546 Queue.offerUnsafe(requests, requestNumber);
547 return requestNumber === 1
548 ? new Promise<Response>(() => {})
549 : answered.then(() => Response.json(SESSION));
550 });
551 const load = yield* fetchEnvironmentSessionState({
552 prepared: { ...PREPARED, httpAuthorization: { _tag: "Bearer", token: "bearer-token" } },
553 signer: Option.none(),
554 timeoutMs: 1_000,
555 }).pipe(Effect.provide(harness.httpLayer), Effect.forkChild({ startImmediately: true }));
556
557 yield* Queue.take(requests);
558 yield* TestClock.adjust("1 second");
559 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
560 yield* TestClock.adjust("1500 millis");
561 answer();
562
563 expect(yield* Fiber.await(load)).toStrictEqual(Exit.succeed(SESSION));
564 expect(harness.calls).toHaveLength(2);
565 }),
566 );
567
568 it.effect("gives up on session permissions once a 60 second wait also times out", () =>
569 Effect.gen(function* () {
570 const requests = yield* Queue.unbounded<number>();
571 const harness = makeHarness((requestNumber) => {
572 Queue.offerUnsafe(requests, requestNumber);
573 return new Promise<Response>(() => {});
574 });
575 const load = yield* fetchEnvironmentSessionState({
576 prepared: { ...PREPARED, httpAuthorization: { _tag: "Bearer", token: "bearer-token" } },
577 signer: Option.none(),
578 timeoutMs: 15_000,
579 }).pipe(Effect.provide(harness.httpLayer), Effect.forkChild({ startImmediately: true }));
580
581 yield* Queue.take(requests);
582 yield* TestClock.adjust("15 seconds");
583 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
584 yield* TestClock.adjust("30 seconds");
585 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
586 yield* TestClock.adjust("60 seconds");
587 const exit = yield* Fiber.await(load);
588
589 expect(exit).toMatchObject({
590 _tag: "Failure",
591 cause: {
592 reasons: [{ error: { _tag: "RemoteEnvironmentAuthTimeoutError", timeoutMs: 60_000 } }],
593 },
594 });
595 expect(harness.calls).toHaveLength(3);
596 }),
597 );
598
599 it.effect("reports persistent session rejection instead of showing missing permissions", () =>
600 Effect.gen(function* () {
601 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
602 const error = yield* fetchEnvironmentSessionState(harness.input).pipe(
603 Effect.provide(harness.httpLayer),
604 Effect.flip,
605 );
606
607 expect(error).toMatchObject({
608 _tag: "RemoteEnvironmentAuthFetchError",
609 message: "The environment rejected the renewed session authorization.",
610 });
611 expect(harness.calls).toHaveLength(2);
612 }),
613 );
614
615 it.effect.each([
616 { name: "cookie", authorization: null },
617 { name: "bearer", authorization: { _tag: "Bearer", token: "bearer-token" } },
618 ] satisfies ReadonlyArray<{ name: string; authorization: PreparedHttpAuthorization | null }>)(
619 "leaves $name sessions unchanged without relay services",
620 ({ authorization }) =>
621 Effect.gen(function* () {
622 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
623 const result = yield* fetchEnvironmentSessionState({
624 prepared: { ...PREPARED, httpAuthorization: authorization },
625 signer: Option.none(),
626 }).pipe(Effect.provide(harness.httpLayer));
627
628 expect(result).toEqual(UNAUTHENTICATED_SESSION);
629 expect(harness.calls).toHaveLength(1);
630 expect(harness.authorizations).toEqual([]);
631 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
632 authorization === null ? null : "Bearer bearer-token",
633 );
634 expect(harness.calls[0]!.init.credentials).toBe(
635 authorization === null ? "include" : undefined,
636 );
637 }),
638 );
639
640 it.effect("reports renewal failure without sending the expired prepared token", () =>
641 Effect.gen(function* () {
642 const harness = makeHarness(() => Response.json(SESSION));
643 const failure = new ConnectionTransientError({
644 reason: "transport",
645 detail: "Relay unavailable",
646 });
647 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
648 ...harness.remoteAuthorization,
649 authorizeDpopHttp: () => Effect.fail(failure),
650 });
651 const error = yield* fetchEnvironmentSessionState({
652 ...harness.input,
653 remoteAuthorization: Option.some(remoteAuthorization),
654 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
655
656 expect(error).toMatchObject({
657 _tag: "RemoteEnvironmentAuthFetchError",
658 message: "Could not authorize the environment request.",
659 cause: failure,
660 });
661 expect(harness.calls).toEqual([]);
662 expect(harness.proofs).toEqual([]);
663 }),
664 );
665
666 it.effect("does not fall back to a captured DPoP token when authorization is unavailable", () =>
667 Effect.gen(function* () {
668 const harness = makeHarness(() => Response.json(SESSION));
669 const error = yield* fetchEnvironmentSessionState({
670 prepared: PREPARED,
671 signer: harness.input.signer,
672 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
673
674 expect(error).toMatchObject({
675 _tag: "RemoteEnvironmentAuthFetchError",
676 message: "No relay authorization service is available for the environment request.",
677 });
678 expect(harness.calls).toEqual([]);
679 }),
680 );
681});