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