Skip to content

feat(images): imageToBuffer reads untrusted input from public addresses only - #211

Merged
jddunn merged 2 commits into
masterfrom
fix/image-fetch-untrusted
Oct 9, 2026
Merged

jddunn merged 2 commits into
masterfrom
fix/image-fetch-untrusted

Conversation

@jddunn

@jddunn jddunn commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

What this changes

imageToBuffer takes a second argument. With { untrusted: true }, input from a tool call or a user is read without touching the file system or the private network:

const image = await imageToBuffer(toolArgs.imageUrl, { untrusted: true });
const result = await editImage({ image, prompt: 'Make it a watercolor' });
Input Default untrusted: true
Buffer, data URL, raw base64 decoded decoded
file path, file: URL read refused, code: 'IMAGE_LOCAL_FILE_REFUSED'
http(s) URL fetch, redirects followed, any host public addresses only, checked at every connection and every redirect; 50 MiB and 30 s at most (maxBytes, timeoutMs); a refusal has code: 'IMAGE_URL_REFUSED'

Why

Every image API (editImage, upscaleImage, variateImage, transferStyle, segment) reads its string input through imageToBuffer, which fetched any URL. A URL from a model reached http://169.254.169.254/, http://localhost:… and the rest of the private network. The image-editing and vision-pipeline packs check the host string before calling AgentOS, but a string check misses two cases:

  1. A public name that resolves to a private address. http://anything.attacker.example/ with DNS answering 169.254.169.254.
  2. A redirect. A public host answering 302 Location: http://169.254.169.254/latest/meta-data/; fetch follows it.

How

  • src/io/media/images/untrustedImageFetch.ts sends the request with node:http/node:https. Its lookup resolves every address of the host and fails unless each one passes, so the connection goes to an address the check saw. A name that answers differently on a second lookup (DNS rebinding) gets no unchecked connection. An address in the URL is checked before connecting. agent: false keeps any pooled socket from an unchecked lookup from being reused.
  • Redirects are followed by hand, at most five, each target checked the same way. A redirect to another scheme is refused. A redirect or an error response is destroyed rather than drained.
  • The body is read up to maxBytes; a declared Content-Length over the limit is refused before reading. One deadline covers the redirects and the body. Error messages show the URL without its query or credentials.
  • The request asks for accept-encoding: identity. A server may send gzip, deflate or br anyway; that body is decoded, and maxBytes counts the decoded bytes, so a compression bomb stops at the limit. Any other coding is refused.
  • maxBytes and timeoutMs must be positive numbers, and timeoutMs at most 2,147,483,647 ms, Node's longest timer (a longer one fires after 1 ms). Any other value throws a RangeError before connecting.
  • src/io/media/images/networkAddress.ts exports isPublicNetworkAddress. It covers IPv4 private, loopback, link-local, carrier-grade NAT, documentation, benchmarking, multicast and reserved ranges. For IPv6 it covers the same classes, and the IPv4 address carried by IPv4-mapped, IPv4-compatible, NAT64 and 6to4 forms. This is the same check the packs ship, reviewed there.

