Open History to see the last commit
1import { afterEach, describe, expect, it } from "vite-plus/test";
2import {
3 AuthOrchestrationReadScope,
4 AuthOrchestrationOperateScope,
5 AuthSessionId,
6 LOCAL_DEVICE_HOST_ID,
7 type AuthEnvironmentScope,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import { HttpClient, HttpClientResponse, HttpRouter } from "effect/http";
12import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
13import type * as DeviceHost from "./DeviceHost.ts";
14import * as DeviceService from "./DeviceService.ts";
15import * as DeviceHubProxy from "./DeviceHubProxy.ts";
16
17const disposers: Array<() => Promise<void>> = [];
18afterEach(async () => {
19 for (const dispose of disposers.splice(0)) await dispose();
20});
21
22const fixture = (
23 scopes: ReadonlyArray<AuthEnvironmentScope>,
24 fail = false,
25 authError?: EnvironmentAuth.ServerAuthCredentialError | EnvironmentAuth.ServerAuthInternalError,
26 upstream?: DeviceHost.DeviceHostReady["upstream"],
27) => {
28 let finalized = 0;
29 const requests: string[] = [];
30 const headers: Array<Readonly<Record<string, string>>> = [];
31 const client = HttpClient.make((request, _url, signal) =>
32 Effect.gen(function* () {
33 requests.push(request.url);
34 headers.push(request.headers);
35 signal.addEventListener("abort", () => {
36 finalized++;
37 });
38 if (fail) return yield* Effect.die(new Error("upstream failed"));
39 return HttpClientResponse.fromWeb(
40 request,
41 new Response("frame", { headers: { "set-cookie": "upstream=1" } }),
42 );
43 }),
44 );
45 const { handler, dispose } = HttpRouter.toWebHandler(
46 DeviceHubProxy.layer.pipe(
47 Layer.provideMerge(
48 Layer.succeed(EnvironmentAuth.EnvironmentAuth, {
49 authenticateWebSocketUpgrade: () =>
50 authError
51 ? Effect.fail(authError)
52 : Effect.succeed({
53 sessionId: AuthSessionId.make("test"),
54 subject: "test",
55 method: "bearer-access-token",
56 scopes,
57 }),
58 } as unknown as EnvironmentAuth.EnvironmentAuth["Service"]),
59 ),
60 Layer.provideMerge(
61 Layer.succeed(DeviceService.DeviceService, {
62 currentReadiness: () =>
63 Effect.succeed({
64 hostId: LOCAL_DEVICE_HOST_ID,
65 hub: { origin: "http://hub.test" },
66 ...(upstream ? { upstream } : {}),
67 }),
68 } as DeviceService.DeviceService["Service"]),
69 ),
70 Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
71 ),
72 { disableLogger: true },
73 );
74 disposers.push(dispose);
75 return { handler, requests, headers, finalized: () => finalized };
76};
77
78describe("device hub proxy", () => {
79 it("releases the upstream response after forwarding its body and strips tickets", async () => {
80 const { handler, requests, finalized } = fixture([AuthOrchestrationReadScope]);
81 const response = await handler(
82 new Request("http://t3.test/api/device-hub/api/devices?wsTicket=secret"),
83 );
84 expect(response.status).toBe(200);
85 expect(await response.text()).toBe("frame");
86 expect(requests).toEqual(["http://hub.test/api/devices"]);
87 expect(finalized()).toBe(1);
88 });
89
90 it("releases resources when upstream acquisition fails", async () => {
91 const { handler, finalized } = fixture([AuthOrchestrationReadScope], true);
92 const response = await handler(new Request("http://t3.test/api/device-hub/api/devices"));
93 expect(response.status).toBe(500);
94 expect(finalized()).toBe(1);
95 });
96
97 it.each(["/vendor/serve-sim/helper/ws", "/vendor/serve-emu/ws"])(
98 "rejects input socket %s for a read-only session",
99 async (path) => {
100 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
101 const response = await handler(
102 new Request(`http://t3.test/api/device-hub${path}`, { headers: { upgrade: "websocket" } }),
103 );
104 expect(response.status).toBe(403);
105 expect(requests).toEqual([]);
106 },
107 );
108
109 it("requires operate scope for stream tuning", async () => {
110 const readOnly = fixture([AuthOrchestrationReadScope]);
111 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/stream-settings";
112 expect((await readOnly.handler(new Request(path, { method: "POST" }))).status).toBe(403);
113 const operator = fixture([AuthOrchestrationOperateScope]);
114 const response = await operator.handler(new Request(path, { method: "POST" }));
115 expect(response.status).toBe(200);
116 await response.text();
117 });
118
119 it("reads Android fold state but requires operate scope to change it", async () => {
120 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554";
121 const reader = fixture([AuthOrchestrationReadScope]);
122 const read = await reader.handler(new Request(path));
123 expect(read.status).toBe(200);
124 await read.text();
125 expect(reader.requests).toEqual([
126 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
127 ]);
128 const denied = await reader.handler(
129 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
130 );
131 expect(denied.status).toBe(403);
132 expect(reader.requests).toHaveLength(1);
133
134 const operator = fixture([AuthOrchestrationOperateScope]);
135 const changed = await operator.handler(
136 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
137 );
138 expect(changed.status).toBe(200);
139 await changed.text();
140 expect(operator.requests).toEqual([
141 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
142 ]);
143 });
144
145 it("presents fold changes from an HTTPS client as same-origin hub requests", async () => {
146 const { handler, headers } = fixture([AuthOrchestrationOperateScope]);
147 const response = await handler(
148 new Request(
149 "https://relay.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554",
150 {
151 method: "POST",
152 headers: { origin: "https://relay.test", "x-forwarded-proto": "https" },
153 body: '{"posture":"opened"}',
154 },
155 ),
156 );
157 expect(response.status).toBe(200);
158 await response.text();
159 expect(headers).toHaveLength(1);
160 expect(headers[0]?.origin).toBe("http://hub.test");
161 expect(headers[0]).not.toHaveProperty("x-forwarded-proto");
162 });
163
164 it("lets a viewer negotiate a WebRTC stream with read scope", async () => {
165 const { handler, requests, headers } = fixture([AuthOrchestrationReadScope]);
166 const offer = await handler(
167 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-1/webrtc/offer", {
168 method: "POST",
169 headers: { "content-type": "application/json" },
170 body: '{"type":"offer"}',
171 }),
172 );
173 expect(offer.status).toBe(200);
174 await offer.text();
175 expect(requests).toEqual(["http://hub.test/vendor/serve-sim/helper/udid-1/webrtc/offer"]);
176 expect(headers[0]?.["content-type"]).toBe("application/json");
177 });
178
179 it("sends requests a host routes itself to its upstream with its credentials", async () => {
180 const { handler, requests, headers } = fixture(
181 [AuthOrchestrationReadScope],
182 false,
183 undefined,
184 (hubPath, search) =>
185 Effect.succeed(
186 hubPath === "/vendor/serve-sim/api"
187 ? {
188 url: `https://session.test${hubPath.slice("/vendor/serve-sim".length)}?${search}`,
189 headers: { authorization: "Bearer session-token" },
190 protocols: [],
191 }
192 : null,
193 ),
194 );
195 const routed = await handler(
196 new Request("http://t3.test/api/device-hub/vendor/serve-sim/api?device=udid-1&hostId=eas", {
197 headers: { authorization: "Bearer environment-token" },
198 }),
199 );
200 expect(routed.status).toBe(200);
201 expect(routed.headers.get("set-cookie")).toBeNull();
202 await routed.text();
203 expect(requests).toEqual(["https://session.test/api?device=udid-1"]);
204 expect(headers[0]?.authorization).toBe("Bearer session-token");
205 const unrouted = await handler(
206 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-2/stream.mjpeg"),
207 );
208 expect(unrouted.status).toBe(404);
209 expect(requests).toHaveLength(1);
210 });
211
212 it("never forwards the vendor shell endpoint", async () => {
213 const { handler, requests } = fixture([AuthOrchestrationOperateScope]);
214 expect(
215 (
216 await handler(
217 new Request("http://t3.test/api/device-hub/vendor/serve-sim/exec", { method: "POST" }),
218 )
219 ).status,
220 ).toBe(404);
221 expect(requests).toEqual([]);
222 });
223});
224
225it.each([
226 [new EnvironmentAuth.ServerAuthMissingCredentialError({}), 401],
227 [
228 new EnvironmentAuth.ServerAuthSessionCredentialValidationError({
229 cause: new Error("private credential diagnostic"),
230 }),
231 500,
232 ],
233] as const)("translates authentication failure to HTTP %s", async (error, status) => {
234 const { handler, requests } = fixture([], false, error);
235 const response = await handler(new Request("http://t3.test/api/device-hub/api/devices"));
236 expect(response.status).toBe(status);
237 expect(await response.text()).not.toContain("private credential diagnostic");
238 expect(requests).toEqual([]);
239});
240
241it.each([1, 3])(
242 "forwards fixed Duo display %s through the authenticated read proxy",
243 async (panel) => {
244 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
245 const route = `/vendor/serve-sim/helper/duo/panel/${panel}/stream.avcc`;
246 const response = await handler(
247 new Request(`http://t3.test/api/device-hub${route}?wsTicket=secret`),
248 );
249 expect(response.status).toBe(200);
250 await response.text();
251 expect(requests).toEqual([`http://hub.test${route}`]);
252 },
253);
254
255it.each(["/panel/2/stream.avcc", "/panel/1/webrtc/offer", "/panel/3/exec"])(
256 "rejects unsupported Duo route %s",
257 async (route) => {
258 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
259 const response = await handler(
260 new Request(`http://t3.test/api/device-hub/vendor/serve-sim/helper/duo${route}`),
261 );
262 expect(response.status).toBe(404);
263 expect(requests).toEqual([]);
264 },
265);