Skip to content

fix(security): bound OpenAI server and media fetches (#3970) - #3980

Merged
Qubitium merged 4 commits into
mainfrom
fix/issue-3970
Nov 14, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/issue-3970

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #3970

TL;DR

GPTQModel.serve() now defaults to a loopback listener, refuses an unauthenticated non-loopback bind, validates the Host header, and bounds request bodies/token counts/choices. Audio/video calibration URLs now go through the existing bounded image-fetch worker (timeout, total budget, byte cap, redirect cap, per-hop private/link-local filtering) and PyAV gets protocol_whitelist=file,pipe; local images get the max_pixels check. Net diff: +904/-252 across 9 files.

1. The problem

At audit revision 93d3ae7a:

  • DEFAULT_HOST = "0.0.0.0" (gptqmodel/utils/openai_server.py:35) and serve(host="0.0.0.0", port=80, api_key=None) (gptqmodel/models/base.py:3168) exposed inference with no key; _warn_if_exposed() only warned (openai_server.py:424-446).
  • OpenAiRequest had max_tokens: int = 256, n: int = 1 and no body/message caps (openai_server.py:219-226); no Host-header validation, so DNS rebinding could reach a loopback listener and /shutdown.
  • process_audio_info() passed http(s) URLs straight to audioread.ffdec.FFmpegAudioFile (gptqmodel/utils/audio.py:86-110) and called av.open(path) for any video string before the scheme check (audio.py:35), with no timeout/byte/redirect/protocol bounds.
  • requests.get followed redirects with no destination filtering (gptqmodel/utils/image.py:147), and local/file:// images skipped the max_pixels check (image.py:468-476).

Old listener and media flow:

flowchart TD
    A["serve(host=0.0.0.0, api_key=None)"] --> B["_warn_if_exposed"]
    B --> C["uvicorn starts on 0.0.0.0:80"]
    C --> D["any peer can call /v1 or /shutdown"]
    E["audio/video URL from dataset"] --> F["audioread FFmpegAudioFile or av.open(url)"]
    F --> G["ffmpeg/PyAV fetch with default protocols"]
    G --> H["no timeout, byte cap or redirect limit"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class D,H failure;
Loading

2. The new flow

flowchart TD
    A["GPTQModel.serve(host, port, api_key, allowed_hosts)"] --> B["OpenAiServer"]
    B --> C["_validate_bind(host, api_keys)"]
    C -- "non-loopback without key" --> X["ValueError before uvicorn starts"]
    C -- "loopback or key present" --> D["_install_host_validation(host)"]
    D --> E["TrustedHostMiddleware allowed_hosts"]
    E --> F["uvicorn.Config + Server"]
    B --> G["BodySizeLimitMiddleware"]
    G -- "body over MAX_REQUEST_BODY_BYTES" --> Y["HTTP 413"]
    G -- "within limit" --> H["OpenAiRequest validation"]
    H -- "max_tokens or n out of range" --> Z["HTTP 422"]
    H -- "valid" --> I["generate under _generation_lock"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class X,Y,Z failure;
Loading
flowchart TD
    A["process_audio_info(audio/video URL)"] --> B["load_bytes_from_url"]
    B --> C["_download_image_bytes: subprocess worker"]
    C --> D["_validate_remote_url for every hop"]
    D -- "link-local or private without opt-in" --> X["ImageFetchError; no connection"]
    D -- "allowed" --> E["requests.get with allow_redirects=False"]
    E -- "redirect" --> F{"redirects < max_redirects?"}
    F -- "no" --> Y["ImageFetchError: redirect limit"]
    F -- "yes" --> D
    E -- "200" --> G["bounded body read"]
    G --> H["_materialized_media writes a temporary local file"]
    H --> I["av.open with protocol_whitelist=file,pipe"]
    H --> J["librosa.load on the local path"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class X,Y failure;
Loading

_address_is_blocked() always rejects link-local (cloud metadata) addresses; loopback/private destinations require the explicit allow_private_addresses=True argument. Redirects are followed manually so each hop is validated, bounded by DEFAULT_IMAGE_FETCH_MAX_REDIRECTS. fetch_image() applies max_pixels to local paths, file:// URLs and base64 data.

3. Before / after

Surface Before After
Default bind DEFAULT_HOST = "0.0.0.0" (openai_server.py:35) "127.0.0.1"; serve() default matches (base.py:3168)
Exposed bind without key warning only (openai_server.py:424-446) _validate_bind() raises ValueError before uvicorn
Host header none TrustedHostMiddleware; loopback binds accept only loopback names
Request bounds max_tokens=256, n=1, no body cap (openai_server.py:219-226) pydantic bounds + BodySizeLimitMiddleware (1 MiB)
Audio/video URL FFmpegAudioFile(path) (audio.py:86-110) load_bytes_from_url then a temporary local file
Video probe av.open(video_path) before scheme check (audio.py:35) local file, protocol_whitelist=file,pipe
Image redirects requests default follow (image.py:147) manual allow_redirects=False, per-hop validation, cap
Image SSRF no filtering link-local always blocked; loopback/private need opt-in
Local images no pixel check (image.py:468-476) _open_local_image enforces max_pixels

4. Before/after repro

Listener (/tmp/repro_3970_server.py, stub model + FastAPI TestClient):

Before (93d3ae7a):

DEFAULT_HOST: 0.0.0.0
serve host default: 0.0.0.0
has _validate_bind: False
has BodySizeLimitMiddleware: False
has _validate_remote_url(image): False
middleware: []
max_tokens=1000000000 -> 200
n=1000 -> 200
2MB body -> 200
bind 0.0.0.0 without key -> warning only: True

After:

DEFAULT_HOST: 127.0.0.1
serve host default: 127.0.0.1
has _validate_bind: True
has BodySizeLimitMiddleware: True
has _validate_remote_url(image): True
middleware: ['BodySizeLimitMiddleware']
max_tokens=1000000000 -> 422
n=1000 -> 422
2MB body -> 413
bind 0.0.0.0 without key -> ValueError: Refusing to bind the GPT-QModel OpenAI server to non-loopback host '0.

Media (/tmp/repro_3970_audio.py, fakes record what ffmpeg/librosa/PyAV receive):

Before:

('audioread.FFmpegAudioFile', 'https://example.com/a.wav')
('librosa.load', 'FakeFFmpegAudioFile', None, {...})
('av.open', 'https://example.com/v.mp4', {})
('audioread.FFmpegAudioFile', 'https://example.com/v.mp4')

After:

('bounded_fetch', 'https://example.com/a.wav', {'max_bytes': 134217728, 'allow_private_addresses': False})
('librosa.load', 'str', '/tmp/gptqmodel-media-f10rtqa_', {...})
('bounded_fetch', 'https://example.com/v.mp4', {'max_bytes': 134217728, 'allow_private_addresses': False})
('av.open', '/tmp/gptqmodel-media-h7idwb2u', {'options': {'protocol_whitelist': 'file,pipe'}})
('librosa.load', 'str', '/tmp/gptqmodel-media-h7idwb2u', {...})

Image redirect/SSRF (/tmp/repro_3970_image.py):

Before: has _validate_remote_url: False, worker uses allow_redirects=False: False, loopback redirect returns (4, 4).
After: has _validate_remote_url: True, worker uses allow_redirects=False: True, default loopback redirect is rejected (ImageFetchError: destination address 127.0.0.1 ...), and allow_private_addresses=True still returns (4, 4).

5. Tests

New/updated tests:

  • tests/test_openai_server_contract.py: loopback default, refused unauthenticated public bind, TrustedHost rejection of Host: evil.example, max_tokens/n 422 caps, 413 body cap.
  • tests/test_image_fetch.py: private/link-local rejection, link-local redirect rejection, redirect cap, local/file:// pixel limit; existing bounded-fetch tests updated for allow_redirects=False and the explicit private opt-in.
  • tests/test_media_fetch.py (new): remote audio uses the bounded worker and a temp path, remote video passes protocol_whitelist=file,pipe and never opens the URL, local media size cap.

Exact commands and results (FastAPI/httpx/uvicorn were installed into a throwaway --target /tmp/oai_deps; the venvs were not modified):

CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e PYTHONPATH=$PWD:/tmp/oai_deps \
  /opt/venvs/cu130t/bin/python -m pytest tests/test_openai_server_contract.py tests/test_image_fetch.py tests/test_media_fetch.py -q
-> 86 passed

HIP_VISIBLE_DEVICES=1 PYTHONPATH=$PWD:/tmp/oai_deps \
  /opt/venvs/rocm101t/bin/python -m pytest tests/test_openai_server_contract.py tests/test_image_fetch.py tests/test_media_fetch.py -q
-> 86 passed

CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e PYTHONPATH=$PWD:/tmp/oai_deps \
  /opt/venvs/cu130t/bin/python -m pytest tests/test_unlimited_ocr_support.py tests/test_qwen2_audio_support.py -q
-> 21 passed

Hardware: NVIDIA RTX 4090 (CUDA UUID GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e, torch 2.16.0.dev+cu130) and AMD Radeon R9700 (HIP_VISIBLE_DEVICES=1, torch 2.16.0.dev+rocm10.1).

6. Docs

Reference page: docs/openai-server-exposure.md, linked from the README OpenAI section. It carries the same diagrams, the before/after table, and the failure contract.

7. Limitations

  • av, librosa, and audioread are not installed in either test venv. The media tests use fakes to pin the control flow (bounded worker first, temp local path, protocol_whitelist); a real ffmpeg/PyAV decode was not executed here.
  • Local audio/video files are size-capped but not wall-clock-bounded; they do not perform network I/O.
  • allow_private_addresses is an explicit API argument (no environment switch). It permits loopback/private hosts but never link-local metadata addresses.
  • A non-loopback bind with api_key keeps Host validation permissive (["*"]) unless allowed_hosts= is supplied, so an existing authenticated public deployment keeps working.

Comment thread gptqmodel/utils/openai_server.py Resolved
Comment thread gptqmodel/utils/audio.py Resolved
Comment thread gptqmodel/utils/openai_server.py Resolved
Qubitium and others added 3 commits November 14, 2026 19:57
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
…mplicit (fall through) returns'

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Security] serve() defaults to an unauthenticated 0.0.0.0 listener; audio/video calibration fetches are unbounded

1 participant