Repository navigation
[Codex Security] Video content downloads bypass concurrency admission #847
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<Response> { | ||
| async function handleRetrieve(req: Request, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission, options: VideoRouteOptions): Promise<Response> { | ||
| 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<Uint8Array>, maxBytes: number): Readabl | |
| })); | ||
| } | ||
|
|
||
| async function handleContent(req: Request, url: URL, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission): Promise<Response> { | ||
| async function handleContent(req: Request, url: URL, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission, options: VideoRouteOptions): Promise<Response> { | ||
| 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 }); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Failed video downloads hold shared turn slots When the upstream fails during a paused download, the stream wrapper waits for another read before releasing the slot. The listener timeout is disabled, so the failed download keeps occupying shared API capacity until the client resumes or disconnects. Learn moreA turn slot is a reservation in the same active-request gate used by video and inference calls. The video dispatcher disables the listener timeout for downloads and hands the slot to the handler. trackStreamLifetime releases it on a read error, but does not observe the reader’s rejection independently of downstream demand. When the client stops draining its socket and the wrapper has a chunk queued, there is no pending read to observe the error. The upstream deadline signals only the upstream transport, not the controller that would stop the tracked response and release its slot. If enough failed transfers remain in this state, the shared turn gate refuses new work. Example: A client pauses a large download while keeping its connection open. The video provider resets the connection. The proxy keeps counting the failed download as active until that client reads again or disconnects. Recommended fix: Observe the capped reader’s rejection even when no pull is pending, and error the outgoing response and release the lease through the same idempotent cleanup path. Bind the transfer deadline to the tracked response as well so it can settle even if the client never resumes. Add a regression test that lets one chunk queue, fails the upstream, and checks that the active count returns to baseline without a further read or cancellation. Was this helpful? React with 👍 or 👎 to provide feedback. |
||
| } | ||
|
|
||
| export async function handleVideos( | ||
|
|
@@ -337,8 +352,8 @@ export async function handleVideos( | |
| ): Promise<Response> { | ||
| 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)) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
Comment on lines
+130
to
+131
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔍 The public video guide omits overload behavior Update the public Videos guide as required by the repository’s docs-sync rule. Explain that polls and downloads share active-turn capacity and document the 503 response and its Was this helpful? React with 👍 or 👎 to provide feedback. |
||
| 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. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<OcxConfig> = {}, rows: Record<string, OcxProv | |
|
|
||
| const logContext = (): RequestLogContext => ({ model: "video", provider: "unknown" } as RequestLogContext); | ||
|
|
||
| async function call(cfg: OcxConfig, method: string, path: string, body?: BodyInit, admission = ALICE, headers: Record<string, string> = { "content-type": "application/json" }, secret = secretFor(admission)) { | ||
| async function call(cfg: OcxConfig, method: string, path: string, body?: BodyInit, admission = ALICE, headers: Record<string, string> = { "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<Uint8Array>({ | ||
| 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("<script>x</script>", { 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" ?'); | ||
|
Comment on lines
+442
to
+447
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔍 Video admission needs a capacity test at the HTTP boundary The new dispatcher test checks source text, while the server-level video test runs with free slots. Extend it to verify that a full gate returns 503 for both GET routes without sending either request upstream. Was this helpful? React with 👍 or 👎 to provide feedback.
Comment on lines
+446
to
+447
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add a behavioral dispatcher test for video retrieve and content admission. The dispatcher check at Add a case that follows the existing server pattern in
Keep the source-text assertion and the existing stream-cancellation test.
|
||
| }); | ||
|
|
||
| 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" }); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔍 Video reads inherit workflow-budget refusals
HTTP turn admission also checks workflow budgets and pool continuity. Decide whether those policies should return 429 for status checks and downloads of already-created jobs, even when active slots are available.
Was this helpful? React with 👍 or 👎 to provide feedback.