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