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

environmentHttpAuth.test.ts

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