Skip to content

Studio: fetch a remote image URL instead of forwarding it to llama-server - #11160

Merged
mahiatlinux merged 11 commits into
unslothai:mainfrom
oobabooga:worktree-image-url-ssrf
Sep 18, 2026
Merged

mahiatlinux merged 11 commits into
unslothai:mainfrom
oobabooga:worktree-image-url-ssrf

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Summary

Fixes #11010, an SSRF vulnerability in remote image handling for local GGUF models.

Previously, Studio passed a remote image URL directly to llama-server. llama-server then downloaded the image from the Studio machine without checking whether the address was public. An authenticated caller could use this to reach services on loopback, the local network, or a cloud metadata address.

Before: client URL -> Studio -> llama-server fetches the URL
After:  client URL -> Studio validates and fetches it -> llama-server receives image bytes

What changed

Image generation requests

Studio now downloads remote images itself before sending a request to llama-server. The fetcher:

  • Accepts HTTPS URLs only.
  • Rejects loopback, private, link-local, and other non-public addresses.
  • Connects to the validated IP while still checking the TLS certificate against the hostname.
  • Repeats those checks after every redirect.
  • Limits downloads to 10 MB per image, 32 MB per request, and 8 remote images per request.

The downloaded image is converted to a PNG data URL. llama-server receives the image bytes and has no remote URL left to fetch.

This common path covers:

  • /v1/chat/completions, including tool passthrough
  • /v1/messages
  • /v1/responses

Token counting

/v1/messages/count_tokens also sent image URLs to llama-server. Its /apply-template handler downloaded each image even though token counting only needs a fixed image marker.

Studio now replaces remote images with a 1x1 placeholder before counting. This keeps the token count the same while preventing any network request. /v1/chat/count_tokens already refuses images and is unchanged.

User-visible behavior

Input Result
Public HTTPS image URL Fetched by Studio and sent to llama-server as bytes
HTTP image URL Refused with a 400 response
Private or loopback HTTPS URL Refused without contacting the address
file:, FTP, or another URL scheme Refused with a 400 response
Base64 data URL Continues to work
Bare base64 image Continues to work
One failed URL in a multi-image request The whole request is refused

Non-GGUF remote-image behavior and remote-video behavior are unchanged. Token counting does not verify that a public HTTPS image exists because it intentionally performs no fetch.

Verification

Live checks compared main and this branch using the same vision GGUF and loopback canary servers:

  • On main, a loopback image URL returned 200 and the canary received a GET from llama-server. This branch returned 400 and made no connection.
  • On main, llama-server attempted to contact the cloud metadata address. This branch refused it before dispatch.
  • Loopback HTTPS URLs were refused by both literal IP and hostname without contacting the canary.
  • A public HTTPS image completed successfully, and llama-server received image bytes without logging a download.
  • Anthropic token counting no longer contacts the image URL. HTTP is refused, while public HTTPS is counted through the placeholder.
  • Existing PNG data URLs still work.

The 20 new route-level test cases cover OpenAI, Anthropic, Responses, tool passthrough, token counting, private-address and scheme refusal, fetch failures, base64 compatibility, and both request limits. All directly affected tests pass, and Ruff is clean.

The broader selected backend suite completed with 11,002 passing tests and the same three failures and ten setup errors seen on main, with no new failures.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-17T00:05:48.806078Z a546d14 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2261ea1f18

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +24006 to +24008
if _messages_have_remote_image(payload.messages):
try:
await asyncio.to_thread(_inline_request_remote_images, payload)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fetch remote images before switching the loaded model

When automatic model switching is enabled and this passthrough request names a different GGUF, the fetch occurs only after _maybe_auto_switch_model has loaded the target. A private, unreachable, or slow image URL can therefore evict the working model and then fail with 400 without ever generating; repeated invalid requests can continually churn model loads. Remote-image fetching should be part of the pre-switch image preflight, like the existing base64 validation, with the fetched result reused after switching.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ordering matches main. On main a GGUF request with a remote image URL passed the pre-switch preflight, the switch loaded the target, and llama-server then fetched the URL, so an unreachable or slow host already evicted the resident model before failing. The pre-switch image preflight validates bytes the request already carries; it has never done network I/O. Moving the fetch there would put up to 60 seconds of fetching ahead of a model switch that can still reject the request for other reasons, and would need the fetched result threaded back through three different request shapes (chat, streaming Responses, Anthropic). Load churn is also not specific to images: any request naming a different model triggers a switch whether or not it later succeeds. The PR keeps the post-switch fetch and changes only who performs it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked against merge base f6cf06d: model switching already precedes remote-image dispatch and its possible network failure. This ordering is unchanged; moving network I/O into model preflight is separate from this SSRF fix.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the GGUF path in studio/backend/routes/inference.py still forwards a remote image_url straight to llama-server, so the host does the fetch, and this branch pins and fetches it in Studio instead. Will get this reviewed.

