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

environmentHttpAuth.test.ts

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