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