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/unstable/http";
12import {
13 EnvironmentAuth,
14 ServerAuthMissingCredentialError,
15 ServerAuthSessionCredentialValidationError,
16 type ServerAuthCredentialError,
17 type ServerAuthInternalError,
18} from "../auth/EnvironmentAuth.ts";
19import { DeviceService } from "./DeviceService.ts";
20import { deviceHubProxyRouteLayer } from "./DeviceHubProxy.ts";
21
22const disposers: Array<() => Promise<void>> = [];
23afterEach(async () => {
24 for (const dispose of disposers.splice(0)) await dispose();
25});
26
27const fixture = (
28 scopes: ReadonlyArray<AuthEnvironmentScope>,
29 fail = false,
30 authError?: ServerAuthCredentialError | ServerAuthInternalError,
31) => {
32 let finalized = 0;
33 const requests: string[] = [];
34 const client = HttpClient.make((request, _url, signal) =>
35 Effect.gen(function* () {
36 requests.push(request.url);
37 signal.addEventListener("abort", () => {
38 finalized++;
39 });
40 if (fail) return yield* Effect.die(new Error("upstream failed"));
41 return HttpClientResponse.fromWeb(request, new Response("frame"));
42 }),
43 );
44 const { handler, dispose } = HttpRouter.toWebHandler(
45 deviceHubProxyRouteLayer.pipe(
46 Layer.provideMerge(
47 Layer.succeed(EnvironmentAuth, {
48 authenticateWebSocketUpgrade: () =>
49 authError
50 ? Effect.fail(authError)
51 : Effect.succeed({
52 sessionId: AuthSessionId.make("test"),
53 subject: "test",
54 method: "bearer-access-token",
55 scopes,
56 }),
57 } as unknown as EnvironmentAuth["Service"]),
58 ),
59 Layer.provideMerge(
60 Layer.succeed(DeviceService, {
61 currentReadiness: () =>
62 Effect.succeed({ hostId: LOCAL_DEVICE_HOST_ID, hub: { origin: "http://hub.test" } }),
63 } as DeviceService["Service"]),
64 ),
65 Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
66 ),
67 { disableLogger: true },
68 );
69 disposers.push(dispose);
70 return { handler, requests, finalized: () => finalized };
71};
72
73describe("device hub proxy", () => {
74 it("releases the upstream response after forwarding its body and strips tickets", async () => {
75 const { handler, requests, finalized } = fixture([AuthOrchestrationReadScope]);
76 const response = await handler(
77 new Request("http://t3.test/api/device-hub/api/devices?wsTicket=secret"),
78 );
79 expect(response.status).toBe(200);
80 expect(await response.text()).toBe("frame");
81 expect(requests).toEqual(["http://hub.test/api/devices"]);
82 expect(finalized()).toBe(1);
83 });
84
85 it("releases resources when upstream acquisition fails", async () => {
86 const { handler, finalized } = fixture([AuthOrchestrationReadScope], true);
87 const response = await handler(new Request("http://t3.test/api/device-hub/api/devices"));
88 expect(response.status).toBe(500);
89 expect(finalized()).toBe(1);
90 });
91
92 it.each(["/vendor/serve-sim/helper/ws", "/vendor/serve-emu/ws"])(
93 "rejects input socket %s for a read-only session",
94 async (path) => {
95 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
96 const response = await handler(
97 new Request(`http://t3.test/api/device-hub${path}`, { headers: { upgrade: "websocket" } }),
98 );
99 expect(response.status).toBe(403);
100 expect(requests).toEqual([]);
101 },
102 );
103
104 it("requires operate scope for stream tuning", async () => {
105 const readOnly = fixture([AuthOrchestrationReadScope]);
106 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/stream-settings";
107 expect((await readOnly.handler(new Request(path, { method: "POST" }))).status).toBe(403);
108 const operator = fixture([AuthOrchestrationOperateScope]);
109 const response = await operator.handler(new Request(path, { method: "POST" }));
110 expect(response.status).toBe(200);
111 await response.text();
112 });
113
114 it("reads Android fold state but requires operate scope to change it", async () => {
115 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554";
116 const reader = fixture([AuthOrchestrationReadScope]);
117 const read = await reader.handler(new Request(path));
118 expect(read.status).toBe(200);
119 await read.text();
120 expect(reader.requests).toEqual([
121 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
122 ]);
123 const denied = await reader.handler(
124 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
125 );
126 expect(denied.status).toBe(403);
127 expect(reader.requests).toHaveLength(1);
128
129 const operator = fixture([AuthOrchestrationOperateScope]);
130 const changed = await operator.handler(
131 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
132 );
133 expect(changed.status).toBe(200);
134 await changed.text();
135 expect(operator.requests).toEqual([
136 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
137 ]);
138 });
139
140 it("never forwards the vendor shell endpoint", async () => {
141 const { handler, requests } = fixture([AuthOrchestrationOperateScope]);
142 expect(
143 (
144 await handler(
145 new Request("http://t3.test/api/device-hub/vendor/serve-sim/exec", { method: "POST" }),
146 )
147 ).status,
148 ).toBe(404);
149 expect(requests).toEqual([]);
150 });
151});
152
153it.each([
154 [new ServerAuthMissingCredentialError({}), 401],
155 [
156 new ServerAuthSessionCredentialValidationError({
157 cause: new Error("private credential diagnostic"),
158 }),
159 500,
160 ],
161] as const)("translates authentication failure to HTTP %s", async (error, status) => {
162 const { handler, requests } = fixture([], false, error);
163 const response = await handler(new Request("http://t3.test/api/device-hub/api/devices"));
164 expect(response.status).toBe(status);
165 expect(await response.text()).not.toContain("private credential diagnostic");
166 expect(requests).toEqual([]);
167});
168
169it.each([1, 3])(
170 "forwards fixed Duo display %s through the authenticated read proxy",
171 async (panel) => {
172 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
173 const route = `/vendor/serve-sim/helper/duo/panel/${panel}/stream.avcc`;
174 const response = await handler(
175 new Request(`http://t3.test/api/device-hub${route}?wsTicket=secret`),
176 );
177 expect(response.status).toBe(200);
178 await response.text();
179 expect(requests).toEqual([`http://hub.test${route}`]);
180 },
181);
182
183it.each(["/panel/2/stream.avcc", "/panel/1/webrtc/offer", "/panel/3/exec"])(
184 "rejects unsupported Duo route %s",
185 async (route) => {
186 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
187 const response = await handler(
188 new Request(`http://t3.test/api/device-hub/vendor/serve-sim/helper/duo${route}`),
189 );
190 expect(response.status).toBe(404);
191 expect(requests).toEqual([]);
192 },
193);