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