@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a546d14c21

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +31835 to +31836
# Convert the encoded length back to the request budget's byte unit.
return f"data:{mime};base64,{b64}", (len(b64) * 3) // 4

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Enforce image budgets after PNG re-encoding

When a fetched JPEG or WebP is under the 10 MB download cap but expands substantially during decoding or PNG conversion, spent accounts only for the original compressed bytes. The subsequent _image_bytes_to_png_b64 call can therefore allocate and forward a PNG far beyond both the 10 MB per-image and 32 MB per-request limits—for example, a noisy 4096×4096 JPEG can fit under the fetch cap but become a roughly 48 MB PNG. A few such URLs can exhaust backend memory or produce an oversized llama-server request, so the final PNG size (and ideally decoded dimensions) must be checked against the remaining budget.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The limits here are download limits, and they are applied where Studio controls the bytes: 10 MB per fetched body, 32 MB and 8 URLs per request. PNG expansion afterwards is the existing contract for every image on this path. A base64 data URL on main goes through the same _image_bytes_to_png_b64 conversion, with no size or count limit at all, so the memory a request can cause through fetched URLs stays below what it can already cause by sending the bytes inline. Capping the re-encoded PNG against those budgets would refuse ordinary photos: a 4000x3000 photo-like JPEG of 4.0 MB re-encodes to a 23.9 MB PNG, which a 10 MB post-encode cap rejects, while main forwarded the same URL and llama-server decoded it. Pillow's MAX_IMAGE_PIXELS decompression-bomb guard still applies on decode.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced the expansion with a deterministic 2048×2048 JPEG: 2,799,419 input bytes become 12,581,871 PNG bytes, with identical output hashes on base f6cf06d and head ed65282. The PR documents download budgets, and the existing inline-image decoder already permits this input. A post-encoding cap would change that existing image contract rather than repair a regression here.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed independently against merge base f6cf06d: a 1.98 MB photographic JPEG re-encodes to 7.01 MB of PNG, so the expansion is real, but it is the pre-existing contract for every image on this path rather than something this PR introduces. A base64 data URL reaches the same converter on main with no size or count limit at all, so the fetched-URL path is the bounded case, not the new worst case. Capping post-encode would refuse ordinary photos that work today. Rejecting the suggested change and keeping the download budgets as they are.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: a546d14c21

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux
mahiatlinux self-requested a review September 17, 2026 00:06
@mahiatlinux

mahiatlinux commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Verified source head 485fa2b2a613391e99225925ea94b24d4eefc1e6 against merge base f6cf06dece62234d2a79cc4b4852dd6ed3c309c2, plus mirror merge 3ed4695ffb19386879a5d67fd7f1c95e9accedae with current upstream. No additional source changes were needed. The head includes the maintainer's URL-padding and User-Agent fixes.

Check Base Current head and mirror merge
Loopback/metadata URLs across chat, tools, Anthropic and Responses Remote URL dispatched 400; no dispatch
Anthropic token counting with HTTPS image Remote URL forwarded Inline placeholder, no fetch
Public HTTPS image Remote URL forwarded Live fetch succeeds; PNG bytes dispatched
Existing inline PNG 200 200
Affected test files 2,085 passed in original run 2,128 on head; 2,139 on mirror merge

All 25 independent route safety assertions pass on both current revisions. The probe uses real FastAPI handlers, a model backend double, and a real local HTTP capture server for tool passthrough. Public image downloads use the real pinned fetcher; all four generation routes dispatch the same 30,343-byte PNG.

Repeated the real socket drip test: a 0.2-second deadline takes 0.952 seconds on base and 0.200 seconds on current head. Ruff 0.6.9 and git diff --check pass on all eight changed Python files. Tests ran on Linux x86_64, Python 3.13.14, in credential-free Bubblewrap isolation with separate uv environments and the original pinned package resolution.

Earlier native Linux, macOS and Windows checks passed on ed65282cb; these precede the maintainer's two fixes. Reproducers, versions and exact-head logs are preserved.