Also in imageToBuffer:

  • A data URL without ;base64 (data:image/svg+xml,%3Csvg…) was decoded as base64, which gives garbage. It is percent-decoded byte by byte (RFC 2397).
  • A file: URL was read through new URL().pathname, so %20 stayed escaped and the read failed. It goes through fileURLToPath.
  • Schemes match in any case (HTTPS://…).

The default path is unchanged: fetch, any host, files read.

Tests

  • untrustedImageFetch.test.ts runs against a real HTTP server on 127.0.0.1. It stands in for a public host through the allowAddress test seam, and a fake resolver plays a hostile DNS server. Cases:

    • a read, and a redirect followed;
    • a name resolving to 127.0.0.1 refused, with the server getting no request;
    • redirects refused to 10.0.0.1, to a name resolving to 169.254.169.254, and to file:;
    • the five-redirect limit;
    • the size limit, both for a declared length and for a chunked body;
    • a stalled body stopped by the deadline;
    • a gzip body decoded, a compression bomb stopped at the limit, an unknown coding refused;
    • NaN, Infinity, zero and negative limits refused before connecting;
    • a 404 reported without the URL's query.

    Through imageToBuffer, it covers 127.0.0.1 and localhost refused, paths and file: URLs refused, and raw base64 still decoded.

  • networkAddress.test.ts: a table of non-public and public addresses.

  • imageToBuffer.test.ts: percent-encoded and upper-case data URLs; a file: URL with an escaped space.

Not in this change

  • VisionPipeline's local tiers fetch URL strings themselves. VISION_PIPELINE.md now says to read untrusted URLs with imageToBuffer(url, { untrusted: true }) and pass the Buffer.
  • The image-editing and vision-pipeline packs will use the untrusted mode in a follow-up PR in agentos-extensions, once this is released.

…es only

imageToBuffer reads any local path and fetches any http(s) URL with
redirects followed, so a URL from a tool call reached this machine, the
private network and the cloud metadata address. Checking the host string
first does not help: a public name can resolve to a private address, and
a public host can redirect to one.

imageToBuffer(input, { untrusted: true }) refuses file paths and file:
URLs, and fetches an http(s) URL only from public network addresses. The
address in the URL is checked before connecting; a host name's addresses
are all checked inside the connection's own lookup, so the connection
goes to an address the check passed. Up to five redirects are followed
by hand and checked the same way. The fetch stops at maxBytes (50 MiB)
and timeoutMs (30 s). isPublicNetworkAddress is exported on its own.

Also: a data URL without ;base64 is percent-decoded (RFC 2397) instead
of read as base64, a file: URL is read through fileURLToPath so escaped
characters resolve, and URL schemes match in any case.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 9, 2026 18:34
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@sourcery-ai

sourcery-ai Bot commented Oct 9, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 11 hours and 31 minutes by commenting @sourcery-ai review. Upgrade to get a review now.

@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 9 billable files and costs up to $2.25.

  • Ask an admin to make reviews automatic

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Or wait 12 minutes for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: c6a2a336-01a4-4745-be86-3904d45358e2

📥 Commits

Reviewing files that changed from the base of the PR and between bcbe902 and 9f0cce6.


📒 Files selected for processing (9)
  • docs/features/IMAGE_EDITING.md
  • docs/features/VISION_PIPELINE.md
  • src/io/media/images/__tests__/imageToBuffer.test.ts
  • src/io/media/images/__tests__/networkAddress.test.ts
  • src/io/media/images/__tests__/untrustedImageFetch.test.ts
  • src/io/media/images/imageToBuffer.ts
  • src/io/media/images/index.ts
  • src/io/media/images/networkAddress.ts
  • src/io/media/images/untrustedImageFetch.ts


  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 9, 2026

Copy link
Copy Markdown

Reviewer's Guide

Introduces an opt-in untrusted image ingestion mode that blocks local files and SSRF targets, validates DNS results and redirects at connection time, limits fetch size and duration, fixes data/file URL decoding edge cases, and documents the safe Buffer-based usage pattern while leaving default fetching behavior unchanged.

Sequence diagram for untrusted image URL ingestion

sequenceDiagram
    participant Caller
    participant imageToBuffer
    participant fetchUntrustedImage
    participant DNS
    participant PublicCheck as isPublicNetworkAddress
    participant HTTP as HTTP_or_HTTPS_Server

    Caller->>imageToBuffer: imageToBuffer(input, options)
    alt untrusted local file
        imageToBuffer-->>Caller: IMAGE_LOCAL_FILE_REFUSED
    else untrusted HTTP(S) URL
        imageToBuffer->>fetchUntrustedImage: fetchUntrustedImage(url, maxBytes, timeoutMs)
        fetchUntrustedImage->>PublicCheck: Check IP literal
        PublicCheck-->>fetchUntrustedImage: public or refusal
        fetchUntrustedImage->>DNS: Resolve all host addresses
        DNS-->>fetchUntrustedImage: Addresses
        fetchUntrustedImage->>PublicCheck: Check every resolved address
        PublicCheck-->>fetchUntrustedImage: public or refusal
        fetchUntrustedImage->>HTTP: GET with agent:false
        alt redirect
            HTTP-->>fetchUntrustedImage: 3xx Location
            fetchUntrustedImage->>PublicCheck: Check redirect target
            fetchUntrustedImage->>DNS: Resolve redirect host
            fetchUntrustedImage->>HTTP: Follow redirect up to five times
        else successful response
            HTTP-->>fetchUntrustedImage: 2xx response body
            fetchUntrustedImage-->>imageToBuffer: Bounded Buffer
            imageToBuffer-->>Caller: Buffer
        end
    end
Loading

Flow diagram for imageToBuffer input handling

flowchart TD
    A[imageToBuffer input] --> B{Input format}
    B -->|Buffer| C[Return Buffer]
    B -->|Data URL| D{base64 marker}
    D -->|Yes| E[Decode base64]
    D -->|No| F[Percent-decode bytes]
    B -->|file URL or local path| G{untrusted}
    G -->|Yes| H[IMAGE_LOCAL_FILE_REFUSED]
    G -->|No| I[Read from filesystem]
    B -->|"HTTP(S) URL"| J{untrusted}
    J -->|Yes| K[Public-address fetch with limits]
    J -->|No| L[Default fetch any host]
    B -->|Raw base64| M[Decode recognized image data]
    C --> N[Image Buffer]
    E --> N
    F --> N
    I --> N
    K --> N
    L --> N
    M --> N
Loading

File-Level Changes

Change Details Files
Add an SSRF-resistant fetch path for untrusted image URLs.
  • Resolve every hostname address and permit only public ranges at connection time.
  • Manually follow up to five HTTP(S) redirects, validating each target and refusing scheme changes.
  • Enforce response-size and end-to-end timeout limits, destroy refused/error responses, and redact query strings and credentials in errors.
src/io/media/images/untrustedImageFetch.ts
src/io/media/images/networkAddress.ts
src/io/media/images/__tests__/untrustedImageFetch.test.ts
src/io/media/images/__tests__/networkAddress.test.ts
Extend imageToBuffer with explicit untrusted-input handling while preserving default behavior.
  • Add untrusted, maxBytes, and timeoutMs options with local-file and private-network refusal error codes.
  • Keep Buffers and recognized raw image base64 usable without filesystem access.
  • Correct case-insensitive scheme handling, RFC 2397 non-base64 data URLs, and escaped file URL conversion.
src/io/media/images/imageToBuffer.ts
src/io/media/images/__tests__/imageToBuffer.test.ts
src/io/media/images/index.ts
Document the safe ingestion pattern for model- and user-supplied images.
  • Show reading untrusted URLs with imageToBuffer(..., { untrusted: true }) and passing the resulting Buffer to image APIs.
  • Describe local-file refusal, public-address checks, redirect validation, and default resource limits.
  • Warn that VisionPipeline local tiers still fetch URL strings directly and require caller-side buffering.
docs/features/IMAGE_EDITING.md
docs/features/VISION_PIPELINE.md

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Add public-address-only fetching for untrusted image inputs

✨ Enhancement 🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Add opt-in image loading that refuses local files and private-network URLs, including DNS and
 redirect targets.
• Cap untrusted fetch size and duration while preserving existing default behavior.
• Fix data URL and file URL decoding; document usage and test security boundaries.
Diagram

graph TD
  Caller["Untrusted caller"] --> Parser["imageToBuffer"] --> Kind{"Input type"}
  Kind -->|"local file"| Refuse["Refuse input"]
  Kind -->|"HTTP URL"| Fetch["Checked fetch"] --> Policy{"Public address"} -->|"allowed"| Bytes["Image buffer"]
  Policy -->|"refused"| Refuse
  Policy -->|"redirect target"| Policy
  Kind -->|"data or base64"| Bytes
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Restrict all image URL reads by default
  • ➕ Protects existing callers without requiring adoption.
  • ➖ Changes established behavior for applications intentionally reading local files or internal URLs.

Recommendation: Keep the opt-in mode for backward compatibility, but treat adoption at every untrusted-input boundary as essential: existing image APIs and VisionPipeline URL strings do not automatically gain this protection.

Files changed (9) +734 / -18

Enhancement (4) +452 / -17
imageToBuffer.tsAdd opt-in untrusted input handling +117/-17

Add opt-in untrusted input handling

• Routes untrusted HTTP(S) URLs to checked fetching and refuses file paths and file URLs without reading them. Also fixes non-base64 data URL decoding, escaped file URL paths, and case-insensitive scheme recognition while retaining default fetch behavior.

src/io/media/images/imageToBuffer.ts

index.tsExport the public-address predicate +1/-0

Export the public-address predicate

• Re-exports networkAddress so callers can use isPublicNetworkAddress through the images module.

src/io/media/images/index.ts

networkAddress.tsClassify public IPv4 and IPv6 addresses +118/-0

Classify public IPv4 and IPv6 addresses

• Adds a fail-closed predicate for private, local, reserved, and embedded-IPv4 address forms used by untrusted fetching.

src/io/media/images/networkAddress.ts

untrustedImageFetch.tsFetch images with connection-time address checks +216/-0

Fetch images with connection-time address checks

• Checks IP literals and every DNS result for each new connection, rechecks redirects, and refuses other schemes. Limits redirects, response size, and total elapsed time while omitting URL credentials and queries from fetch errors.

src/io/media/images/untrustedImageFetch.ts

Tests (3) +267 / -0
imageToBuffer.test.tsCover data URL decoding and escaped file paths +19/-0

Cover data URL decoding and escaped file paths

• Tests percent-encoded data URL bytes, case-insensitive data URL handling, and reading a file URL containing an escaped space.

src/io/media/images/tests/imageToBuffer.test.ts

networkAddress.test.tsTest public and non-public IP classifications +66/-0

Test public and non-public IP classifications

• Adds IPv4, IPv6, embedded-IPv4, malformed-address, and public-address cases for the exported address predicate.

src/io/media/images/tests/networkAddress.test.ts

untrustedImageFetch.test.tsExercise untrusted fetching against a local HTTP server +182/-0

Exercise untrusted fetching against a local HTTP server

• Tests DNS and redirect refusals, redirect count, size and timeout limits, and redacted URL errors. Integration cases verify that imageToBuffer refuses local inputs while still decoding image base64.

src/io/media/images/tests/untrustedImageFetch.test.ts

Documentation (2) +15 / -1
IMAGE_EDITING.mdDocument safe handling of user- and model-supplied images +14/-0

Document safe handling of user- and model-supplied images

• Shows how to convert untrusted input to a Buffer before editing. Documents refusals, address checks, redirects, and fetch limits.

docs/features/IMAGE_EDITING.md

VISION_PIPELINE.mdWarn that local vision tiers fetch URL strings directly +1/-1

Warn that local vision tiers fetch URL strings directly

• Advises callers to use untrusted image loading and pass a Buffer for user- or model-supplied URLs; the pipeline itself is unchanged.

docs/features/VISION_PIPELINE.md

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Invalid limits allow unbounded downloads ✓ Resolved
Description
fetchUntrustedImage accepts NaN or Infinity as maxBytes, making both response-size
comparisons ineffective. If a caller supplies either value, an untrusted endpoint can keep sending
chunks that accumulate in memory until the deadline expires.
Code

src/io/media/images/untrustedImageFetch.ts[178]

+  const maxBytes = options.maxBytes ?? UNTRUSTED_IMAGE_MAX_BYTES;
Evidence
The option is passed through without validation, including from imageToBuffer. Both checks use
>; neither rejects when maxBytes is NaN or Infinity, and the loop continues collecting
chunks.

src/io/media/images/imageToBuffer.ts[115-118]
src/io/media/images/untrustedImageFetch.ts[178-182]
src/io/media/images/untrustedImageFetch.ts[130-152]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An invalid `maxBytes` value disables both response-size checks, allowing untrusted responses to accumulate without a byte cap.
## Fix Focus Areas
- src/io/media/images/untrustedImageFetch.ts[178-182]
- src/io/media/images/untrustedImageFetch.ts[130-152]
## Recommended Fix
Validate `maxBytes` as a finite, nonnegative byte limit before starting the request, and reject invalid values. Add tests for `NaN` and `Infinity`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Compressed images reach editors undecoded ✓ Resolved
Description
readBody returns HTTP response chunks unchanged without handling Content-Encoding. When an
untrusted image URL serves a compressed response, imageToBuffer returns compressed bytes that an
image provider can receive in a blob labeled as an image.
Code

src/io/media/images/untrustedImageFetch.ts[152]

+    return Buffer.concat(chunks, total);
Evidence
The new fetch collects and returns chunks without checking the response's content encoding.
imageToBuffer returns that buffer directly, while an image provider places image buffers into
blobs labeled image/png.

src/io/media/images/untrustedImageFetch.ts[123-152]
src/io/media/images/imageToBuffer.ts[115-118]
src/io/media/images/providers/OpenAIImageProvider.ts[170-185]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The untrusted fetch returns compressed HTTP response bytes as though they were image bytes.
## Fix Focus Areas
- src/io/media/images/untrustedImageFetch.ts[123-152]
- src/io/media/images/imageToBuffer.ts[115-118]
## Recommended Fix
Handle supported `Content-Encoding` values before returning the image buffer, enforce a byte limit on decoded output, and test a compressed image response.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

…sed bodies

A maxBytes of NaN or Infinity made both size checks false, so an
untrusted response could grow until the deadline. maxBytes and
timeoutMs must be positive numbers, and timeoutMs at most Node's
longest timer, or the fetch throws a RangeError before connecting.

The response body was returned as it came, so a gzip-encoded image
reached the provider compressed. The request asks for identity; a gzip,
deflate or br body sent anyway is decoded, maxBytes counts the decoded
bytes so a compression bomb stops at the limit, and any other coding is
refused.
@jddunn
jddunn merged commit 31805b1 into master Oct 9, 2026
9 checks passed
github-actions Bot pushed a commit that referenced this pull request Oct 9, 2026
## [0.13.16](v0.13.15...v0.13.16) (2026-10-09)

### feat

* **images:** imageToBuffer reads untrusted input from public addresses only (#211) ([31805b1](31805b1))
@jddunn
jddunn deleted the fix/image-fetch-untrusted branch October 10, 2026 18:59
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.

1 participant