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