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

environmentHttpAuth.test.ts

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