|
| 1 | +// Product proof for audio media-understanding proxy routing and size preflight. |
| 2 | +import fs from "node:fs/promises"; |
| 3 | +import { |
| 4 | + createServer, |
| 5 | + request as httpRequest, |
| 6 | + type IncomingHttpHeaders, |
| 7 | + type Server, |
| 8 | + type ServerResponse, |
| 9 | +} from "node:http"; |
| 10 | +import net, { type AddressInfo, type Socket } from "node:net"; |
| 11 | +import os from "node:os"; |
| 12 | +import path from "node:path"; |
| 13 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 14 | +import { openaiMediaUnderstandingProvider } from "../../../../extensions/openai/api.js"; |
| 15 | +import type { MsgContext } from "../../../../src/auto-reply/templating.js"; |
| 16 | +import type { OpenClawConfig } from "../../../../src/config/types.js"; |
| 17 | +import { applyMediaUnderstanding } from "../../../../src/media-understanding/apply.js"; |
| 18 | +import { withEnvAsync } from "../../../../src/test-utils/env.js"; |
| 19 | + |
| 20 | +vi.mock("../../../../src/plugins/capability-provider-runtime.js", () => ({ |
| 21 | + resolvePluginCapabilityProviders: () => [], |
| 22 | +})); |
| 23 | + |
| 24 | +type RequestObservation = { |
| 25 | + body: Buffer; |
| 26 | + headers: IncomingHttpHeaders; |
| 27 | + method: string | undefined; |
| 28 | + remotePort: number | undefined; |
| 29 | + url: string | undefined; |
| 30 | +}; |
| 31 | + |
| 32 | +type LoopbackServer = { |
| 33 | + server: Server; |
| 34 | + sockets: Set<Socket>; |
| 35 | + url: string; |
| 36 | +}; |
| 37 | + |
| 38 | +let tempRoot: string | undefined; |
| 39 | + |
| 40 | +afterEach(async () => { |
| 41 | + if (!tempRoot) { |
| 42 | + return; |
| 43 | + } |
| 44 | + await fs.rm(tempRoot, { recursive: true, force: true }); |
| 45 | + tempRoot = undefined; |
| 46 | +}); |
| 47 | + |
| 48 | +async function listen(server: Server): Promise<LoopbackServer> { |
| 49 | + const sockets = new Set<Socket>(); |
| 50 | + server.on("connection", (socket) => { |
| 51 | + sockets.add(socket); |
| 52 | + socket.once("close", () => sockets.delete(socket)); |
| 53 | + }); |
| 54 | + await new Promise<void>((resolve, reject) => { |
| 55 | + server.once("error", reject); |
| 56 | + server.listen(0, "127.0.0.1", () => { |
| 57 | + server.off("error", reject); |
| 58 | + resolve(); |
| 59 | + }); |
| 60 | + }); |
| 61 | + const address = server.address() as AddressInfo; |
| 62 | + return { server, sockets, url: `http://127.0.0.1:${address.port}` }; |
| 63 | +} |
| 64 | + |
| 65 | +async function closeServer(handle: LoopbackServer): Promise<void> { |
| 66 | + for (const socket of handle.sockets) { |
| 67 | + socket.destroy(); |
| 68 | + } |
| 69 | + handle.server.closeAllConnections?.(); |
| 70 | + await new Promise<void>((resolve, reject) => { |
| 71 | + handle.server.close((error) => { |
| 72 | + if (error) { |
| 73 | + reject(error); |
| 74 | + return; |
| 75 | + } |
| 76 | + resolve(); |
| 77 | + }); |
| 78 | + }); |
| 79 | +} |
| 80 | + |
| 81 | +function collectRequestBody(request: NodeJS.ReadableStream): Promise<Buffer> { |
| 82 | + return new Promise<Buffer>((resolve, reject) => { |
| 83 | + const chunks: Buffer[] = []; |
| 84 | + request.on("data", (chunk: Buffer | string) => { |
| 85 | + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); |
| 86 | + }); |
| 87 | + request.on("end", () => resolve(Buffer.concat(chunks))); |
| 88 | + request.on("error", reject); |
| 89 | + }); |
| 90 | +} |
| 91 | + |
| 92 | +function withRequestBody( |
| 93 | + request: NodeJS.ReadableStream, |
| 94 | + response: ServerResponse, |
| 95 | + handle: (body: Buffer) => void, |
| 96 | +): void { |
| 97 | + void collectRequestBody(request) |
| 98 | + .then(handle) |
| 99 | + .catch((error: unknown) => { |
| 100 | + response.destroy(error instanceof Error ? error : new Error(String(error))); |
| 101 | + }); |
| 102 | +} |
| 103 | + |
| 104 | +async function startProviderServer(observations: RequestObservation[]): Promise<LoopbackServer> { |
| 105 | + return await listen( |
| 106 | + createServer((request, response) => { |
| 107 | + withRequestBody(request, response, (body) => { |
| 108 | + observations.push({ |
| 109 | + body, |
| 110 | + headers: request.headers, |
| 111 | + method: request.method, |
| 112 | + remotePort: request.socket.remotePort, |
| 113 | + url: request.url, |
| 114 | + }); |
| 115 | + response.writeHead(200, { "content-type": "application/json", connection: "close" }); |
| 116 | + response.end(JSON.stringify({ text: "proxied audio transcript" })); |
| 117 | + }); |
| 118 | + }), |
| 119 | + ); |
| 120 | +} |
| 121 | + |
| 122 | +async function startForwardProxy( |
| 123 | + observations: RequestObservation[], |
| 124 | + upstreamLocalPorts: Set<number>, |
| 125 | +): Promise<LoopbackServer> { |
| 126 | + const server = createServer((request, response) => { |
| 127 | + withRequestBody(request, response, (body) => { |
| 128 | + observations.push({ |
| 129 | + body, |
| 130 | + headers: request.headers, |
| 131 | + method: request.method, |
| 132 | + remotePort: request.socket.remotePort, |
| 133 | + url: request.url, |
| 134 | + }); |
| 135 | + |
| 136 | + let target: URL; |
| 137 | + try { |
| 138 | + target = new URL(request.url ?? ""); |
| 139 | + } catch { |
| 140 | + response.writeHead(400, { connection: "close" }); |
| 141 | + response.end("absolute-form proxy URL required"); |
| 142 | + return; |
| 143 | + } |
| 144 | + |
| 145 | + const upstream = httpRequest( |
| 146 | + { |
| 147 | + hostname: target.hostname, |
| 148 | + port: target.port, |
| 149 | + method: request.method, |
| 150 | + path: `${target.pathname}${target.search}`, |
| 151 | + headers: { |
| 152 | + ...request.headers, |
| 153 | + connection: "close", |
| 154 | + host: target.host, |
| 155 | + "x-qa-proxy-hop": "audio-media-understanding", |
| 156 | + }, |
| 157 | + }, |
| 158 | + (upstreamResponse) => { |
| 159 | + response.writeHead(upstreamResponse.statusCode ?? 502, { |
| 160 | + ...upstreamResponse.headers, |
| 161 | + connection: "close", |
| 162 | + }); |
| 163 | + upstreamResponse.pipe(response); |
| 164 | + }, |
| 165 | + ); |
| 166 | + upstream.on("error", (error) => { |
| 167 | + response.writeHead(502, { "content-type": "text/plain", connection: "close" }); |
| 168 | + response.end(error.message); |
| 169 | + }); |
| 170 | + upstream.on("socket", (socket) => { |
| 171 | + const recordPort = () => { |
| 172 | + if (socket.localPort) { |
| 173 | + upstreamLocalPorts.add(socket.localPort); |
| 174 | + } |
| 175 | + }; |
| 176 | + if (socket.connecting) { |
| 177 | + socket.once("connect", recordPort); |
| 178 | + } else { |
| 179 | + recordPort(); |
| 180 | + } |
| 181 | + }); |
| 182 | + upstream.end(body); |
| 183 | + }); |
| 184 | + }); |
| 185 | + server.on("connect", (request, clientSocket, head) => { |
| 186 | + observations.push({ |
| 187 | + body: Buffer.alloc(0), |
| 188 | + headers: request.headers, |
| 189 | + method: request.method, |
| 190 | + remotePort: (clientSocket as Socket).remotePort, |
| 191 | + url: request.url, |
| 192 | + }); |
| 193 | + let target: URL; |
| 194 | + try { |
| 195 | + target = new URL(`http://${request.url ?? ""}`); |
| 196 | + } catch { |
| 197 | + clientSocket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"); |
| 198 | + return; |
| 199 | + } |
| 200 | + const upstream = net.connect(Number(target.port), target.hostname, () => { |
| 201 | + if (upstream.localPort) { |
| 202 | + upstreamLocalPorts.add(upstream.localPort); |
| 203 | + } |
| 204 | + clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n"); |
| 205 | + if (head.length > 0) { |
| 206 | + upstream.write(head); |
| 207 | + } |
| 208 | + upstream.pipe(clientSocket); |
| 209 | + clientSocket.pipe(upstream); |
| 210 | + }); |
| 211 | + upstream.on("error", () => { |
| 212 | + clientSocket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); |
| 213 | + }); |
| 214 | + }); |
| 215 | + return await listen(server); |
| 216 | +} |
| 217 | + |
| 218 | +function createConfig(providerBaseUrl: string, maxBytes: number): OpenClawConfig { |
| 219 | + return { |
| 220 | + models: { |
| 221 | + providers: { |
| 222 | + openai: { |
| 223 | + apiKey: "test", |
| 224 | + baseUrl: providerBaseUrl, |
| 225 | + request: { allowPrivateNetwork: true }, |
| 226 | + models: [], |
| 227 | + }, |
| 228 | + }, |
| 229 | + }, |
| 230 | + tools: { |
| 231 | + media: { |
| 232 | + models: [{ provider: "openai", model: "gpt-4o-transcribe", capabilities: ["audio"] }], |
| 233 | + audio: { |
| 234 | + enabled: true, |
| 235 | + maxBytes, |
| 236 | + }, |
| 237 | + }, |
| 238 | + }, |
| 239 | + }; |
| 240 | +} |
| 241 | + |
| 242 | +async function createAudioContext( |
| 243 | + fileName: string, |
| 244 | + size: number, |
| 245 | +): Promise<{ |
| 246 | + ctx: MsgContext; |
| 247 | + filePath: string; |
| 248 | + workspaceDir: string; |
| 249 | +}> { |
| 250 | + tempRoot ??= await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-audio-qa-"))); |
| 251 | + const filePath = path.join(tempRoot, fileName); |
| 252 | + await fs.writeFile(filePath, Buffer.alloc(size, 0x52)); |
| 253 | + return { |
| 254 | + ctx: { |
| 255 | + Body: "", |
| 256 | + media: [{ path: filePath, contentType: "audio/wav" }], |
| 257 | + }, |
| 258 | + filePath, |
| 259 | + workspaceDir: tempRoot, |
| 260 | + }; |
| 261 | +} |
| 262 | + |
| 263 | +describe("media.audio-proxy-and-limit-handling", () => { |
| 264 | + it("routes provider audio through the proxy and rejects oversized audio before network IO", async () => { |
| 265 | + const proxyRequests: RequestObservation[] = []; |
| 266 | + const providerRequests: RequestObservation[] = []; |
| 267 | + const proxyUpstreamPorts = new Set<number>(); |
| 268 | + const provider = await startProviderServer(providerRequests); |
| 269 | + const proxy = await startForwardProxy(proxyRequests, proxyUpstreamPorts); |
| 270 | + |
| 271 | + try { |
| 272 | + await withEnvAsync( |
| 273 | + { |
| 274 | + HTTPS_PROXY: proxy.url, |
| 275 | + HTTP_PROXY: proxy.url, |
| 276 | + ALL_PROXY: "", |
| 277 | + https_proxy: proxy.url, |
| 278 | + http_proxy: proxy.url, |
| 279 | + all_proxy: "", |
| 280 | + NO_PROXY: "", |
| 281 | + no_proxy: "", |
| 282 | + }, |
| 283 | + async () => { |
| 284 | + const accepted = await createAudioContext("accepted.wav", 2048); |
| 285 | + const acceptedResult = await applyMediaUnderstanding({ |
| 286 | + ctx: accepted.ctx, |
| 287 | + cfg: createConfig(`${provider.url}/v1`, 4096), |
| 288 | + workspaceDir: accepted.workspaceDir, |
| 289 | + providers: { openai: openaiMediaUnderstandingProvider }, |
| 290 | + }); |
| 291 | + |
| 292 | + const acceptedEvidence = JSON.stringify({ |
| 293 | + decisions: acceptedResult.decisions, |
| 294 | + providerRequests: providerRequests.map((request) => ({ |
| 295 | + method: request.method, |
| 296 | + remotePort: request.remotePort, |
| 297 | + url: request.url, |
| 298 | + })), |
| 299 | + proxyRequests: proxyRequests.map((request) => ({ |
| 300 | + method: request.method, |
| 301 | + url: request.url, |
| 302 | + })), |
| 303 | + }); |
| 304 | + expect(acceptedResult.appliedAudio, acceptedEvidence).toBe(true); |
| 305 | + expect(accepted.ctx.Transcript).toBe("proxied audio transcript"); |
| 306 | + expect(proxyRequests).toHaveLength(1); |
| 307 | + expect(providerRequests).toHaveLength(1); |
| 308 | + expect(proxyRequests[0]?.method).toBe("CONNECT"); |
| 309 | + expect(proxyRequests[0]?.url).toBe(new URL(provider.url).host); |
| 310 | + expect(providerRequests[0]?.method).toBe("POST"); |
| 311 | + expect(providerRequests[0]?.url).toBe("/v1/audio/transcriptions"); |
| 312 | + expect(providerRequests[0]?.headers["content-type"]).toContain("multipart/form-data"); |
| 313 | + expect(providerRequests[0]?.body.toString("utf8")).toContain("gpt-4o-transcribe"); |
| 314 | + expect(proxyUpstreamPorts.has(providerRequests[0]?.remotePort ?? -1)).toBe(true); |
| 315 | + |
| 316 | + proxyRequests.length = 0; |
| 317 | + providerRequests.length = 0; |
| 318 | + proxyUpstreamPorts.clear(); |
| 319 | + |
| 320 | + const oversized = await createAudioContext("oversized.wav", 4097); |
| 321 | + const oversizedResult = await applyMediaUnderstanding({ |
| 322 | + ctx: oversized.ctx, |
| 323 | + cfg: createConfig(`${provider.url}/v1`, 4096), |
| 324 | + workspaceDir: oversized.workspaceDir, |
| 325 | + providers: { openai: openaiMediaUnderstandingProvider }, |
| 326 | + }); |
| 327 | + |
| 328 | + expect(oversizedResult.appliedAudio).toBe(false); |
| 329 | + expect(JSON.stringify(oversizedResult.decisions)).toContain("exceeds maxBytes 4096"); |
| 330 | + expect(proxyRequests).toHaveLength(0); |
| 331 | + expect(providerRequests).toHaveLength(0); |
| 332 | + }, |
| 333 | + ); |
| 334 | + } finally { |
| 335 | + await closeServer(proxy); |
| 336 | + await closeServer(provider); |
| 337 | + } |
| 338 | + }); |
| 339 | +}); |
0 commit comments