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 Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Fiber from "effect/Fiber";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Queue from "effect/Queue";
22import * as Schema from "effect/Schema";
23import * as TestClock from "effect/testing/TestClock";
24import type { HttpClient } from "effect/http";
25import { AsyncResult } from "effect/reactivity";
26
27import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
28import {
29 ConnectionTransientError,
30 RelayConnectionTarget,
31 type PreparedConnection,
32 type PreparedHttpAuthorization,
33} from "../connection/model.ts";
34import * as ManagedRelay from "../relay/managedRelay.ts";
35import { type RemoteEnvironmentRequestError } from "../rpc/http.ts";
36import * as RpcHttp from "../rpc/http.ts";
37import { resolveDeviceHubAccess } from "./deviceHubAccess.ts";
38import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
39import { fetchEnvironmentSessionState, sessionDeniesScope } from "./session.ts";
40import { fetchEnvironmentShellSnapshot } from "./shellSnapshotHttp.ts";
41import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
42import { fetchEnvironmentThreadTranscript } from "./threadTranscriptHttp.ts";
43import { fetchEnvironmentBoundedThreadSnapshot } from "./boundedThreadSnapshotHttp.ts";
44import * as BoundedThreadSnapshotHttp from "./boundedThreadSnapshotHttp.ts";
45import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts";
46import { v2Projection } from "./orchestrationV2TestFixtures.ts";
47
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 authorizeDirectDpop: () => Effect.die("HTTP requests must not prepare a WebSocket connection."),
138 authorizeDirectDpopHttp: () => Effect.die("Unexpected direct DPoP authorization."),
139 authorizeDpopHttp: (input) =>
140 Effect.sync(() => {
141 authorizations.push(input);
142 const rejected = input.rejectedAccessToken !== undefined;
143 return {
144 environmentId: TARGET.environmentId,
145 label: TARGET.label,
146 httpBaseUrl: rejected ? RENEWED_ORIGIN : CURRENT_ORIGIN,
147 httpAuthorization: {
148 _tag: "Dpop" as const,
149 accessToken: rejected ? "renewed-token" : "current-token",
150 expiresAtEpochMs: 3_600_000,
151 },
152 };
153 }),
154 rememberCheckedDescriptor: () => Effect.void,
155 renewDpopBeforeExpiry: () => Effect.die("HTTP requests must not renew a socket's token."),
156 });
157 const signer = ManagedRelay.ManagedRelayDpopSigner.of({
158 thumbprint: Effect.succeed("test-thumbprint"),
159 createProof: (input) =>
160 Effect.sync(() => {
161 proofs.push(input);
162 return `proof-${proofs.length}`;
163 }),
164 });
165 const fetchFn: typeof fetch = async (request, init) => {
166 calls.push({ url: String(request), init: init ?? {} });
167 return reply(calls.length);
168 };
169 return {
170 calls,
171 authorizations,
172 proofs,
173 remoteAuthorization,
174 input: {
175 prepared: PREPARED,
176 signer: Option.some(signer),
177 remoteAuthorization: Option.some(remoteAuthorization),
178 },
179 httpLayer: RpcHttp.layerRemoteHttpClient(fetchFn),
180 };
181}
182
183// Resolves "settled" instead of hanging when the load finishes without sending another request.
184function nextRequestOrSettled(requests: Queue.Queue<number>, load: Fiber.Fiber<unknown, unknown>) {
185 return Effect.raceFirst(
186 Queue.take(requests).pipe(Effect.as("sent" as const)),
187 Fiber.await(load).pipe(Effect.as("settled" as const)),
188 );
189}
190
191type HttpInput = ReturnType<typeof makeHarness>["input"];
192const LOADERS: ReadonlyArray<{
193 readonly name: string;
194 readonly method: string;
195 readonly path: string;
196 readonly response: unknown;
197 readonly expected: unknown;
198 readonly load: (
199 input: HttpInput,
200 ) => Effect.Effect<
201 unknown,
202 RemoteEnvironmentRequestError | PullRequestDiffLoader.PullRequestDiffCredentialRejectedError,
203 HttpClient.HttpClient
204 >;
205}> = [
206 {
207 name: "PR diff",
208 method: "POST",
209 path: "/api/pull-requests/diff",
210 response: DIFF_RESULT,
211 expected: DIFF_RESULT,
212 load: (input: HttpInput) =>
213 PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({ ...input, diff: DIFF }),
214 },
215 {
216 name: "session permissions",
217 method: "GET",
218 path: "/api/auth/session",
219 response: SESSION,
220 expected: SESSION,
221 load: fetchEnvironmentSessionState,
222 },
223 {
224 name: "shell snapshot",
225 method: "GET",
226 path: "/api/orchestration/shell",
227 response: SHELL,
228 expected: SHELL,
229 load: fetchEnvironmentShellSnapshot,
230 },
231 {
232 name: "thread transcript",
233 method: "GET",
234 path: `/api/orchestration/threads/${TRANSCRIPT.threadId}/transcript`,
235 response: encodeThreadTranscript(TRANSCRIPT),
236 expected: TRANSCRIPT,
237 load: (input: HttpInput) =>
238 fetchEnvironmentThreadTranscript({ ...input, threadId: TRANSCRIPT.threadId }),
239 },
240 {
241 name: "bounded thread snapshot",
242 method: "GET",
243 path: `/api/orchestration/threads/${THREAD.projection.thread.id}/bounded`,
244 response: encodeBoundedSnapshot(BOUNDED_THREAD),
245 expected: BOUNDED_THREAD,
246 load: (input: HttpInput) =>
247 fetchEnvironmentBoundedThreadSnapshot({ ...input, threadId: THREAD.projection.thread.id }),
248 },
249 {
250 name: "older thread history",
251 method: "GET",
252 path: `/api/orchestration/threads/${THREAD.projection.thread.id}/history`,
253 response: THREAD_HISTORY,
254 expected: THREAD_HISTORY,
255 load: (input: HttpInput) =>
256 fetchEnvironmentThreadHistoryPage({
257 ...input,
258 threadId: THREAD.projection.thread.id,
259 cursor: "older-page",
260 }),
261 },
262];
263
264describe("authenticated environment HTTP requests", () => {
265 it.effect.each(LOADERS)("rejects an invalid $name response", (loader) =>
266 Effect.gen(function* () {
267 const harness = makeHarness(() => Response.json({}));
268 const result = yield* loader
269 .load(harness.input)
270 .pipe(Effect.provide(harness.httpLayer), Effect.asVoid, Effect.flip);
271 expect(result._tag).toBe("RemoteEnvironmentAuthInvalidJsonError");
272 expect(harness.calls).toHaveLength(1);
273 }),
274 );
275
276 it.effect("keeps the status of a shell snapshot error that is not a declared error", () =>
277 Effect.gen(function* () {
278 const harness = makeHarness(() => Response.json({ error: "bad_gateway" }, { status: 502 }));
279 const error = yield* fetchEnvironmentShellSnapshot(harness.input).pipe(
280 Effect.provide(harness.httpLayer),
281 Effect.flip,
282 );
283 expect(error).toMatchObject({
284 _tag: "RemoteEnvironmentAuthUndeclaredStatusError",
285 status: 502,
286 });
287 }),
288 );
289
290 it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
291 Effect.gen(function* () {
292 const harness = makeHarness(() => Response.json(loader.response));
293 const result = yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
294
295 expect(result).toEqual(loader.expected);
296 expect(harness.calls).toHaveLength(1);
297 const call = harness.calls[0]!;
298 const url = new URL(call.url);
299 expect(url.origin).toBe(CURRENT_ORIGIN);
300 expect(url.pathname).toBe(loader.path);
301 expect(call.init.method).toBe(loader.method);
302 expect(new Headers(call.init.headers).get("authorization")).toBe("DPoP current-token");
303 expect(new Headers(call.init.headers).get("dpop")).toBe("proof-1");
304 expect(call.init.credentials).toBeUndefined();
305 if (loader.path.startsWith("/api/orchestration/")) {
306 expect(new Headers(call.init.headers).get(ORCHESTRATION_PROTOCOL_HEADER)).toBe(
307 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
308 );
309 }
310 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
311 // The proof signs exactly the URL sent; signers drop the query for `htu`.
312 expect(harness.proofs).toEqual([
313 { method: loader.method, url: call.url, accessToken: "current-token" },
314 ]);
315 if (loader.name === "older thread history") {
316 expect(url.searchParams.get("cursor")).toBe("older-page");
317 }
318 expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
319 }),
320 );
321
322 // MCP-created thread ids contain ":", which the request path percent-encodes.
323 // The DPoP proof must sign the URL that is actually sent, or the environment
324 // rejects it as a URL mismatch.
325 const MCP_THREAD_ID = ThreadId.make("mcp:3534bc83-1c17-4a1e-9118-601c2766d355");
326 const MCP_THREAD_LOADERS: ReadonlyArray<
327 Pick<(typeof LOADERS)[number], "name" | "response" | "load">
328 > = [
329 {
330 name: "thread transcript",
331 response: encodeThreadTranscript(TRANSCRIPT),
332 load: (input: HttpInput) =>
333 fetchEnvironmentThreadTranscript({ ...input, threadId: MCP_THREAD_ID }),
334 },
335 {
336 name: "bounded thread snapshot",
337 response: encodeBoundedSnapshot(BOUNDED_THREAD),
338 load: (input: HttpInput) =>
339 fetchEnvironmentBoundedThreadSnapshot({ ...input, threadId: MCP_THREAD_ID }),
340 },
341 {
342 name: "older thread history",
343 response: THREAD_HISTORY,
344 load: (input: HttpInput) =>
345 fetchEnvironmentThreadHistoryPage({
346 ...input,
347 threadId: MCP_THREAD_ID,
348 cursor: "older-page",
349 }),
350 },
351 ];
352 it.effect.each(MCP_THREAD_LOADERS)(
353 "signs the sent URL for a $name of a thread id that needs encoding",
354 (loader) =>
355 Effect.gen(function* () {
356 const harness = makeHarness(() => Response.json(loader.response));
357 yield* loader.load(harness.input).pipe(Effect.provide(harness.httpLayer));
358
359 const sent = harness.calls[0]!.url;
360 expect(new URL(sent).pathname).toContain("/mcp%3A3534bc83-");
361 expect(harness.proofs.map((proof) => proof.url)).toEqual([sent]);
362 }),
363 );
364
365 it.effect("retries a rejected diff once with a new token, endpoint, and proof", () =>
366 Effect.gen(function* () {
367 const harness = makeHarness((requestNumber) =>
368 requestNumber === 1 ? credentialRejectedResponse() : Response.json(DIFF_RESULT),
369 );
370 const result = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
371 ...harness.input,
372 diff: DIFF,
373 }).pipe(Effect.provide(harness.httpLayer));
374
375 expect(result).toEqual(DIFF_RESULT);
376 expect(harness.authorizations).toEqual([
377 { expectedEnvironmentId: TARGET.environmentId },
378 { expectedEnvironmentId: TARGET.environmentId, rejectedAccessToken: "current-token" },
379 ]);
380 expect(harness.calls.map((call) => call.url)).toEqual([
381 `${CURRENT_ORIGIN}/api/pull-requests/diff`,
382 `${RENEWED_ORIGIN}/api/pull-requests/diff`,
383 ]);
384 expect(
385 harness.calls.map((call) => new Headers(call.init.headers).get("authorization")),
386 ).toEqual(["DPoP current-token", "DPoP renewed-token"]);
387 expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual([
388 "proof-1",
389 "proof-2",
390 ]);
391 expect(harness.proofs[1]).toEqual({
392 method: "POST",
393 url: `${RENEWED_ORIGIN}/api/pull-requests/diff`,
394 accessToken: "renewed-token",
395 });
396 expect(harness.calls[1]!.init.body).toEqual(harness.calls[0]!.init.body);
397 }),
398 );
399
400 it.effect("renews credentials captured by the bounded snapshot loader", () =>
401 Effect.gen(function* () {
402 const harness = makeHarness((requestNumber) =>
403 requestNumber === 1
404 ? credentialRejectedResponse()
405 : Response.json(encodeBoundedSnapshot(BOUNDED_THREAD)),
406 );
407 const layerLoader = BoundedThreadSnapshotHttp.layer.pipe(
408 Layer.provide(
409 Layer.mergeAll(
410 harness.httpLayer,
411 Layer.succeed(
412 ManagedRelay.ManagedRelayDpopSigner,
413 Option.getOrThrow(harness.input.signer),
414 ),
415 Layer.succeed(
416 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
417 harness.remoteAuthorization,
418 ),
419 ),
420 ),
421 );
422 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader.pipe(
423 Effect.provide(layerLoader),
424 );
425 const result = yield* loader.load(PREPARED, THREAD.projection.thread.id);
426 expect(result).toEqual({
427 _tag: "present",
428 snapshot: { ...THREAD, latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal },
429 history: {
430 historyCursor: BOUNDED_THREAD.historyCursor,
431 hasMoreHistory: true,
432 latestLocalTurnOrdinal: BOUNDED_THREAD.latestLocalTurnOrdinal,
433 },
434 });
435 expect(harness.calls).toHaveLength(2);
436 expect(new Headers(harness.calls[1]!.init.headers).get("authorization")).toBe(
437 "DPoP renewed-token",
438 );
439 }),
440 );
441
442 it.effect("preserves the credential rejection after the one recovery attempt fails", () =>
443 Effect.gen(function* () {
444 const harness = makeHarness(() => credentialRejectedResponse());
445 const error = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
446 ...harness.input,
447 diff: DIFF,
448 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
449
450 expect(error).toMatchObject({
451 _tag: "PullRequestDiffCredentialRejectedError",
452 traceId: "trace-rejected",
453 });
454 expect(harness.calls).toHaveLength(2);
455 expect(harness.authorizations).toHaveLength(2);
456 }),
457 );
458
459 it.effect.each([
460 {
461 name: "insufficient scope",
462 reply: () =>
463 Response.json(
464 {
465 _tag: "EnvironmentScopeRequiredError",
466 code: "insufficient_scope",
467 requiredScope: "orchestration:read",
468 traceId: "trace-scope",
469 },
470 { status: 403 },
471 ),
472 errorTag: "EnvironmentScopeRequiredError",
473 },
474 {
475 name: "missing credential",
476 reply: () => credentialRejectedResponse("missing_credential"),
477 errorTag: "EnvironmentAuthInvalidError",
478 },
479 {
480 name: "Cloudflare 530",
481 reply: () => new Response("error code: 1033", { status: 530 }),
482 errorTag: "RemoteEnvironmentAuthUndeclaredStatusError",
483 },
484 {
485 name: "network failure",
486 reply: () => Promise.reject(new Error("Network unreachable")),
487 errorTag: "RemoteEnvironmentAuthFetchError",
488 },
489 ])("does not renew or retry on $name", ({ reply, errorTag }) =>
490 Effect.gen(function* () {
491 const harness = makeHarness(reply);
492 const error = yield* PullRequestDiffLoader.fetchEnvironmentPullRequestDiff({
493 ...harness.input,
494 diff: DIFF,
495 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
496
497 expect(error._tag).toBe(errorTag);
498 expect(harness.calls).toHaveLength(1);
499 expect(harness.authorizations).toEqual([{ expectedEnvironmentId: TARGET.environmentId }]);
500 }),
501 );
502
503 it.effect("recovers a session's unauthenticated 200 response before checking permissions", () =>
504 Effect.gen(function* () {
505 const harness = makeHarness((requestNumber) =>
506 Response.json(requestNumber === 1 ? UNAUTHENTICATED_SESSION : SESSION),
507 );
508 const result = yield* fetchEnvironmentSessionState(harness.input).pipe(
509 Effect.provide(harness.httpLayer),
510 );
511
512 expect(result).toEqual(SESSION);
513 expect(harness.authorizations[1]).toEqual({
514 expectedEnvironmentId: TARGET.environmentId,
515 rejectedAccessToken: "current-token",
516 });
517 expect(harness.calls).toHaveLength(2);
518 }),
519 );
520
521 it.effect(
522 "waits longer for session permissions after the environment is too slow to answer",
523 () =>
524 Effect.gen(function* () {
525 const requests = yield* Queue.unbounded<number>();
526 let answer: () => void = () => {};
527 const answered = new Promise<void>((resolve) => {
528 answer = resolve;
529 });
530 const harness = makeHarness((requestNumber) => {
531 Queue.offerUnsafe(requests, requestNumber);
532 return requestNumber === 1
533 ? new Promise<Response>(() => {})
534 : answered.then(() => Response.json(SESSION));
535 });
536 const load = yield* fetchEnvironmentSessionState({
537 prepared: { ...PREPARED, httpAuthorization: { _tag: "Bearer", token: "bearer-token" } },
538 signer: Option.none(),
539 timeoutMs: 1_000,
540 }).pipe(Effect.provide(harness.httpLayer), Effect.forkChild({ startImmediately: true }));
541
542 yield* Queue.take(requests);
543 yield* TestClock.adjust("1 second");
544 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
545 yield* TestClock.adjust("1500 millis");
546 answer();
547
548 expect(yield* Fiber.await(load)).toStrictEqual(Exit.succeed(SESSION));
549 expect(harness.calls).toHaveLength(2);
550 }),
551 );
552
553 it.effect("gives up on session permissions once a 60 second wait also times out", () =>
554 Effect.gen(function* () {
555 const requests = yield* Queue.unbounded<number>();
556 const harness = makeHarness((requestNumber) => {
557 Queue.offerUnsafe(requests, requestNumber);
558 return new Promise<Response>(() => {});
559 });
560 const load = yield* fetchEnvironmentSessionState({
561 prepared: { ...PREPARED, httpAuthorization: { _tag: "Bearer", token: "bearer-token" } },
562 signer: Option.none(),
563 timeoutMs: 15_000,
564 }).pipe(Effect.provide(harness.httpLayer), Effect.forkChild({ startImmediately: true }));
565
566 yield* Queue.take(requests);
567 yield* TestClock.adjust("15 seconds");
568 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
569 yield* TestClock.adjust("30 seconds");
570 expect(yield* nextRequestOrSettled(requests, load)).toBe("sent");
571 yield* TestClock.adjust("60 seconds");
572 const exit = yield* Fiber.await(load);
573
574 expect(exit).toMatchObject({
575 _tag: "Failure",
576 cause: {
577 reasons: [{ error: { _tag: "RemoteEnvironmentAuthTimeoutError", timeoutMs: 60_000 } }],
578 },
579 });
580 expect(harness.calls).toHaveLength(3);
581 }),
582 );
583
584 it.effect("reports persistent session rejection instead of showing missing permissions", () =>
585 Effect.gen(function* () {
586 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
587 const error = yield* fetchEnvironmentSessionState(harness.input).pipe(
588 Effect.provide(harness.httpLayer),
589 Effect.flip,
590 );
591
592 expect(error).toMatchObject({
593 _tag: "RemoteEnvironmentAuthFetchError",
594 message: "The environment rejected the renewed session authorization.",
595 });
596 expect(harness.calls).toHaveLength(2);
597 const rejectedLookup = AsyncResult.failure<AuthSessionState, typeof error>(Cause.fail(error));
598 expect(sessionDeniesScope(rejectedLookup, "orchestration:read")).toBe(true);
599 }),
600 );
601
602 it.effect.each([
603 { name: "cookie", authorization: null },
604 { name: "bearer", authorization: { _tag: "Bearer", token: "bearer-token" } },
605 ] satisfies ReadonlyArray<{ name: string; authorization: PreparedHttpAuthorization | null }>)(
606 "leaves $name sessions unchanged without relay services",
607 ({ authorization }) =>
608 Effect.gen(function* () {
609 const harness = makeHarness(() => Response.json(UNAUTHENTICATED_SESSION));
610 const result = yield* fetchEnvironmentSessionState({
611 prepared: { ...PREPARED, httpAuthorization: authorization },
612 signer: Option.none(),
613 }).pipe(Effect.provide(harness.httpLayer));
614
615 expect(result).toEqual(UNAUTHENTICATED_SESSION);
616 expect(harness.calls).toHaveLength(1);
617 expect(harness.authorizations).toEqual([]);
618 expect(new Headers(harness.calls[0]!.init.headers).get("authorization")).toBe(
619 authorization === null ? null : "Bearer bearer-token",
620 );
621 expect(harness.calls[0]!.init.credentials).toBe(
622 authorization === null ? "include" : undefined,
623 );
624 }),
625 );
626
627 // Hosts from before the `/:use` ticket route answer 404 there but still issue bare tickets.
628 it.effect.each([
629 {
630 name: "bearer",
631 authorization: { _tag: "Bearer", token: "bearer-token" },
632 origin: PREPARED.httpBaseUrl,
633 },
634 {
635 name: "relay",
636 authorization: { _tag: "Dpop", accessToken: "expired-token", expiresAtEpochMs: 0 },
637 origin: CURRENT_ORIGIN,
638 },
639 ] satisfies ReadonlyArray<{
640 name: string;
641 authorization: PreparedHttpAuthorization;
642 origin: string;
643 }>)(
644 "falls back to the bare ticket path for $name media streams on a host without the audience route",
645 ({ authorization, origin }) =>
646 Effect.gen(function* () {
647 const harness = makeHarness((requestNumber) =>
648 requestNumber === 1
649 ? Response.json({ message: "Not Found" }, { status: 404 })
650 : Response.json({ ticket: "bare-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
651 );
652 const access = yield* resolveDeviceHubAccess({
653 prepared: { ...PREPARED, httpAuthorization: authorization },
654 hubBasePath: "/api/preview-stream",
655 }).pipe(
656 Effect.provide(harness.httpLayer),
657 Effect.provideService(
658 ManagedRelay.ManagedRelayDpopSigner,
659 Option.getOrThrow(harness.input.signer),
660 ),
661 Effect.provideService(
662 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
663 harness.remoteAuthorization,
664 ),
665 );
666
667 expect(access.query).toEqual({ wsTicket: "bare-ticket" });
668 expect(harness.calls.map((call) => call.url)).toEqual([
669 `${origin}/api/auth/websocket-ticket/media`,
670 `${origin}/api/auth/websocket-ticket`,
671 ]);
672 expect(harness.calls.map((call) => new Headers(call.init.headers).get("dpop"))).toEqual(
673 authorization._tag === "Dpop" ? ["proof-1", "proof-2"] : [null, null],
674 );
675 expect(harness.proofs.map((proof) => proof.url)).toEqual(
676 authorization._tag === "Dpop" ? harness.calls.map((call) => call.url) : [],
677 );
678 }),
679 );
680
681 it.effect("reports renewal failure without sending the expired prepared token", () =>
682 Effect.gen(function* () {
683 const harness = makeHarness(() => Response.json(SESSION));
684 const failure = new ConnectionTransientError({
685 reason: "transport",
686 detail: "Relay unavailable",
687 });
688 const remoteAuthorization = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
689 ...harness.remoteAuthorization,
690 authorizeDpopHttp: () => Effect.fail(failure),
691 });
692 const error = yield* fetchEnvironmentSessionState({
693 ...harness.input,
694 remoteAuthorization: Option.some(remoteAuthorization),
695 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
696
697 expect(error).toMatchObject({
698 _tag: "RemoteEnvironmentAuthFetchError",
699 message: "Could not authorize the environment request.",
700 cause: failure,
701 });
702 expect(harness.calls).toEqual([]);
703 expect(harness.proofs).toEqual([]);
704 }),
705 );
706
707 it.effect("does not fall back to a captured DPoP token when authorization is unavailable", () =>
708 Effect.gen(function* () {
709 const harness = makeHarness(() => Response.json(SESSION));
710 const error = yield* fetchEnvironmentSessionState({
711 prepared: PREPARED,
712 signer: harness.input.signer,
713 }).pipe(Effect.provide(harness.httpLayer), Effect.flip);
714
715 expect(error).toMatchObject({
716 _tag: "RemoteEnvironmentAuthFetchError",
717 message: "No relay authorization service is available for the environment request.",
718 });
719 expect(harness.calls).toEqual([]);
720 }),
721 );
722});