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

environmentHttpAuth.test.ts

719 lines26.3 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 // Pull request links decode separately; the rows match the response on their own.
208 load: (input: HttpInput) =>
209 fetchEnvironmentShellSnapshot(input).pipe(
210 Effect.map(({ loadPullRequests: _links, ...snapshot }) => snapshot),
211 ),
212 },
213 {
214 name: "thread snapshot",
215 method: "GET",
216 path: `/api/orchestration/threads/${THREAD.projection.thread.id}`,
217 response: encodeThreadSnapshot(THREAD),
218 expected: THREAD,
219 load: (input: HttpInput) =>
220 ThreadSnapshotLoader.fetchEnvironmentThreadSnapshot({
221 ...input,
222 threadId: THREAD.projection.thread.id,
223 }),
224 },
225 {
226 name: "bounded thread snapshot",
227 method: "GET",
228 path: `/api/orchestration/threads/${THREAD.projection.thread.id}/bounded`,
229 response: encodeBoundedSnapshot(BOUNDED_THREAD),
230 expected: BOUNDED_THREAD,
231 load: (input: HttpInput) =>
232 fetchEnvironmentBoundedThreadSnapshot({ ...input, threadId: THREAD.projection.thread.id }),
233 },
234 {
235 name: "older thread history",
236 method: "GET",
237 path: `/api/orchestration/threads/${THREAD.projection.thread.id}/history`,
238 response: THREAD_HISTORY,
239 expected: THREAD_HISTORY,
240 load: (input: HttpInput) =>
241 fetchEnvironmentThreadHistoryPage({
242 ...input,
243 threadId: THREAD.projection.thread.id,
244 cursor: "older-page",
245 }),
246 },
247];
248​
249describe("authenticated environment HTTP requests", () => {
250 it.effect.each(LOADERS)("rejects an invalid $name response", (loader) =>
251 Effect.gen(function* () {
252 const harness = makeHarness(() => Response.json({}));
253 const result = yield* loader
254 .load(harness.input)
255 .pipe(Effect.provide(harness.httpLayer), Effect.asVoid, Effect.flip);
256 expect(result._tag).toBe("RemoteEnvironmentAuthInvalidJsonError");
257 expect(harness.calls).toHaveLength(1);
258 }),
259 );
260​
261 it.effect("keeps the status of a shell snapshot error that is not a declared error", () =>
262 Effect.gen(function* () {
263 const harness = makeHarness(() => Response.json({ error: "bad_gateway" }, { status: 502 }));
264 const error = yield* fetchEnvironmentShellSnapshot(harness.input).pipe(
265 Effect.provide(harness.httpLayer),
266 Effect.flip,
267 );
268 expect(error).toMatchObject({
269 _tag: "RemoteEnvironmentAuthUndeclaredStatusError",
270 status: 502,
271 });
272 }),
273 );
274​
275 it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
276 Effect.gen(function* () {
277 const harness = makeHarness(() => Response.json(loader.response));
278 const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
279​
280 expect(result).toEqual(loader.expected);
281 expect(harness.calls).toHaveLength(1);
282 const call = harness.calls[0]!;
283 const url = new URL(call.url);
284 expect(url.origin).toBe(CURRENT_ORIGIN);
285 expect(url.pathname).toBe(loader.path);
286 expect(call.init.method).toBe(loader.method);
287 expect(new Headers(call.init.headers).get("authorization")).toBe("DPoP current-token");
288 expect(new Headers(call.init.headers).get("dpop")).toBe("proof-1");
289 expect(call.init.credentials).toBeUndefined();
290 if (loader.path.startsWith("/api/orchestration/")) {
291 expect(new Headers(call.init.headers).get(ORCHESTRATION_PROTOCOL_HEADER)).toBe(
292 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
293 );
294 }
295 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
296 expect(harness.proofs).toEqual([
297 {
298 method: loader.method,
299 url: `${CURRENT_ORIGIN}${loader.path}`,
300 accessToken: "current-token",
301 },
302 ]);
303 if (loader.name === "older thread history") {
304 expect(url.searchParams.get("cursor")).toBe("older-page");
305 }
306 expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
307 }),
308 );
309​
310 it.effect("retries a rejected diff once with a new token, endpoint, and proof", () =>
311 Effect.gen(function* () {
312 const harness = makeHarness((requestNumber) =>
313 requestNumber === 1 ? credentialRejectedResponse() : Response.json(DIFF_RESULT),
314 );
315 const result = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
316 ...harness.input,
317 diff: DIFF,
318 }).pipe(Effect.provide(harness.httpLayer));
319​
320 expect(result).toEqual(DIFF_RESULT);
321 expect(harness.authorizations).toEqual([
322 { expectedEnvironmentId: TARGET.environmentId },
323 { expectedEnvironmentId: TARGET.environmentId, rejectedAccessToken: "current-token" },
324 ]);
325 expect(harness.calls.map((call) => call.url)).toEqual([
326 `${CURRENT_ORIGIN}/api/pull-requests/diff`,
327 `${RENEWED_ORIGIN}/api/pull-requests/diff`,
328 ]);
329 expect(
330 harness.calls.map((call) => new Headers(call.init.headers).get("authorization")),
331 ).toEqual(["DPoP current-token", "DPoP renewed-token"]);
332 expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual([
333 "proof-1",
334 "proof-2",
335 ]);
336 expect(harness.proofs[1]).toEqual({
337 method: "POST",
338 url: `${RENEWED_ORIGIN}/api/pull-requests/diff`,
339 accessToken: "renewed-token",
340 });
341 expect(harness.calls[1]!.init.body).toEqual(harness.calls[0]!.init.body);
342 }),
343 );
344​
345 it.effect.each(LOADERS.filter((loader) => loader.path.startsWith("/api/orchestration/")))(
346 "renews a rejected credential without losing the v2 protocol or query for $name",
347 (loader) =>
348 Effect.gen(function* () {
349 const harness = makeHarness((requestNumber) =>
350 requestNumber === 1 ? credentialRejectedResponse() : Response.json(loader.response),
351 );
352 const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
353 expect(result).toEqual(loader.expected);
354 expect(harness.calls).toHaveLength(2);
355 const retried = harness.calls[1]!;
356 const url = new URL(retried.url);
357 expect(url.origin).toBe(RENEWED_ORIGIN);
358 expect(url.pathname).toBe(loader.path);
359 expect(new Headers(retried.init.headers).get("authorization")).toBe("DPoP renewed-token");
360 expect(new Headers(retried.init.headers).get("dpop")).toBe("proof-2");
361 expect(new Headers(retried.init.headers).get(ORCHESTRATION_PROTOCOL_HEADER)).toBe(
362 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
363 );
364 expect(harness.proofs[1]).toEqual({
365 method: "GET",
366 url: `${RENEWED_ORIGIN}${loader.path}`,
367 accessToken: "renewed-token",
368 });
369 if (loader.name === "older thread history") {
370 expect(url.searchParams.get("cursor")).toBe("older-page");
371 }
372 }),
373 );
374​
375 it.effect("renews credentials captured by the bounded snapshot loader", () =>
376 Effect.gen(function* () {
377 const harness = makeHarness((requestNumber) =>
378 requestNumber === 1
379 ? credentialRejectedResponse()
380 : Response.json(encodeBoundedSnapshot(BOUNDED_THREAD)),
381 );
382 const layerLoader = BoundedThreadSnapshotHttp.layer.pipe(
383 Layer.provide(
384 Layer.mergeAll(
385 harness.httpLayer,
386 Layer.succeed(
387 ManagedRelay.ManagedRelayDpopSigner,
388 Option.getOrThrow(harness.input.signer),
389 ),
390 Layer.succeed(
391 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
392 harness.remoteAuthorization,
393 ),
394 ),
395 ),
396 );
397 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader.pipe(
398 Effect.provide(layerLoader),
399 );
400 const result = yield* loader.load(PREPARED, THREAD.projection.thread.id);
401 expect(result).toEqual({
402 _tag: "present",
403 snapshot: { ...THREAD, latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal },
404 history: {
405 historyCursor: BOUNDED_THREAD.historyCursor,
406 hasMoreHistory: true,
407 latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal,
408 },
409 });
410 expect(harness.calls).toHaveLength(2);
411 expect(new Headers(harness.calls[1]!.init.headers).get("authorization")).toBe(
412 "DPoP renewed-token",
413 );
414 }),
415 );
416​
417 it.effect("uses the authorization service captured by the diff loader layer", () =>
418 Effect.gen(function* () {
419 const harness = makeHarness(() => Response.json(DIFF_RESULT));
420 const layerLoader = PullRequestDiffLoader.layer.pipe(
421 Layer.provide(
422 Layer.mergeAll(
423 harness.httpLayer,
424 Layer.succeed(
425 ManagedRelay.ManagedRelayDpopSigner,
426 Option.getOrThrow(harness.input.signer),
427 ),
428 Layer.succeed(
429 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
430 harness.remoteAuthorization,
431 ),
432 ),
433 ),
434 );
435 const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader.pipe(
436 Effect.provide(layerLoader),
437 );
438 const result = yield* loader.load(PREPARED, DIFF);
439​
440 expect(result).toEqual(DIFF_RESULT);
441 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
442 "DPoP current-token",
443 );
444 }),
445 );
446​
447 it.effect("preserves the credential rejection after the one recovery attempt fails", () =>
448 Effect.gen(function* () {
449 const harness = makeHarness(() => credentialRejectedResponse());
450 const error = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
451 ...harness.input,
452 diff: DIFF,
453 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
454​
455 expect(error).toMatchObject({
456 _tag: "PullRequestDiffCredentialRejectedError",
457 traceId: "trace-rejected",
458 });
459 expect(harness.calls).toHaveLength(2);
460 expect(harness.authorizations).toHaveLength(2);
461 }),
462 );
463​
464 it.effect.each([
465 {
466 name: "insufficient scope",
467 reply: () =>
468 Response.json(
469 {
470 _tag: "EnvironmentScopeRequiredError",
471 code: "insufficient_scope",
472 requiredScope: "orchestration:read",
473 traceId: "trace-scope",
474 },
475 { status: 403 },
476 ),
477 errorTag: "EnvironmentScopeRequiredError",
478 },
479 {
480 name: "missing credential",
481 reply: () => credentialRejectedResponse("missing_credential"),
482 errorTag: "EnvironmentAuthInvalidError",
483 },
484 {
485 name: "Cloudflare 530",
486 reply: () => new Response("error code: 1033", { status: 530 }),
487 errorTag: "RemoteEnvironmentAuthUndeclaredStatusError",
488 },
489 {
490 name: "network failure",
491 reply: () => Promise.reject(new Error("Network unreachable")),
492 errorTag: "RemoteEnvironmentAuthFetchError",
493 },
494 ])("does not renew or retry on $name", ({ reply, errorTag }) =>
495 Effect.gen(function* () {
496 const harness = makeHarness(reply);
497 const error = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
498 ...harness.input,
499 diff: DIFF,
500 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
501​
502 expect(error._tag).toBe(errorTag);
503 expect(harness.calls).toHaveLength(1);
504 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
505 }),
506 );
507​
508 it.effect("recovers a session's unauthenticated 200 response before checking permissions", () =>
509 Effect.gen(function* () {
510 const harness = makeHarness((requestNumber) =>
511 Response.json(requestNumber === 1 ? UNAUTHENTICATED_SESSION : SESSION),
512 );
513 const result = yield* fetchEnvironmentSessionState(harness.input).pipe(
514 Effect.provide(harness.httpLayer),
515 );
516​
517 expect(result).toEqual(SESSION);
518 expect(harness.authorizations[1]).toEqual({
519 expectedEnvironmentId: TARGET.environmentId,
520 rejectedAccessToken: "current-token",
521 });
522 expect(harness.calls).toHaveLength(2);
523 }),
524 );
525​
526 it.effect("reports persistent session rejection instead of showing missing permissions", () =>
527 Effect.gen(function* () {
528 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
529 const error = yield* fetchEnvironmentSessionState(harness.input).pipe(
530 Effect.provide(harness.httpLayer),
531 Effect.flip,
532 );
533​
534 expect(error).toMatchObject({
535 _tag: "RemoteEnvironmentAuthFetchError",
536 message: "The environment rejected the renewed session authorization.",
537 });
538 expect(harness.calls).toHaveLength(2);
539 }),
540 );
541​
542 it.effect.each([
543 { name: "cookie", authorization: null },
544 { name: "bearer", authorization: { _tag: "Bearer", token: "bearer-token" } },
545 ] satisfies ReadonlyArray<{ name: string; authorization: PreparedHttpAuthorization | null }>)(
546 "leaves $name sessions unchanged without relay services",
547 ({ authorization }) =>
548 Effect.gen(function* () {
549 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
550 const result = yield* fetchEnvironmentSessionState({
551 prepared: { ...PREPARED, httpAuthorization: authorization },
552 signer: Option.none(),
553 }).pipe(Effect.provide(harness.httpLayer));
554​
555 expect(result).toEqual(UNAUTHENTICATED_SESSION);
556 expect(harness.calls).toHaveLength(1);
557 expect(harness.authorizations).toEqual([]);
558 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
559 authorization === null ? null : "Bearer bearer-token",
560 );
561 expect(harness.calls[0]!.init.credentials).toBe(
562 authorization === null ? "include" : undefined,
563 );
564 }),
565 );
566​
567 it.effect("keeps the caller's timeout while waiting for renewal", () =>
568 Effect.gen(function* () {
569 const harness = makeHarness(() => Response.json(SESSION));
570 const authorizing = yield* Deferred.make<void>();
571 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
572 ...harness.remoteAuthorization,
573 authorizeDpopHttp: () =>
574 Deferred.succeed(authorizing, undefined).pipe(Effect.andThen(Effect.never)),
575 });
576 const pending = yield* fetchEnvironmentSessionState({
577 ...harness.input,
578 remoteAuthorization: Option.some(remoteAuthorization),
579 timeoutMs: 100,
580 }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
581 yield* Deferred.await(authorizing);
582 yield* TestClock.adjust(100);
583​
584 expect(yield* Fiber.join(pending)).toMatchObject({
585 _tag: "RemoteEnvironmentAuthTimeoutError",
586 requestUrl: `${PREPARED.httpBaseUrl}/api/auth/session`,
587 timeoutMs: 100,
588 });
589 expect(harness.calls).toEqual([]);
590 }),
591 );
592​
593 it.effect("reports the current endpoint when the total timeout expires during HTTP", () =>
594 Effect.gen(function* () {
595 const requested = Promise.withResolvers<void>();
596 const response = Promise.withResolvers<Response>();
597 const harness = makeHarness(() => {
598 requested.resolve();
599 return response.promise;
600 });
601 const authorizing = yield* Deferred.make<void>();
602 const authorize = yield* Deferred.make<void>();
603 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
604 ...harness.remoteAuthorization,
605 authorizeDpopHttp: (input) =>
606 Deferred.succeed(authorizing, undefined).pipe(
607 Effect.andThen(Deferred.await(authorize)),
608 Effect.andThen(harness.remoteAuthorization.authorizeDpopHttp(input)),
609 ),
610 });
611 const pending = yield* fetchEnvironmentSessionState({
612 ...harness.input,
613 remoteAuthorization: Option.some(remoteAuthorization),
614 timeoutMs: 100,
615 }).pipe(Effect.provide(harness.httpLayer), Effect.flip, Effect.forkChild);
616 yield* Deferred.await(authorizing);
617 yield* TestClock.adjust(25);
618 yield* Deferred.succeed(authorize, undefined);
619 yield* Effect.promise(() => requested.promise);
620 yield* TestClock.adjust(75);
621​
622 expect(yield* Fiber.join(pending)).toMatchObject({
623 _tag: "RemoteEnvironmentAuthTimeoutError",
624 requestUrl: `${CURRENT_ORIGIN}/api/auth/session`,
625 timeoutMs: 100,
626 });
627 expect(harness.calls.map((call) => call.url)).toEqual([`${CURRENT_ORIGIN}/api/auth/session`]);
628 expect(harness.authorizations).toHaveLength(1);
629 response.resolve(Response.json(SESSION));
630 }),
631 );
632​
633 it.effect("reports renewal failure without sending the expired prepared token", () =>
634 Effect.gen(function* () {
635 const harness = makeHarness(() => Response.json(SESSION));
636 const failure = new ConnectionTransientError({
637 reason: "transport",
638 detail: "Relay unavailable",
639 });
640 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
641 ...harness.remoteAuthorization,
642 authorizeDpopHttp: () => Effect.fail(failure),
643 });
644 const error = yield* fetchEnvironmentSessionState({
645 ...harness.input,
646 remoteAuthorization: Option.some(remoteAuthorization),
647 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
648​
649 expect(error).toMatchObject({
650 _tag: "RemoteEnvironmentAuthFetchError",
651 message: "Could not authorize the environment request.",
652 cause: failure,
653 });
654 expect(harness.calls).toEqual([]);
655 expect(harness.proofs).toEqual([]);
656 }),
657 );
658​
659 it.effect("does not fall back to a captured DPoP token when authorization is unavailable", () =>
660 Effect.gen(function* () {
661 const harness = makeHarness(() => Response.json(SESSION));
662 const error = yield* fetchEnvironmentSessionState({
663 prepared: PREPARED,
664 signer: harness.input.signer,
665 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
666​
667 expect(error).toMatchObject({
668 _tag: "RemoteEnvironmentAuthFetchError",
669 message: "No relay authorization service is available for the environment request.",
670 });
671 expect(harness.calls).toEqual([]);
672 }),
673 );
674});
675​
676describe("relay request tracing", () => {
677 it.effect("starts an exported trace for a T3 Connect request", () =>
678 Effect.gen(function* () {
679 const productSpans: Array<{ readonly name: string; readonly root: boolean }> = [];
680 const productTracer = Tracer.make({
681 span: (options) => {
682 productSpans.push({ name: options.name, root: Option.isNone(options.parent) });
683 return new Tracer.NativeSpan(options);
684 },
685 });
686 const harness = makeHarness(() => Response.json(DIFF_RESULT));
687​
688 yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
689 ...harness.input,
690 diff: DIFF,
691 }).pipe(
692 Effect.withSpan("mobile.screen.local"),
693 Effect.provide(harness.httpLayer),
694 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
695 );
696​
697 expect(productSpans[0]).toEqual({
698 name: "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest",
699 root: true,
700 });
701 expect(productSpans.map((span) => span.name)).not.toContain("mobile.screen.local");
702 }),
703 );
704});
705​
706describe("orchestration HTTP compatibility header", () => {
707 it("announces the current protocol without replacing bearer or DPoP authentication", () => {
708 expect(
709 withOrchestrationProtocolHeader({
710 authorization: "DPoP access-token",
711 dpop: "signed-proof",
712 }),
713 ).toEqual({
714 authorization: "DPoP access-token",
715 dpop: "signed-proof",
716 [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT,
717 });
718 });
719});