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

environmentHttpAuth.test.ts

664 lines24.2 KB

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