From 78d83bd778fc44e677579bbf5ccba0fa3c47c914 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 26 Nov 2026 15:25:31 +0900 Subject: [PATCH] Fix security finding acf_41b8bd87c174d7eb709918e0f9557342 --- src/server/index/serve-options.ts | 8 +++---- src/server/videos.ts | 35 +++++++++++++++++++++--------- structure/data-planes/images.md | 9 +++++--- tests/server/server-videos.test.ts | 35 +++++++++++++++++++++++++++--- 4 files changed, 67 insertions(+), 20 deletions(-) diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index 3532f54a13b..5c6d9fa586a 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -1326,7 +1326,7 @@ export function createServeOptions(ctx: ServeOptionsContext) { }, { requestId, start, logCtx }); } - // Public OpenAI Videos routes (#9110): images-endpoint admission; only the paid create takes a turn slot. + // Public OpenAI Videos routes (#9110): images-endpoint admission; every upstream call takes a turn slot. const videoRoute = url.pathname.startsWith("/v1/videos") ? matchVideoRoute(req.method, url.pathname) : undefined; if (videoRoute) { // A create keeps the listener timeout until its body is read, so a stalled upload cannot hold its slots. @@ -1344,14 +1344,14 @@ export function createServeOptions(ctx: ServeOptionsContext) { ...requestMetricsLogContext, client: classifyUsageClient(req.headers), ...admissionFields(admission), }; - const run = async (lease?: import("../../lib/admission").AdmissionLease): Promise => { + const run = async (lease: import("../../lib/admission").AdmissionLease): Promise => { const response = await handleVideos(req, url, config, videoRoute, logCtx, admission, { - ...(lease ? { lease } : {}), onRequestBodyRead: () => disableResponsesRequestTimeout(req, requestServer), + lease, onRequestBodyRead: () => disableResponsesRequestTimeout(req, requestServer), }); addFinalRequestLog(requestId, start, logCtx, response.status, response.status === 499 ? { closeReason: "client_cancel" } : undefined); return withCors(response, req, policy); }; - return videoRoute.kind === "create" ? runAdmittedHttpTurn(req, policy, lease => run(lease), { requestId, start, logCtx }) : run(); + return runAdmittedHttpTurn(req, policy, lease => run(lease), { requestId, start, logCtx }); } if (req.method === "GET" && url.pathname.startsWith("/v1/opencodex/artifacts/")) { diff --git a/src/server/videos.ts b/src/server/videos.ts index 390d7be8ba5..c4976caf433 100644 --- a/src/server/videos.ts +++ b/src/server/videos.ts @@ -28,7 +28,7 @@ import type { DataPlaneAdmission } from "./auth-cors"; import type { RequestLogContext } from "./request-log"; import { readBoundedJsonRequestBody, readBoundedRequestBodyBytes, resolveInboundBodyLimitBytes } from "./request-decompress"; import { decodeRequestErrorResponse } from "./responses"; -import { registerTurn, unregisterTurn } from "./lifecycle"; +import { registerTurn, trackStreamLifetime, unregisterTurn } from "./lifecycle"; import type { AdmissionLease } from "../lib/admission"; import { ensureVideoHandleKey, isVideoHandleKeyError, openVideoHandle, sealVideoHandle, videoHandleClaimsError, videoHandlePrincipal } from "./video-handle"; import { safeXaiErrorDetail } from "../images/xai-upstream-error"; @@ -146,7 +146,7 @@ export function setVideoCreateBodyTimeoutForTests(ms: number | undefined): void } export interface VideoRouteOptions { - /** The create's turn lease: shutdown aborts the upstream create through it. */ + /** The route's turn lease: shutdown aborts upstream work and content retains it while streaming. */ lease?: AdmissionLease; /** Called once the create body is read, when the listener timeout may be lifted. */ onRequestBodyRead?: () => void; @@ -273,14 +273,19 @@ async function openHandle( return { claims, auth: row.auth }; } -async function handleRetrieve(req: Request, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission): Promise { +async function handleRetrieve(req: Request, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission, options: VideoRouteOptions): Promise { const opened = await openHandle(req, config, handle, logCtx, admission); if (opened instanceof Response) return opened; + const operation = new AbortController(); + if (options.lease) registerTurn(operation, options.lease); try { - const job = await retrieveOpenAiVideo(opened.claims.upstreamId, opened.auth, req.signal, outboundDependencies); + const job = await retrieveOpenAiVideo(opened.claims.upstreamId, opened.auth, AbortSignal.any([req.signal, operation.signal]), outboundDependencies); return Response.json(publicVideoJob(job, handle, opened.claims.model)); } catch (error) { + if (operation.signal.aborted && !req.signal.aborted) return formatErrorResponse(503, "server_draining", "video retrieve stopped during shutdown"); return failureResponse(error, req, "video retrieve"); + } finally { + if (options.lease) unregisterTurn(operation); } } @@ -298,22 +303,27 @@ function cappedBody(body: ReadableStream, maxBytes: number): Readabl })); } -async function handleContent(req: Request, url: URL, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission): Promise { +async function handleContent(req: Request, url: URL, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission, options: VideoRouteOptions): Promise { const variant = url.searchParams.get("variant") ?? undefined; if (variant !== undefined && !OPENAI_VIDEO_CONTENT_VARIANTS.has(variant)) return invalid("variant must be video, thumbnail or spritesheet"); const opened = await openHandle(req, config, handle, logCtx, admission); if (opened instanceof Response) return opened; + const operation = new AbortController(); + if (options.lease) registerTurn(operation, options.lease); + const finishOperation = () => { if (options.lease) unregisterTurn(operation); }; let upstream: Response; try { upstream = await fetchOpenAiVideoContent(opened.claims.upstreamId, opened.auth, { - signal: req.signal, ...(variant !== undefined ? { variant } : {}), + signal: AbortSignal.any([req.signal, operation.signal]), ...(variant !== undefined ? { variant } : {}), }, outboundDependencies); } catch (error) { + finishOperation(); + if (operation.signal.aborted && !req.signal.aborted) return formatErrorResponse(503, "server_draining", "video content stopped during shutdown"); return failureResponse(error, req, "video content"); } const declared = upstream.headers.get("content-length"); if (declared !== null && /^\d+$/.test(declared) && Number(declared) > VIDEO_CONTENT_MAX_BYTES) { - try { await upstream.body?.cancel(); } catch { /* ignore */ } + try { await upstream.body?.cancel(); } catch { /* ignore */ } finally { finishOperation(); } return formatErrorResponse(502, "upstream_error", "video content exceeds size cap"); } const type = (upstream.headers.get("content-type") ?? "").toLowerCase().split(";")[0]!.trim(); @@ -323,7 +333,12 @@ async function handleContent(req: Request, url: URL, config: OcxConfig, handle: "x-content-type-options": "nosniff", }; if (declared !== null && /^\d+$/.test(declared)) headers["content-length"] = declared; - return new Response(upstream.body ? cappedBody(upstream.body, VIDEO_CONTENT_MAX_BYTES) : null, { status: 200, headers }); + if (!upstream.body) { + finishOperation(); + return new Response(null, { status: 200, headers }); + } + const body = cappedBody(upstream.body, VIDEO_CONTENT_MAX_BYTES); + return new Response(options.lease ? trackStreamLifetime(body, operation, undefined, options.lease) : body, { status: 200, headers }); } export async function handleVideos( @@ -337,8 +352,8 @@ export async function handleVideos( ): Promise { try { if (route.kind === "create") return await handleCreate(req, config, logCtx, admission, options); - if (route.kind === "retrieve") return await handleRetrieve(req, config, route.handle, logCtx, admission); - return await handleContent(req, url, config, route.handle, logCtx, admission); + if (route.kind === "retrieve") return await handleRetrieve(req, config, route.handle, logCtx, admission, options); + return await handleContent(req, url, config, route.handle, logCtx, admission, options); } catch (error) { // The handle key file is the one local failure left; it names no secret. if (isVideoHandleKeyError(error)) { diff --git a/structure/data-planes/images.md b/structure/data-planes/images.md index 55434367917..45073397679 100644 --- a/structure/data-planes/images.md +++ b/structure/data-planes/images.md @@ -127,9 +127,12 @@ collapse onto another path of the same host. Bridge arguments map to `seconds`, `src/server/videos.ts` serves `POST /v1/videos`, `GET /v1/videos/{id}` and `GET /v1/videos/{id}/content` (`src/lib/video-routes.ts` matches them; other methods and subpaths reach the JSON `/v1/*` 404). The dispatcher applies the Images admission: draining refusal, `resolveApiAuth`, origin policy and a -request-log row (`usage.jsonl`); only the paid create takes an admitted turn slot and the inbound body gate -(`/v1/videos` is in `CONFIGURABLE_JSON_BODY_ROUTES`). Its upstream POST is bound to that turn lease, so shutdown aborts -it with a 503, and it keeps the listener request timeout until its body is read. The body read also has a 60 s +request-log row (`usage.jsonl`). Every create, retrieve and content request takes an admitted turn slot; the +create additionally takes the inbound body gate (`/v1/videos` is in `CONFIGURABLE_JSON_BODY_ROUTES`). Each +credentialed upstream operation is bound to its turn, so shutdown aborts work before response headers with a +503. A retrieve releases the turn after its bounded upstream JSON is parsed, while content transfers the turn to +the capped response body and releases it only at EOF, stream error or client cancellation. The create keeps the +listener request timeout until its body is read. The body read also has a 60 s whole-body deadline (the idle timeout alone bounds only silence), after which the reader is cancelled and the create answers 408 before any send, so neither a stalled nor a trickling upload can hold either slot. The loopback listener and Remote Link admit the same three shapes. diff --git a/tests/server/server-videos.test.ts b/tests/server/server-videos.test.ts index 1160c3ffba3..51cfb8e9589 100644 --- a/tests/server/server-videos.test.ts +++ b/tests/server/server-videos.test.ts @@ -14,7 +14,8 @@ import type { DataPlaneAdmission } from "../../src/server/auth-cors"; import type { RequestLogContext } from "../../src/server/request-log"; import { setVideoHandleKeyForTests } from "../../src/server/video-handle"; import { matchVideoRoute } from "../../src/lib/video-routes"; -import { handleVideos, setVideoCreateBodyTimeoutForTests, setVideoOutboundDependenciesForTests } from "../../src/server/videos"; +import { handleVideos, setVideoCreateBodyTimeoutForTests, setVideoOutboundDependenciesForTests, type VideoRouteOptions } from "../../src/server/videos"; +import { getActiveTurnCount, tryAdmitTurn } from "../../src/server/lifecycle"; import type { OcxConfig, OcxProviderConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { repoPath } from "../helpers/repo-root"; @@ -95,14 +96,14 @@ function config(overrides: Partial = {}, rows: Record ({ model: "video", provider: "unknown" } as RequestLogContext); -async function call(cfg: OcxConfig, method: string, path: string, body?: BodyInit, admission = ALICE, headers: Record = { "content-type": "application/json" }, secret = secretFor(admission)) { +async function call(cfg: OcxConfig, method: string, path: string, body?: BodyInit, admission = ALICE, headers: Record = { "content-type": "application/json" }, secret = secretFor(admission), options?: VideoRouteOptions) { const url = new URL("http://localhost" + path); headers = { ...headers, authorization: "Bearer " + secret }; const route = matchVideoRoute(method, url.pathname); if (!route) throw new Error("no video route for " + method + " " + path); const logCtx = logContext(); const req = new Request(url, { method, headers, ...(body !== undefined ? { body } : {}) }); - const response = await handleVideos(req, url, cfg, route, logCtx, admission); + const response = await handleVideos(req, url, cfg, route, logCtx, admission, options); return { response, logCtx }; } @@ -235,6 +236,26 @@ describe("GET /v1/videos/{id} and /content", () => { expect(sent).toEqual([{ method: "GET", url: "https://" + HOST + "/v1/videos/video_up_1/content", address: "93.184.216.34", authorization: "Bearer " + KEY }]); }); + test("content retains its admitted turn until the response body is cancelled", async () => { + const handle = await handleFor(); + answer = () => new Response(new ReadableStream({ + start(controller) { controller.enqueue(MP4); }, + }), { headers: { "content-type": "video/mp4" } }); + const baseline = getActiveTurnCount(); + const lease = tryAdmitTurn(); + expect(lease).not.toBeNull(); + try { + const { response } = await call(config(), "GET", "/v1/videos/" + handle + "/content", undefined, ALICE, {}, ALICE_SECRET, { lease: lease! }); + const reader = response.body!.getReader(); + expect((await reader.read()).value).toEqual(MP4); + expect(getActiveTurnCount()).toBe(baseline + 1); + await reader.cancel("client stopped download"); + expect(getActiveTurnCount()).toBe(baseline); + } finally { + lease?.release(); + } + }); + test("content never relays an active media type and passes only known variants", async () => { const handle = await handleFor(); answer = () => new Response("", { headers: { "content-type": "text/html" } }); @@ -418,6 +439,14 @@ test("the loopback listener hands /v1/videos paths to the same matcher and nothi expect(gate.match(/\/v1\/videos/g)?.length).toBe(2); }); +test("the dispatcher admits every matched videos route as an active turn", async () => { + const source = await Bun.file(repoPath("src", "server", "index", "serve-options.ts")).text(); + const start = source.indexOf("const videoRoute ="); + const branch = source.slice(start, source.indexOf("\n if (req.method === \"GET\"", start)); + expect(branch).toContain("return runAdmittedHttpTurn(req, policy, lease => run(lease)"); + expect(branch).not.toContain('videoRoute.kind === "create" ?'); +}); + test("route matching admits only the three documented shapes", () => { expect(matchVideoRoute("POST", "/v1/videos")).toEqual({ kind: "create" }); expect(matchVideoRoute("GET", "/v1/videos/abc")).toEqual({ kind: "retrieve", handle: "abc" });