Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

environmentHttpAuth.test.ts

729 lines27.0 KB

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