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

environmentHttpAuth.test.ts

653 lines23.9 KB

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 );
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 };
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)("rejects an invalid $name response", (loader) =>
246 Effect.gen(function* () {
247 const harness = makeHarness(() => Response.json({}));
248 const result = yield* loader
249 .load(harness.input)
250 .pipe(Effect.provide(harness.httpLayer), Effect.asVoid, Effect.flip);
251 expect(result._tag).toBe("RemoteEnvironmentAuthInvalidJsonError");
252 expect(harness.calls).toHaveLength(1);
253 }),
254 );
255​
256 it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
257 Effect.gen(function* () {
258 const harness = makeHarness(() => Response.json(loader.response));
259 const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
260​
261 expect(result).toEqual(loader.expected);
262 expect(harness.calls).toHaveLength(1);
263 const call = harness.calls[0]!;
264 const url = new URL(call.url);
265 expect(url.origin).toBe(CURRENT_ORIGIN);
266 expect(url.pathname).toBe(loader.path);
267 expect(call.init.method).toBe(loader.method);
268 expect(new Headers(call.init.headers).get("authorization")).toBe("DPoP current-token");
269 expect(new Headers(call.init.headers).get("dpop")).toBe("proof-1");
270 expect(call.init.credentials).toBeUndefined();
271 if (loader.path.startsWith("/api/orchestration/")) {
272 expect(new Headers(call.init.headers).get(ORCHESTRATION_PROTOCOL_HEADER)).toBe(
273 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
274 );
275 }
276 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
277 expect(harness.proofs).toEqual([
278 {
279 method: loader.method,
280 url: `${CURRENT_ORIGIN}${loader.path}`,
281 accessToken: "current-token",
282 },
283 ]);
284 if (loader.name === "older thread history") {
285 expect(url.searchParams.get("cursor")).toBe("older-page");
286 }
287 expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
288 }),
289 );
290​
291 it.effect("retries a rejected diff once with a new token, endpoint, and proof", () =>
292 Effect.gen(function* () {
293 const harness = makeHarness((requestNumber) =>
294 requestNumber === 1 ? credentialRejectedResponse() : Response.json(DIFF_RESULT),
295 );
296 const result = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
297 Effect.provide(harness.httpLayer),
298 );
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 loaderLayer = boundedThreadSnapshotLoaderLayer.pipe(
363 Layer.provide(
364 Layer.mergeAll(
365 harness.httpLayer,
366 Layer.succeed(ManagedRelayDpopSigner, Option.getOrThrow(harness.input.signer)),
367 Layer.succeed(RemoteEnvironmentAuthorization, harness.remoteAuthorization),
368 ),
369 ),
370 );
371 const loader = yield* ThreadSnapshotLoader.pipe(Effect.provide(loaderLayer));
372 const result = yield* loader.load(PREPARED, THREAD.projection.thread.id);
373 expect(result).toEqual({
374 _tag: "present",
375 snapshot: { ...THREAD, latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal },
376 history: {
377 historyCursor: BOUNDED_THREAD.historyCursor,
378 hasMoreHistory: true,
379 latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal,
380 },
381 });
382 expect(harness.calls).toHaveLength(2);
383 expect(new Headers(harness.calls[1]!.init.headers).get("authorization")).toBe(
384 "DPoP renewed-token",
385 );
386 }),
387 );
388​
389 it.effect("uses the authorization service captured by the diff loader layer", () =>
390 Effect.gen(function* () {
391 const harness = makeHarness(() => Response.json(DIFF_RESULT));
392 const loaderLayer = pullRequestDiffLoaderLayer.pipe(
393 Layer.provide(
394 Layer.mergeAll(
395 harness.httpLayer,
396 Layer.succeed(ManagedRelayDpopSigner, Option.getOrThrow(harness.input.signer)),
397 Layer.succeed(RemoteEnvironmentAuthorization, harness.remoteAuthorization),
398 ),
399 ),
400 );
401 const loader = yield* PullRequestDiffLoader.pipe(Effect.provide(loaderLayer));
402 const result = yield* loader.load(PREPARED, DIFF);
403​
404 expect(result).toEqual(DIFF_RESULT);
405 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
406 "DPoP current-token",
407 );
408 }),
409 );
410​
411 it.effect("preserves the credential rejection after the one recovery attempt fails", () =>
412 Effect.gen(function* () {
413 const harness = makeHarness(() => credentialRejectedResponse());
414 const error = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
415 Effect.provide(harness.httpLayer),
416 Effect.flip,
417 );
418​
419 expect(error).toMatchObject({
420 _tag: "PullRequestDiffCredentialRejectedError",
421 traceId: "trace-rejected",
422 });
423 expect(harness.calls).toHaveLength(2);
424 expect(harness.authorizations).toHaveLength(2);
425 }),
426 );
427​
428 it.effect.each([
429 {
430 name: "insufficient scope",
431 reply: () =>
432 Response.json(
433 {
434 _tag: "EnvironmentScopeRequiredError",
435 code: "insufficient_scope",
436 requiredScope: "orchestration:read",
437 traceId: "trace-scope",
438 },
439 { status: 403 },
440 ),
441 errorTag: "EnvironmentScopeRequiredError",
442 },
443 {
444 name: "missing credential",
445 reply: () => credentialRejectedResponse("missing_credential"),
446 errorTag: "EnvironmentAuthInvalidError",
447 },
448 {
449 name: "Cloudflare 530",
450 reply: () => new Response("error code: 1033", { status: 530 }),
451 errorTag: "RemoteEnvironmentAuthUndeclaredStatusError",
452 },
453 {
454 name: "network failure",
455 reply: () => Promise.reject(new Error("Network unreachable")),
456 errorTag: "RemoteEnvironmentAuthFetchError",
457 },
458 ])("does not renew or retry on $name", ({ reply, errorTag }) =>
459 Effect.gen(function* () {
460 const harness = makeHarness(reply);
461 const error = yield* fetchEnvironmentPullRequestDiff({ ...harness.input, diff: DIFF }).pipe(
462 Effect.provide(harness.httpLayer),
463 Effect.flip,
464 );
465​
466 expect(error._tag).toBe(errorTag);
467 expect(harness.calls).toHaveLength(1);
468 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
469 }),
470 );
471​
472 it.effect("recovers a session's unauthenticated 200 response before checking permissions", () =>
473 Effect.gen(function* () {
474 const harness = makeHarness((requestNumber) =>
475 Response.json(requestNumber === 1 ? UNAUTHENTICATED_SESSION : SESSION),
476 );
477 const result = yield* fetchEnvironmentSessionState(harness.input).pipe(
478 Effect.provide(harness.httpLayer),
479 );
480​
481 expect(result).toEqual(SESSION);
482 expect(harness.authorizations[1]).toEqual({
483 expectedEnvironmentId: TARGET.environmentId,
484 rejectedAccessToken: "current-token",
485 });
486 expect(harness.calls).toHaveLength(2);
487 }),
488 );
489​
490 it.effect("reports persistent session rejection instead of showing missing permissions", () =>
491 Effect.gen(function* () {
492 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
493 const error = yield* fetchEnvironmentSessionState(harness.input).pipe(
494 Effect.provide(harness.httpLayer),
495 Effect.flip,
496 );
497​
498 expect(error).toMatchObject({
499 _tag: "RemoteEnvironmentAuthFetchError",
500 message: "The environment rejected the renewed session authorization.",
501 });
502 expect(harness.calls).toHaveLength(2);
503 }),
504 );
505​
506 it.effect.each([
507 { name: "cookie", authorization: null },
508 { name: "bearer", authorization: { _tag: "Bearer", token: "bearer-token" } },
509 ] satisfies ReadonlyArray<{ name: string; authorization: PreparedHttpAuthorization | null }>)(
510 "leaves $name sessions unchanged without relay services",
511 ({ authorization }) =>
512 Effect.gen(function* () {
513 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
514 const result = yield* fetchEnvironmentSessionState({
515 prepared: { ...PREPARED, httpAuthorization: authorization },
516 signer: Option.none(),
517 }).pipe(Effect.provide(harness.httpLayer));
518​
519 expect(result).toEqual(UNAUTHENTICATED_SESSION);
520 expect(harness.calls).toHaveLength(1);
521 expect(harness.authorizations).toEqual([]);
522 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
523 authorization === null ? null : "Bearer bearer-token",
524 );
525 expect(harness.calls[0]!.init.credentials).toBe(
526 authorization === null ? "include" : undefined,
527 );
528 }),
529 );
530​
531 it.effect("keeps the caller's timeout while waiting for renewal", () =>
532 Effect.gen(function* () {
533 const harness = makeHarness(() => Response.json(SESSION));
534 const authorizing = yield* Deferred.make<void>();
535 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
536 ...harness.remoteAuthorization,
537 authorizeDpopHttp: () =>
538 Deferred.succeed(authorizing, undefined).pipe(Effect.andThen(Effect.never)),
539 });
540 const pending = yield* fetchEnvironmentSessionState({
541 ...harness.input,
542 remoteAuthorization: Option.some(remoteAuthorization),
543 timeoutMs: 100,
544 }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
545 yield* Deferred.await(authorizing);
546 yield* TestClock.adjust(100);
547​
548 expect(yield* Fiber.join(pending)).toMatchObject({
549 _tag: "RemoteEnvironmentAuthTimeoutError",
550 requestUrl: `${PREPARED.httpBaseUrl}/api/auth/session`,
551 timeoutMs: 100,
552 });
553 expect(harness.calls).toEqual([]);
554 }),
555 );
556​
557 it.effect("reports the current endpoint when the total timeout expires during HTTP", () =>
558 Effect.gen(function* () {
559 const requested = Promise.withResolvers<void>();
560 const response = Promise.withResolvers<Response>();
561 const harness = makeHarness(() => {
562 requested.resolve();
563 return response.promise;
564 });
565 const authorizing = yield* Deferred.make<void>();
566 const authorize = yield* Deferred.make<void>();
567 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
568 ...harness.remoteAuthorization,
569 authorizeDpopHttp: (input) =>
570 Deferred.succeed(authorizing, undefined).pipe(
571 Effect.andThen(Deferred.await(authorize)),
572 Effect.andThen(harness.remoteAuthorization.authorizeDpopHttp(input)),
573 ),
574 });
575 const pending = yield* fetchEnvironmentSessionState({
576 ...harness.input,
577 remoteAuthorization: Option.some(remoteAuthorization),
578 timeoutMs: 100,
579 }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
580 yield* Deferred.await(authorizing);
581 yield* TestClock.adjust(25);
582 yield* Deferred.succeed(authorize, undefined);
583 yield* Effect.promise(() => requested.promise);
584 yield* TestClock.adjust(75);
585​
586 expect(yield* Fiber.join(pending)).toMatchObject({
587 _tag: "RemoteEnvironmentAuthTimeoutError",
588 requestUrl: `${CURRENT_ORIGIN}/api/auth/session`,
589 timeoutMs: 100,
590 });
591 expect(harness.calls.map((call) => call.url)).toEqual([`${CURRENT_ORIGIN}/api/auth/session`]);
592 expect(harness.authorizations).toHaveLength(1);
593 response.resolve(Response.json(SESSION));
594 }),
595 );
596​
597 it.effect("reports renewal failure without sending the expired prepared token", () =>
598 Effect.gen(function* () {
599 const harness = makeHarness(() => Response.json(SESSION));
600 const failure = new ConnectionTransientError({
601 reason: "transport",
602 detail: "Relay unavailable",
603 });
604 const remoteAuthorization = RemoteEnvironmentAuthorization.of({
605 ...harness.remoteAuthorization,
606 authorizeDpopHttp: () => Effect.fail(failure),
607 });
608 const error = yield* fetchEnvironmentSessionState({
609 ...harness.input,
610 remoteAuthorization: Option.some(remoteAuthorization),
611 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
612​
613 expect(error).toMatchObject({
614 _tag: "RemoteEnvironmentAuthFetchError",
615 message: "Could not authorize the environment request.",
616 cause: failure,
617 });
618 expect(harness.calls).toEqual([]);
619 expect(harness.proofs).toEqual([]);
620 }),
621 );
622​
623 it.effect("does not fall back to a captured DPoP token when authorization is unavailable", () =>
624 Effect.gen(function* () {
625 const harness = makeHarness(() => Response.json(SESSION));
626 const error = yield* fetchEnvironmentSessionState({
627 prepared: PREPARED,
628 signer: harness.input.signer,
629 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
630​
631 expect(error).toMatchObject({
632 _tag: "RemoteEnvironmentAuthFetchError",
633 message: "No relay authorization service is available for the environment request.",
634 });
635 expect(harness.calls).toEqual([]);
636 }),
637 );
638});
639​
640describe("orchestration HTTP compatibility header", () => {
641 it("announces the current protocol without replacing bearer or DPoP authentication", () => {
642 expect(
643 withOrchestrationProtocolHeader({
644 authorization: "DPoP access-token",
645 dpop: "signed-proof",
646 }),
647 ).toEqual({
648 authorization: "DPoP access-token",
649 dpop: "signed-proof",
650 [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT,
651 });
652 });
653});