Fresh scoped staging CI resolves the historical CI evidence gap:

Job group Base Head
Backend a-k plus serial tests 16,071 passed, 1 failed, 43 skipped 16,072 passed, 1 failed, 43 skipped
Repository Python plus CLI 6,544 passed, 128 skipped 6,544 passed, 128 skipped
Extra browser UI FLUX.2 picker timeout in download-only cancel/retry All selected steps passed

The one backend failure is identical on both revisions: test_base_model_dir_name_fallback.py::test_the_transcribed_repo_id_rule_is_never_looser_than_the_hubs reports assert ['Café-8B'] == []. All serial backend tests pass. Backend package resolutions match exactly; repository Python packages differ only in the editable Unsloth commit. The recorded browser test-driver packages also match.

Head passed the exact browser scenario that timed out on base, plus the remaining model-settings, memory-estimate and IME checks. Screenshots were inspected. The staging run is red because it retains these observed baseline failures; no head-only failure was found. The old logs are unavailable, so their original failure causes remain unknown. Structured results, versions and screenshots are preserved.

Mirror review converged at 3ed4695ffb19386879a5d67fd7f1c95e9accedae. The original source head remains 485fa2b2a613391e99225925ea94b24d4eefc1e6; no later source changes or additional fixes need landing. Verification supports approval.

Approved after final-head verification, then squash-merged as 8b3c658c032e9bbf58abf68edb041f2a96937c1e. The review mirror remains unmerged.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

6 similar comments
@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@danielhanchen danielhanchen self-assigned this Sep 17, 2026
…ai#11160

_image_url_scheme only looked at the first 17 characters, so a URL whose colon
sits past that window read as a bare base64 payload and was forwarded to
llama-server untouched. Leading blanks do it: urlsplit drops them before reading
a scheme, so "\n" * 13 + "http://169.254.169.254/" parsed as http everywhere
except the guard.

Skip those blanks, widen the scan past any real scheme, and only call a value a
payload when it holds no colon and nothing outside the base64 alphabet.
The pinned fetcher sent no User-Agent, and image hosts refuse that: the same
Wikimedia PNG answers 403 with no header and 200 with one. llama-server used to
send its own, so moving the fetch into Studio made those URLs fail with the
generic refusal.

Reuse the _USER_AGENTS list _fetch_url_raw already picks from, chosen once per
fetch, so the web fetch and the image fetch look the same to an origin.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Simulated this against the merge base f6cf06dece62234d2a79cc4b4852dd6ed3c309c2 and pushed two fixes to the branch.

#11160 | issue: REAL | PR as submitted: DEFECTIVE, 2 fixed by me | merge: YES

issue what the user hits today what they get after the PR reproduced on main fixed on branch verdict
#11010 A caller who can reach /v1/chat/completions makes the host fetch any address. Against a real llama-server: status: 200, reply: Red., canary logged GET /secret.png Studio fetches it through a pinned public IP, or refuses. 400 Unsupported image URL scheme ('http:'), canary hits [] yes, real llama-server plus 5 route entry points yes, 0 of 1195 enumerated cells forward a URL REAL

I ran a real llama-server (prebuilt CUDA bundle, SmolVLM-256M plus mmproj) and handed it a loopback image_url. It fetched the image from the host and captioned it. The report was conservative: the merge base also forwards the URL on /v1/messages, /v1/responses and /v1/messages/count_tokens, not only on /v1/chat/completions.

Enumeration over the full input space

13 scheme classes x 17 host forms x 5 padding classes, plus 5 payload shapes. Each cell is the branch the real code takes.

cell class merge base head
forwarded to llama-server verbatim 1177 0
refused 400 before any dial 0 1003
handed to the pinned fetcher 0 170
data URL re-encoded, unchanged path 18 18
passed through as a base64 payload 0 4

1195 cells, 18 identical, 1177 changed, 0 violations. The 18 identical cells are the data-URL shapes, so a user who never sends a remote URL is on a byte-identical path. The 4 payload cells are exactly the 4 base64 shapes, so no URL shape can pass as a payload.

AST diff: 16 functions changed, 9 new, 0 bare excepts added. All 21 predicates of _safe_fetch_image_for_gemini_sync reappear unchanged in the shared fetcher; the 7 new ones each add a bound or turn a crash into a refusal.

Two defects, both fixed here

