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

DeviceHubProxy.test.ts

267 lines10.2 KB

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.each(["/vendor/serve-sim/helper/ws", "/vendor/serve-emu/ws"])(
91 "rejects input socket %s for a read-only session",
92 async (path) => {
93 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
94 const response = await handler(
95 new Request(`http://t3.test/api/device-hub${path}`, { headers: { upgrade: "websocket" } }),
96 );
97 expect(response.status).toBe(403);
98 expect(requests).toEqual([]);
99 },
100 );
101​
102 it("requires operate scope for stream tuning", async () => {
103 const readOnly = fixture([AuthOrchestrationReadScope]);
104 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/stream-settings";
105 expect((await readOnly.handler(new Request(path, { method: "POST" }))).status).toBe(403);
106 const operator = fixture([AuthOrchestrationOperateScope]);
107 const response = await operator.handler(new Request(path, { method: "POST" }));
108 expect(response.status).toBe(200);
109 await response.text();
110 });
111​
112 it("reads Android fold state but requires operate scope to change it", async () => {
113 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554";
114 const reader = fixture([AuthOrchestrationReadScope]);
115 const read = await reader.handler(new Request(path));
116 expect(read.status).toBe(200);
117 await read.text();
118 expect(reader.requests).toEqual([
119 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
120 ]);
121 const denied = await reader.handler(
122 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
123 );
124 expect(denied.status).toBe(403);
125 expect(reader.requests).toHaveLength(1);
126​
127 const operator = fixture([AuthOrchestrationOperateScope]);
128 const changed = await operator.handler(
129 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
130 );
131 expect(changed.status).toBe(200);
132 await changed.text();
133 expect(operator.requests).toEqual([
134 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
135 ]);
136 });
137​
138 it("presents fold changes from an HTTPS client as same-origin hub requests", async () => {
139 const { handler, headers } = fixture([AuthOrchestrationOperateScope]);
140 const response = await handler(
141 new Request(
142 "https://relay.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554",
143 {
144 method: "POST",
145 headers: { origin: "https://relay.test", "x-forwarded-proto": "https" },
146 body: '{"posture":"opened"}',
147 },
148 ),
149 );
150 expect(response.status).toBe(200);
151 await response.text();
152 expect(headers).toHaveLength(1);
153 expect(headers[0]?.origin).toBe("http://hub.test");
154 expect(headers[0]).not.toHaveProperty("x-forwarded-proto");
155 });
156​
157 it("lets a viewer negotiate a WebRTC stream with read scope", async () => {
158 const { handler, requests, headers } = fixture([AuthOrchestrationReadScope]);
159 const offer = await handler(
160 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-1/webrtc/offer", {
161 method: "POST",
162 headers: { "content-type": "application/json" },
163 body: '{"type":"offer"}',
164 }),
165 );
166 expect(offer.status).toBe(200);
167 await offer.text();
168 expect(requests).toEqual(["http://hub.test/vendor/serve-sim/helper/udid-1/webrtc/offer"]);
169 expect(headers[0]?.["content-type"]).toBe("application/json");
170 });
171​
172 it("lets a viewer read Android stream capabilities and signal WebRTC with read scope", async () => {
173 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
174 const hub = "http://t3.test/api/device-hub/vendor/serve-emu";
175 const api = await handler(new Request(`${hub}/api?device=session-1`));
176 expect(api.status).toBe(200);
177 await api.text();
178 for (const action of ["offer", "close"]) {
179 const signal = await handler(
180 new Request(`${hub}/webrtc/${action}?device=session-1`, {
181 method: "POST",
182 headers: { "content-type": "application/json" },
183 body: '{"sessionId":"viewer"}',
184 }),
185 );
186 expect(signal.status).toBe(200);
187 await signal.text();
188 }
189 expect(requests).toEqual([
190 "http://hub.test/vendor/serve-emu/api?device=session-1",
191 "http://hub.test/vendor/serve-emu/webrtc/offer?device=session-1",
192 "http://hub.test/vendor/serve-emu/webrtc/close?device=session-1",
193 ]);
194 expect((await handler(new Request(`${hub}/api`, { method: "POST" }))).status).toBe(405);
195 expect((await handler(new Request(`${hub}/webrtc/offer`))).status).toBe(405);
196 });
197​
198 it("sends requests a host routes itself to its upstream with its credentials", async () => {
199 const { handler, requests, headers } = fixture(
200 [AuthOrchestrationReadScope],
201 false,
202 undefined,
203 (hubPath, search) =>
204 Effect.succeed(
205 hubPath === "/vendor/serve-sim/api"
206 ? {
207 url: `https://session.test${hubPath.slice("/vendor/serve-sim".length)}?${search}`,
208 headers: { authorization: "Bearer session-token" },
209 protocols: [],
210 }
211 : null,
212 ),
213 );
214 const routed = await handler(
215 new Request("http://t3.test/api/device-hub/vendor/serve-sim/api?device=udid-1&hostId=eas", {
216 headers: { authorization: "Bearer environment-token" },
217 }),
218 );
219 expect(routed.status).toBe(200);
220 expect(routed.headers.get("set-cookie")).toBeNull();
221 await routed.text();
222 expect(requests).toEqual(["https://session.test/api?device=udid-1"]);
223 expect(headers[0]?.authorization).toBe("Bearer session-token");
224 const unrouted = await handler(
225 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-2/stream.mjpeg"),
226 );
227 expect(unrouted.status).toBe(404);
228 expect(requests).toHaveLength(1);
229 });
230​
231 it("never forwards the vendor shell endpoint", async () => {
232 const { handler, requests } = fixture([AuthOrchestrationOperateScope]);
233 expect(
234 (
235 await handler(
236 new Request("http://t3.test/api/device-hub/vendor/serve-sim/exec", { method: "POST" }),
237 )
238 ).status,
239 ).toBe(404);
240 expect(requests).toEqual([]);
241 });
242});
243​
244it.each([
245 [new EnvironmentAuth.ServerAuthMissingCredentialError({}), 401],
246 [
247 new EnvironmentAuth.ServerAuthSessionCredentialValidationError({
248 cause: new Error("private credential diagnostic"),
249 }),
250 500,
251 ],
252] as const)("translates authentication failure to HTTP %s", async (error, status) => {
253 const { handler, requests } = fixture([], false, error);
254 const response = await handler(new Request("http://t3.test/api/device-hub/api/devices"));
255 expect(response.status).toBe(status);
256 expect(await response.text()).not.toContain("private credential diagnostic");
257 expect(requests).toEqual([]);
258});
259​
260it("rejects unsupported Duo routes", async () => {
261 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
262 const response = await handler(
263 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/duo/panel/1/webrtc/offer"),
264 );
265 expect(response.status).toBe(404);
266 expect(requests).toEqual([]);
267});