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 * as Cause from "effect/Cause";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Fiber from "effect/Fiber";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Queue from "effect/Queue";
23import * as Ref from "effect/Ref";
24import * as Schema from "effect/Schema";
25import * as SubscriptionRef from "effect/SubscriptionRef";
26import * as TestClock from "effect/testing/TestClock";
27import type { HttpClient } from "effect/http";
28import { AsyncResult } from "effect/reactivity";
29
30import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
31import {
32 AVAILABLE_CONNECTION_STATE,
33 ConnectionBlockedError,
34 ConnectionTransientError,
35 RelayConnectionTarget,
36 type PreparedConnection,
37 type PreparedHttpAuthorization,
38} from "../connection/model.ts";
39import * as EnvironmentRegistry from "../connection/registry.ts";
40import * as EnvironmentSupervisor from "../connection/supervisor.ts";
41import type * as RpcSession from "../rpc/session.ts";
42import {
43 executeAuthenticatedEnvironmentHttpRequest,
44 executeConnectedEnvironmentHttpRequest,
45} from "./environmentHttpAuth.ts";
46import * as ManagedRelay from "../relay/managedRelay.ts";
47import { type RemoteEnvironmentRequestError } from "../rpc/http.ts";
48import * as RpcHttp from "../rpc/http.ts";
49import { resolveDeviceHubAccess } from "./deviceHubAccess.ts";
50import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
51import { fetchEnvironmentSessionState, sessionDeniesScope } from "./session.ts";
52import { fetchEnvironmentShellSnapshot } from "./shellSnapshotHttp.ts";
53import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
54import { fetchEnvironmentThreadTranscript } from "./threadTranscriptHttp.ts";
55import { fetchEnvironmentBoundedThreadSnapshot } from "./boundedThreadSnapshotHttp.ts";
56import * as BoundedThreadSnapshotHttp from "./boundedThreadSnapshotHttp.ts";
57import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts";
58import { v2Projection } from "./orchestrationV2TestFixtures.ts";
59
60const encodeBoundedSnapshot = Schema.encodeSync(OrchestrationV2ThreadBoundedSnapshot);
61const encodeThreadTranscript = Schema.encodeSync(OrchestrationV2ThreadTranscript);
62
63const TARGET = new RelayConnectionTarget({
64 environmentId: EnvironmentId.make("environment-1"),
65 label: "Remote environment",
66});
67const PREPARED: PreparedConnection = {
68 environmentId: TARGET.environmentId,
69 label: TARGET.label,
70 httpBaseUrl: "https://previous.example.test",
71 socketUrl: "wss://previous.example.test/ws",
72 httpAuthorization: { _tag: "Dpop", accessToken: "expired-token", expiresAtEpochMs: 0 },
73 target: TARGET,
74};
75const CURRENT_ORIGIN = "https://current.example.test";
76const RENEWED_ORIGIN = "https://renewed.example.test";
77const DIFF = {
78 projectId: ProjectId.make("project-1"),
79 repository: "owner/repository",
80 number: 42,
81};
82const DIFF_RESULT = { patch: "diff --git a/file.ts b/file.ts", truncated: false, nextCursor: null };
83const AUTH = {
84 policy: "remote-reachable",
85 bootstrapMethods: ["one-time-token"],
86 sessionMethods: ["dpop-access-token"],
87 sessionCookieName: "t3_session",
88} satisfies AuthSessionState["auth"];
89const SESSION = {
90 authenticated: true,
91 auth: AUTH,
92 scopes: ["orchestration:read", "orchestration:operate"],
93 sessionMethod: "dpop-access-token",
94} satisfies AuthSessionState;
95const UNAUTHENTICATED_SESSION = { authenticated: false, auth: AUTH } satisfies AuthSessionState;
96const SHELL = {
97 schemaVersion: 1,
98 snapshotSequence: 1,
99 projects: [],
100 threads: [],
101 archivedThreads: [],
102} satisfies OrchestrationV2ShellSnapshot;
103const THREAD = {
104 snapshotSequence: 2,
105 projection: v2Projection,
106} satisfies OrchestrationV2ThreadDetailSnapshot;
107const TRANSCRIPT = {
108 threadId: v2Projection.thread.id,
109 title: v2Projection.thread.title,
110 updatedAt: v2Projection.updatedAt,
111 items: v2Projection.visibleTurnItems,
112} satisfies OrchestrationV2ThreadTranscript;
113const BOUNDED_THREAD = {
114 ...THREAD,
115 historyCursor: "older-page",
116 hasMoreHistory: true,
117 latestLocalTurnOrdinal: 3,
118} satisfies OrchestrationV2ThreadBoundedSnapshot;
119const THREAD_HISTORY = {
120 snapshotSequence: 2,
121 items: [],
122 nextCursor: null,
123 hasMoreHistory: false,
124} satisfies OrchestrationV2ThreadHistoryPage;
125
126function credentialRejectedResponse(reason = "invalid_credential") {
127 return Response.json(
128 {
129 _tag: "EnvironmentAuthInvalidError",
130 code: "auth_invalid",
131 reason,
132 traceId: "trace-rejected",
133 },
134 { status: 401 },
135 );
136}
137
138function makeHarness(reply: (requestNumber: number) => Response | Promise<Response>) {
139 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
140 const authorizations: Array<
141 Parameters<
142 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]
143 >[0]
144 > = [];
145 const proofs: Array<ManagedRelay.ManagedRelayDpopProofInput> = [];
146 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
147 authorizeBearer: () => Effect.die("Unexpected bearer connection preparation."),
148 authorizeDpop: () => Effect.die("HTTP requests must not prepare a WebSocket connection."),
149 authorizeDirectDpop: () => Effect.die("HTTP requests must not prepare a WebSocket connection."),
150 authorizeDirectDpopHttp: () => Effect.die("Unexpected direct DPoP authorization."),
151 authorizeDpopHttp: (input) =>
152 Effect.sync(() => {
153 authorizations.push(input);
154 const rejected = input.rejectedAccessToken !== undefined;
155 return {
156 environmentId: TARGET.environmentId,
157 label: TARGET.label,
158 httpBaseUrl: rejected ? RENEWED_ORIGIN : CURRENT_ORIGIN,
159 httpAuthorization: {
160 _tag: "Dpop" as const,
161 accessToken: rejected ? "renewed-token" : "current-token",
162 expiresAtEpochMs: 3_600_000,
163 },
164 };
165 }),
166 rememberCheckedDescriptor: () => Effect.void,
167 renewDpopBeforeExpiry: () => Effect.die("HTTP requests must not renew a socket's token."),
168 });
169 const signer = ManagedRelay.ManagedRelayDpopSigner.of({
170 thumbprint: Effect.succeed("test-thumbprint"),
171 createProof: (input) =>
172 Effect.sync(() => {
173 proofs.push(input);
174 return `proof-${proofs.length}`;
175 }),
176 });
177 const fetchFn: typeof fetch = async (request, init) => {
178 calls.push({ url: String(request), init: init ?? {} });
179 return reply(calls.length);
180 };
181 return {
182 calls,
183 authorizations,
184 proofs,
185 remoteAuthorization,
186 input: {
187 prepared: PREPARED,
188 signer: Option.some(signer),
189 remoteAuthorization: Option.some(remoteAuthorization),
190 },
191 httpLayer: RpcHttp.layerRemoteHttpClient(fetchFn),
192 };
193}
194
195// Resolves "settled" instead of hanging when the load finishes without sending another request.
196function nextRequestOrSettled(requests: Queue.Queue<number>, load: Fiber.Fiber<unknown, unknown>) {
197 return Effect.raceFirst(
198 Queue.take(requests).pipe(Effect.as("sent" as const)),
199 Fiber.await(load).pipe(Effect.as("settled" as const)),
200 );
201}
202
203type HttpInput = ReturnType<typeof makeHarness>["input"];
204const LOADERS: ReadonlyArray<{
205 readonly name: string;
206 readonly method: string;
207 readonly path: string;
208 readonly response: unknown;
209 readonly expected: unknown;
210 readonly load: (
211 input: HttpInput,
212 ) => Effect.Effect<
213 unknown,
214 RemoteEnvironmentRequestError | PullRequestDiffLoader.PullRequestDiffCredentialRejectedError,
215 HttpClient.HttpClient
216 >;
217}> = [
218 {
219 name: "PR diff",
220 method: "POST",
221 path: "/api/pull-requests/diff",
222 response: DIFF_RESULT,
223 expected: DIFF_RESULT,
224 load: (input: HttpInput) =>
225 PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({ ...input, diff: DIFF }),
226 },
227 {
228 name: "session permissions",
229 method: "GET",
230 path: "/api/auth/session",
231 response: SESSION,
232 expected: SESSION,
233 load: fetchEnvironmentSessionState,
234 },
235 {
236 name: "shell snapshot",
237 method: "GET",
238 path: "/api/orchestration/shell",
239 response: SHELL,
240 expected: SHELL,
241 load: fetchEnvironmentShellSnapshot,
242 },
243 {
244 name: "thread transcript",
245 method: "GET",
246 path: `/api/orchestration/threads/${TRANSCRIPT.threadId}/transcript`,
247 response: encodeThreadTranscript(TRANSCRIPT),
248 expected: TRANSCRIPT,
249 load: (input: HttpInput) =>
250 fetchEnvironmentThreadTranscript({ ...input, threadId: TRANSCRIPT.threadId }),
251 },
252 {
253 name: "bounded thread snapshot",
254 method: "GET",
255 path: `/api/orchestration/threads/${THREAD.projection.thread.id}/bounded`,
256 response: encodeBoundedSnapshot(BOUNDED_THREAD),
257 expected: BOUNDED_THREAD,
258 load: (input: HttpInput) =>
259 fetchEnvironmentBoundedThreadSnapshot({ ...input, threadId: THREAD.projection.thread.id }),
260 },
261 {
262 name: "older thread history",
263 method: "GET",
264 path: `/api/orchestration/threads/${THREAD.projection.thread.id}/history`,
265 response: THREAD_HISTORY,
266 expected: THREAD_HISTORY,
267 load: (input: HttpInput) =>
268 fetchEnvironmentThreadHistoryPage({
269 ...input,
270 threadId: THREAD.projection.thread.id,
271 cursor: "older-page",
272 }),
273 },
274];
275
276describe("authenticated environment HTTP requests", () => {
277 it.effect.each(LOADERS)("rejects an invalid $name response", (loader) =>
278 Effect.gen(function* () {
279 const harness = makeHarness(() => Response.json({}));
280 const result = yield* loader
281 .load(harness.input)
282 .pipe(Effect.provide(harness.httpLayer), Effect.asVoid, Effect.flip);
283 expect(result._tag).toBe("RemoteEnvironmentAuthInvalidJsonError");
284 expect(harness.calls).toHaveLength(1);
285 }),
286 );
287
288 it.effect("keeps the status of a shell snapshot error that is not a declared error", () =>
289 Effect.gen(function* () {
290 const harness = makeHarness(() => Response.json({ error: "bad_gateway" }, { status: 502 }));
291 const error = yield* fetchEnvironmentShellSnapshot(harness.input).pipe(
292 Effect.provide(harness.httpLayer),
293 Effect.flip,
294 );
295 expect(error).toMatchObject({
296 _tag: "RemoteEnvironmentAuthUndeclaredStatusError",
297 status: 502,
298 });
299 }),
300 );
301
302 it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
303 Effect.gen(function* () {
304 const harness = makeHarness(() => Response.json(loader.response));
305 const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
306
307 expect(result).toEqual(loader.expected);
308 expect(harness.calls).toHaveLength(1);
309 const call = harness.calls[0]!;
310 const url = new URL(call.url);
311 expect(url.origin).toBe(CURRENT_ORIGIN);
312 expect(url.pathname).toBe(loader.path);
313 expect(call.init.method).toBe(loader.method);
314 expect(new Headers(call.init.headers).get("authorization")).toBe("DPoP current-token");
315 expect(new Headers(call.init.headers).get("dpop")).toBe("proof-1");
316 expect(call.init.credentials).toBeUndefined();
317 if (loader.path.startsWith("/api/orchestration/")) {
318 expect(new Headers(call.init.headers).get(ORCHESTRATION_PROTOCOL_HEADER)).toBe(
319 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
320 );
321 }
322 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
323 // The proof signs exactly the URL sent; signers drop the query for `htu`.
324 expect(harness.proofs).toEqual([
325 { method: loader.method, url: call.url, accessToken: "current-token" },
326 ]);
327 if (loader.name === "older thread history") {
328 expect(url.searchParams.get("cursor")).toBe("older-page");
329 }
330 expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
331 }),
332 );
333
334 // MCP-created thread ids contain ":", which the request path percent-encodes.
335 // The DPoP proof must sign the URL that is actually sent, or the environment
336 // rejects it as a URL mismatch.
337 const MCP_THREAD_ID = ThreadId.make("mcp:3534bc83-1c17-4a1e-9118-601c2766d355");
338 const MCP_THREAD_LOADERS: ReadonlyArray<
339 Pick<(typeof LOADERS)[number], "name" | "response" | "load">
340 > = [
341 {
342 name: "thread transcript",
343 response: encodeThreadTranscript(TRANSCRIPT),
344 load: (input: HttpInput) =>
345 fetchEnvironmentThreadTranscript({ ...input, threadId: MCP_THREAD_ID }),
346 },
347 {
348 name: "bounded thread snapshot",
349 response: encodeBoundedSnapshot(BOUNDED_THREAD),
350 load: (input: HttpInput) =>
351 fetchEnvironmentBoundedThreadSnapshot({ ...input, threadId: MCP_THREAD_ID }),
352 },
353 {
354 name: "older thread history",
355 response: THREAD_HISTORY,
356 load: (input: HttpInput) =>
357 fetchEnvironmentThreadHistoryPage({
358 ...input,
359 threadId: MCP_THREAD_ID,
360 cursor: "older-page",
361 }),
362 },
363 ];
364 it.effect.each(MCP_THREAD_LOADERS)(
365 "signs the sent URL for a $name of a thread id that needs encoding",
366 (loader) =>
367 Effect.gen(function* () {
368 const harness = makeHarness(() => Response.json(loader.response));
369 yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
370
371 const sent = harness.calls[0]!.url;
372 expect(new URL(sent).pathname).toContain("/mcp%3A3534bc83-");
373 expect(harness.proofs.map((proof) => proof.url)).toEqual([sent]);
374 }),
375 );
376
377 it.effect("retries a rejected diff once with a new token, endpoint, and proof", () =>
378 Effect.gen(function* () {
379 const harness = makeHarness((requestNumber) =>
380 requestNumber === 1 ? credentialRejectedResponse() : Response.json(DIFF_RESULT),
381 );
382 const result = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
383 ...harness.input,
384 diff: DIFF,
385 }).pipe(Effect.provide(harness.httpLayer));
386
387 expect(result).toEqual(DIFF_RESULT);
388 expect(harness.authorizations).toEqual([
389 { expectedEnvironmentId: TARGET.environmentId },
390 { expectedEnvironmentId: TARGET.environmentId, rejectedAccessToken: "current-token" },
391 ]);
392 expect(harness.calls.map((call) => call.url)).toEqual([
393 `${CURRENT_ORIGIN}/api/pull-requests/diff`,
394 `${RENEWED_ORIGIN}/api/pull-requests/diff`,
395 ]);
396 expect(
397 harness.calls.map((call) => new Headers(call.init.headers).get("authorization")),
398 ).toEqual(["DPoP current-token", "DPoP renewed-token"]);
399 expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual([
400 "proof-1",
401 "proof-2",
402 ]);
403 expect(harness.proofs[1]).toEqual({
404 method: "POST",
405 url: `${RENEWED_ORIGIN}/api/pull-requests/diff`,
406 accessToken: "renewed-token",
407 });
408 expect(harness.calls[1]!.init.body).toEqual(harness.calls[0]!.init.body);
409 }),
410 );
411
412 it.effect("renews credentials captured by the bounded snapshot loader", () =>
413 Effect.gen(function* () {
414 const harness = makeHarness((requestNumber) =>
415 requestNumber === 1
416 ? credentialRejectedResponse()
417 : Response.json(encodeBoundedSnapshot(BOUNDED_THREAD)),
418 );
419 const layerLoader = BoundedThreadSnapshotHttp.layer.pipe(
420 Layer.provide(
421 Layer.mergeAll(
422 harness.httpLayer,
423 Layer.succeed(
424 ManagedRelay.ManagedRelayDpopSigner,
425 Option.getOrThrow(harness.input.signer),
426 ),
427 Layer.succeed(
428 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
429 harness.remoteAuthorization,
430 ),
431 ),
432 ),
433 );
434 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader.pipe(
435 Effect.provide(layerLoader),
436 );
437 const result = yield* loader.load(PREPARED, THREAD.projection.thread.id);
438 expect(result).toEqual({
439 _tag: "present",
440 snapshot: { ...THREAD, latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal },
441 history: {
442 historyCursor: BOUNDED_THREAD.historyCursor,
443 hasMoreHistory: true,
444 latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal,
445 },
446 });
447 expect(harness.calls).toHaveLength(2);
448 expect(new Headers(harness.calls[1]!.init.headers).get("authorization")).toBe(
449 "DPoP renewed-token",
450 );
451 }),
452 );
453
454 it.effect("preserves the credential rejection after the one recovery attempt fails", () =>
455 Effect.gen(function* () {
456 const harness = makeHarness(() => credentialRejectedResponse());
457 const error = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
458 ...harness.input,
459 diff: DIFF,
460 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
461
462 expect(error).toMatchObject({
463 _tag: "PullRequestDiffCredentialRejectedError",
464 traceId: "trace-rejected",
465 });
466 expect(harness.calls).toHaveLength(2);
467 expect(harness.authorizations).toHaveLength(2);
468 }),
469 );
470
471 it.effect.each([
472 {
473 name: "insufficient scope",
474 reply: () =>
475 Response.json(
476 {
477 _tag: "EnvironmentScopeRequiredError",
478 code: "insufficient_scope",
479 requiredScope: "orchestration:read",
480 traceId: "trace-scope",
481 },
482 { status: 403 },
483 ),
484 errorTag: "EnvironmentScopeRequiredError",
485 },
486 {
487 name: "missing credential",
488 reply: () => credentialRejectedResponse("missing_credential"),
489 errorTag: "EnvironmentAuthInvalidError",
490 },
491 {
492 name: "Cloudflare 530",
493 reply: () => new Response("error code: 1033", { status: 530 }),
494 errorTag: "RemoteEnvironmentAuthUndeclaredStatusError",
495 },
496 {
497 name: "network failure",
498 reply: () => Promise.reject(new Error("Network unreachable")),
499 errorTag: "RemoteEnvironmentAuthFetchError",
500 },
501 ])("does not renew or retry on $name", ({ reply, errorTag }) =>
502 Effect.gen(function* () {
503 const harness = makeHarness(reply);
504 const error = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
505 ...harness.input,
506 diff: DIFF,
507 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
508
509 expect(error._tag).toBe(errorTag);
510 expect(harness.calls).toHaveLength(1);
511 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
512 }),
513 );
514
515 it.effect("recovers a session's unauthenticated 200 response before checking permissions", () =>
516 Effect.gen(function* () {
517 const harness = makeHarness((requestNumber) =>
518 Response.json(requestNumber === 1 ? UNAUTHENTICATED_SESSION : SESSION),
519 );
520 const result = yield* fetchEnvironmentSessionState(harness.input).pipe(
521 Effect.provide(harness.httpLayer),
522 );
523
524 expect(result).toEqual(SESSION);
525 expect(harness.authorizations[1]).toEqual({
526 expectedEnvironmentId: TARGET.environmentId,
527 rejectedAccessToken: "current-token",
528 });
529 expect(harness.calls).toHaveLength(2);
530 }),
531 );
532
533 it.effect(
534 "waits longer for session permissions after the environment is too slow to answer",
535 () =>
536 Effect.gen(function* () {
537 const requests = yield* Queue.unbounded<number>();
538 let answer: () => void = () => {};
539 const answered = new Promise<void>((resolve) => {
540 answer = resolve;
541 });
542 const harness = makeHarness((requestNumber) => {
543 Queue.offerUnsafe(requests, requestNumber);
544 return requestNumber === 1
545 ? new Promise<Response>(() => {})
546 : answered.then(() => Response.json(SESSION));
547 });
548 const load = yield* fetchEnvironmentSessionState({
549 prepared: { ...PREPARED, httpAuthorization: { _tag: "Bearer", token: "bearer-token" } },
550 signer: Option.none(),
551 timeoutMs: 1_000,
552 }).pipe(Effect.provide(harness.httpLayer), Effect.forkChild({ startImmediately: true }));
553
554 yield* Queue.take(requests);
555 yield* TestClock.adjust("1 second");
556 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
557 yield* TestClock.adjust("1500 millis");
558 answer();
559
560 expect(yield* Fiber.await(load)).toStrictEqual(Exit.succeed(SESSION));
561 expect(harness.calls).toHaveLength(2);
562 }),
563 );
564
565 it.effect("gives up on session permissions once a 60 second wait also times out", () =>
566 Effect.gen(function* () {
567 const requests = yield* Queue.unbounded<number>();
568 const harness = makeHarness((requestNumber) => {
569 Queue.offerUnsafe(requests, requestNumber);
570 return new Promise<Response>(() => {});
571 });
572 const load = yield* fetchEnvironmentSessionState({
573 prepared: { ...PREPARED, httpAuthorization: { _tag: "Bearer", token: "bearer-token" } },
574 signer: Option.none(),
575 timeoutMs: 15_000,
576 }).pipe(Effect.provide(harness.httpLayer), Effect.forkChild({ startImmediately: true }));
577
578 yield* Queue.take(requests);
579 yield* TestClock.adjust("15 seconds");
580 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
581 yield* TestClock.adjust("30 seconds");
582 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
583 yield* TestClock.adjust("60 seconds");
584 const exit = yield* Fiber.await(load);
585
586 expect(exit).toMatchObject({
587 _tag: "Failure",
588 cause: {
589 reasons: [{ error: { _tag: "RemoteEnvironmentAuthTimeoutError", timeoutMs: 60_000 } }],
590 },
591 });
592 expect(harness.calls).toHaveLength(3);
593 }),
594 );
595
596 it.effect("reports persistent session rejection instead of showing missing permissions", () =>
597 Effect.gen(function* () {
598 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
599 const error = yield* fetchEnvironmentSessionState(harness.input).pipe(
600 Effect.provide(harness.httpLayer),
601 Effect.flip,
602 );
603
604 expect(error).toMatchObject({
605 _tag: "RemoteEnvironmentAuthFetchError",
606 message: "The environment rejected the renewed session authorization.",
607 });
608 expect(harness.calls).toHaveLength(2);
609 const rejectedLookup = AsyncResult.failure<AuthSessionState, typeof error>(Cause.fail(error));
610 expect(sessionDeniesScope(rejectedLookup, "orchestration:read")).toBe(true);
611 }),
612 );
613
614 it.effect.each([
615 { name: "cookie", authorization: null },
616 { name: "bearer", authorization: { _tag: "Bearer", token: "bearer-token" } },
617 ] satisfies ReadonlyArray<{ name: string; authorization: PreparedHttpAuthorization | null }>)(
618 "leaves $name sessions unchanged without relay services",
619 ({ authorization }) =>
620 Effect.gen(function* () {
621 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
622 const result = yield* fetchEnvironmentSessionState({
623 prepared: { ...PREPARED, httpAuthorization: authorization },
624 signer: Option.none(),
625 }).pipe(Effect.provide(harness.httpLayer));
626
627 expect(result).toEqual(UNAUTHENTICATED_SESSION);
628 expect(harness.calls).toHaveLength(1);
629 expect(harness.authorizations).toEqual([]);
630 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
631 authorization === null ? null : "Bearer bearer-token",
632 );
633 expect(harness.calls[0]!.init.credentials).toBe(
634 authorization === null ? "include" : undefined,
635 );
636 }),
637 );
638
639 // Hosts from before the `/:use` ticket route answer 404 there but still issue bare tickets.
640 it.effect.each([
641 {
642 name: "bearer",
643 authorization: { _tag: "Bearer", token: "bearer-token" },
644 origin: PREPARED.httpBaseUrl,
645 },
646 {
647 name: "relay",
648 authorization: { _tag: "Dpop", accessToken: "expired-token", expiresAtEpochMs: 0 },
649 origin: CURRENT_ORIGIN,
650 },
651 ] satisfies ReadonlyArray<{
652 name: string;
653 authorization: PreparedHttpAuthorization;
654 origin: string;
655 }>)(
656 "falls back to the bare ticket path for $name media streams on a host without the audience route",
657 ({ authorization, origin }) =>
658 Effect.gen(function* () {
659 const harness = makeHarness((requestNumber) =>
660 requestNumber === 1
661 ? Response.json({ message: "Not Found" }, { status: 404 })
662 : Response.json({ ticket: "bare-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
663 );
664 const access = yield* resolveDeviceHubAccess({
665 prepared: { ...PREPARED, httpAuthorization: authorization },
666 hubBasePath: "/api/preview-stream",
667 }).pipe(
668 Effect.provide(harness.httpLayer),
669 Effect.provideService(
670 ManagedRelay.ManagedRelayDpopSigner,
671 Option.getOrThrow(harness.input.signer),
672 ),
673 Effect.provideService(
674 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
675 harness.remoteAuthorization,
676 ),
677 );
678
679 expect(access.query).toEqual({ wsTicket: "bare-ticket" });
680 expect(harness.calls.map((call) => call.url)).toEqual([
681 `${origin}/api/auth/websocket-ticket/media`,
682 `${origin}/api/auth/websocket-ticket`,
683 ]);
684 expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual(
685 authorization._tag === "Dpop" ? ["proof-1", "proof-2"] : [null, null],
686 );
687 expect(harness.proofs.map((proof) => proof.url)).toEqual(
688 authorization._tag === "Dpop" ? harness.calls.map((call) => call.url) : [],
689 );
690 }),
691 );
692
693 it.effect("reports renewal failure without sending the expired prepared token", () =>
694 Effect.gen(function* () {
695 const harness = makeHarness(() => Response.json(SESSION));
696 const failure = new ConnectionTransientError({
697 reason: "transport",
698 detail: "Relay unavailable",
699 });
700 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
701 ...harness.remoteAuthorization,
702 authorizeDpopHttp: () => Effect.fail(failure),
703 });
704 const error = yield* fetchEnvironmentSessionState({
705 ...harness.input,
706 remoteAuthorization: Option.some(remoteAuthorization),
707 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
708
709 expect(error).toMatchObject({
710 _tag: "RemoteEnvironmentAuthFetchError",
711 message: "Could not authorize the environment request.",
712 cause: failure,
713 });
714 expect(harness.calls).toEqual([]);
715 expect(harness.proofs).toEqual([]);
716 }),
717 );
718
719 it.effect("does not fall back to a captured DPoP token when authorization is unavailable", () =>
720 Effect.gen(function* () {
721 const harness = makeHarness(() => Response.json(SESSION));
722 const error = yield* fetchEnvironmentSessionState({
723 prepared: PREPARED,
724 signer: harness.input.signer,
725 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
726
727 expect(error).toMatchObject({
728 _tag: "RemoteEnvironmentAuthFetchError",
729 message: "No relay authorization service is available for the environment request.",
730 });
731 expect(harness.calls).toEqual([]);
732 }),
733 );
734
735 it.effect(
736 "checks the HTTP origin when a request cannot reach it, not on HTTP status responses or failed credential renewal",
737 () =>
738 Effect.gen(function* () {
739 const checks = yield* Ref.make(0);
740 const prepared: PreparedConnection = {
741 ...PREPARED,
742 httpAuthorization: { _tag: "Bearer", token: "bearer-token" },
743 };
744 const preparedRef = yield* SubscriptionRef.make(Option.some(prepared));
745 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
746 target: PREPARED.target,
747 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
748 session: yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none()),
749 prepared: preparedRef,
750 connect: Effect.void,
751 disconnect: Effect.void,
752 retryNow: Effect.void,
753 checkHttpOrigin: Ref.update(checks, (count) => count + 1),
754 });
755 const runSession = (respond: () => Response | Promise<Response>) =>
756 fetchEnvironmentSessionState({
757 prepared,
758 signer: Option.none(),
759 timeoutMs: 1_000,
760 }).pipe(
761 Effect.provide(RpcHttp.layerRemoteHttpClient(async () => respond())),
762 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
763 Effect.flip,
764 );
765
766 // An HTTP 500 proves the origin answered: do not trigger failover.
767 yield* runSession(() => Response.json({ message: "boom" }, { status: 500 }));
768 expect(yield* Ref.get(checks)).toBe(0);
769
770 // A network/DNS transport failure on a direct caller triggers an HTTP origin check.
771 yield* runSession(() => Promise.reject(new TypeError("Failed to fetch")));
772 expect(yield* Ref.get(checks)).toBe(1);
773
774 // A stalled DPoP renewal hitting the outer timeout never reached the environment origin.
775 const renewalHarness = makeHarness(() => Response.json(SESSION));
776 const stalledAuthorization =
777 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
778 ...renewalHarness.remoteAuthorization,
779 authorizeDpopHttp: () => Effect.never,
780 });
781 const dpopPreparedRef = yield* SubscriptionRef.make(Option.some(PREPARED));
782 const dpopSupervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
783 ...supervisor,
784 prepared: dpopPreparedRef,
785 });
786 const renewalFiber = yield* executeConnectedEnvironmentHttpRequest({
787 method: "GET",
788 url: (urls) => urls.session(),
789 timeoutMs: 1_000,
790 group: "auth",
791 request: ({ client, headers }) => client.session({ headers }),
792 }).pipe(
793 Effect.provide(renewalHarness.httpLayer),
794 Effect.provideService(
795 ManagedRelay.ManagedRelayDpopSigner,
796 Option.getOrThrow(renewalHarness.input.signer),
797 ),
798 Effect.provideService(
799 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
800 stalledAuthorization,
801 ),
802 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, dpopSupervisor),
803 Effect.flip,
804 Effect.forkChild,
805 );
806 yield* TestClock.adjust("1 second");
807 const renewalTimeout = yield* Fiber.join(renewalFiber);
808 expect(renewalTimeout._tag).toBe("RemoteEnvironmentAuthTimeoutError");
809 expect(renewalHarness.calls).toEqual([]);
810 expect(yield* Ref.get(checks)).toBe(1);
811
812 // A failed credential renewal belongs to the HTTP operation and must never replace the socket.
813 const directPrepared: PreparedConnection = {
814 ...PREPARED,
815 httpAuthorization: {
816 _tag: "Dpop",
817 accessToken: "expired-direct-token",
818 expiresAtEpochMs: 0,
819 directConnection: {
820 connectionId: "dpop:direct-1",
821 httpBaseUrl: PREPARED.httpBaseUrl,
822 },
823 },
824 };
825 const directPreparedRef = yield* SubscriptionRef.make(Option.some(directPrepared));
826 const directSupervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
827 ...supervisor,
828 prepared: directPreparedRef,
829 });
830 const runDirectRenewal = (
831 authorizeDirectDpopHttp: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDirectDpopHttp"],
832 ) =>
833 executeConnectedEnvironmentHttpRequest({
834 method: "GET",
835 url: (urls) => urls.session(),
836 timeoutMs: 1_000,
837 group: "auth",
838 request: ({ client, headers }) => client.session({ headers }),
839 }).pipe(
840 Effect.provide(renewalHarness.httpLayer),
841 Effect.provideService(
842 ManagedRelay.ManagedRelayDpopSigner,
843 Option.getOrThrow(renewalHarness.input.signer),
844 ),
845 Effect.provideService(
846 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
847 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
848 ...renewalHarness.remoteAuthorization,
849 authorizeDirectDpopHttp,
850 }),
851 ),
852 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, directSupervisor),
853 Effect.flip,
854 );
855
856 yield* runDirectRenewal(() =>
857 Effect.fail(
858 new ConnectionBlockedError({
859 reason: "authentication",
860 detail: "The environment credential is invalid.",
861 hop: "server",
862 via: "direct",
863 }),
864 ),
865 );
866 expect(yield* Ref.get(checks)).toBe(1);
867
868 yield* runDirectRenewal(() =>
869 Effect.fail(
870 new ConnectionTransientError({
871 reason: "network",
872 detail: "Could not resolve host.",
873 hop: "server",
874 via: "direct",
875 }),
876 ),
877 );
878 expect(yield* Ref.get(checks)).toBe(1);
879
880 const directTimeoutFiber = yield* runDirectRenewal(() => Effect.never).pipe(
881 Effect.forkChild,
882 );
883 yield* TestClock.adjust("1 second");
884 const directTimeout = yield* Fiber.join(directTimeoutFiber);
885 expect(directTimeout._tag).toBe("RemoteEnvironmentAuthTimeoutError");
886 expect(yield* Ref.get(checks)).toBe(1);
887
888 // A blocked registry lease lock must not delay the caller's timeout, and the detached lookup is bounded.
889 const lookupStarted = yield* Deferred.make<void>();
890 const lookupInterrupted = yield* Deferred.make<void>();
891 const blockedRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
892 run: () =>
893 Deferred.succeed(lookupStarted, undefined).pipe(
894 Effect.andThen(Effect.never),
895 Effect.onInterrupt(() => Deferred.succeed(lookupInterrupted, undefined)),
896 ),
897 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
898 const blockedTimeoutFiber = yield* executeAuthenticatedEnvironmentHttpRequest({
899 prepared,
900 signer: Option.none(),
901 method: "GET",
902 url: (urls) => urls.session(),
903 timeoutMs: 1_000,
904 group: "auth",
905 request: ({ client, headers }) => client.session({ headers }),
906 }).pipe(
907 Effect.provide(RpcHttp.layerRemoteHttpClient(() => new Promise<Response>(() => {}))),
908 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, blockedRegistry),
909 Effect.flip,
910 Effect.forkChild,
911 );
912 yield* TestClock.adjust("1 second");
913 const blockedTimeout = yield* Fiber.join(blockedTimeoutFiber);
914 expect(blockedTimeout._tag).toBe("RemoteEnvironmentAuthTimeoutError");
915 yield* Deferred.await(lookupStarted);
916 yield* TestClock.adjust("5 seconds");
917 yield* Deferred.await(lookupInterrupted);
918 }).pipe(Effect.provide(TestClock.layer())),
919 );
920});