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