2f053e8e3 _image_url_scheme read only the first 17 characters. urlsplit drops leading blanks before reading a scheme, so a padded URL parsed as http everywhere except the guard, and was forwarded to llama-server as a bare base64 payload:

                 guard saw    urlsplit saw
blank-padded     ''           'http'
tab-padded       ''           'https'
nul-padded       ''           'http'
long scheme      ''           'averyveryverylongscheme'

Now the blanks are skipped, the window outruns any real scheme, and a value is only called a payload when it holds no colon and nothing outside the base64 alphabet. Still sub-microsecond: 0.198 us on a URL, 0.532 us on a 10 MB payload, so the scan stays bounded.

f28595228 The fetch went out with no User-Agent, and image hosts refuse that. Same Wikimedia PNG over the real network:

no UA    HTTPError: HTTP Error 403: Forbidden
with UA  status=200 bytes=224566

llama-server sent its own, so moving the fetch into Studio broke those URLs. Now reuses the _USER_AGENTS list _fetch_url_raw already picks from.

Test power

The suite run against the merge base: 39 failed, 1 passed. On the branch: 40 passed. Reverting the scheme gate fails exactly the 3 new padding cases; removing the User-Agent fails exactly the 1 new case.

One vacuous pass worth naming: test_the_counted_placeholder_prices_the_same_as_a_real_image is the single test that also passes on the merge base, where the placeholder does not exist. Its backend double returns 100 for every input, so it pins routing rather than pricing, and it is the only test covering the count-tokens placeholder's central claim.

Blast radius

  • _read_capped_body, the widest-reach hunk: 3 production callers, all passing a bare http.client.HTTPResponse, which has read1; every response double in the repo defines only read and takes the fallback. 10 MB body, identical bytes on both arms: 161 read calls at 10.43 ms against 1281 read1 calls at 9.24 ms. Suites 1475 passed on base, 1476 on head.
  • Symbol audit across unsloth, unsloth_zoo and studio: every added symbol has a non-test caller, and the Gemini wrapper keeps its callers.
  • import routes.inference: 1.58 s median on head against 1.65 s on base, n=10 a side, base spread 0.10 s. No import cost.
  • The five red checks here fail identically on the merge base, 6 failed and 108 passed on both arms.

Cross-platform, each with a base arm

leg head base verdict
ubuntu-latest PASS n/a pass
macos-15, Apple Silicon PASS n/a pass
windows-latest 1 failed, 2098 passed 2 failed, 2083 passed no regression

The one Windows head failure, test_pinned_http_handler_walks_through_a_real_opener with WinError 10053, also fails on the merge base. It is byte-identical on both arms and exercises _PinnedHTTPHandler through a direct resp.read(), which this PR does not touch. My first base arm exited 4 with zero tests executed because the generated workflow named a file that only exists on this PR; I treated that as void and re-ran it against the files the merge base ships.

Two behaviour changes worth naming rather than fixing

  • Converting fetched images to PNG inflates photographs. A 1.98 MB JPEG becomes 7.01 MB, 3.5x. The 10 MB per-image cap governs the source bytes, so a 10 MB JPEG can reach llama-server as roughly 35 MB and a full 32 MB request as roughly 110 MB. The merge base had llama-server decode the JPEG natively. This is pre-existing for data URLs, so changing the PNG policy belongs in its own change.
  • Gemini image fetches now inherit a 30 second whole-fetch deadline where the merge base bounded only one socket operation, and their DNS runs through _resolve_with_budget on a polled thread. A slow but legitimate image that used to succeed can now be refused.

What I could not prove

  • The real metadata endpoint was never dialled; 169.254.169.254 is a canary throughout.
  • Token-count parity is sound by construction, since /apply-template substitutes a fixed marker, but I did not measure counts per model against a real tokenizer.
  • windows-11-arm, ubuntu-24.04-arm and macos-26 did not run, and WSL is not a runner.
  • Peak RSS for a max-budget 8 image request grew 85 to 103 MB in process, which is bounded but not the 32 MB the byte budget suggests.

@unslothai unslothai deleted a comment from oobabooga Sep 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@mahiatlinux mahiatlinux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Ready to merge, all manually checked.

@mahiatlinux
mahiatlinux merged commit 8b3c658 into unslothai:main Sep 18, 2026
42 of 55 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…11160)

Validate and fetch remote image URLs in Studio before GGUF dispatch, with pinned public addresses and bounded downloads.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Studio: a remote image_url is forwarded to llama-server, which fetches it from the host

3 participants