Skip to content

fix(images): the untrusted fetch settles on a protocol upgrade, and four review follow-ups - #227

Merged
jddunn merged 1 commit into
masterfrom
fix/untrusted-fetch-review
Oct 10, 2026
Merged

jddunn merged 1 commit into
masterfrom
fix/untrusted-fetch-review

Conversation

@jddunn

@jddunn jddunn commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

What this fixes

A cold security read of #211 (the untrusted mode of imageToBuffer) found five defects on master.

1. A 101 Switching Protocols reply left the fetch pending forever (P2). Node's HTTP client, on a 101 with Upgrade and Connection: upgrade and no 'upgrade' listener, closes the socket without an error (lib/_http_client.js, socketOnData). Neither 'response' nor 'error' fires. socketCloseListener marks the request destroyed, so the deadline's request.destroy() returns at once and the promise never settles. Any public host could hold a tool call open forever; ToolExecutor awaits execute() with no deadline of its own.

get() now settles on every way a request ends: a response, an error, the deadline (rejecting directly), an upgrade (with an 'upgrade' listener that destroys the socket), or a bare 'close'.

2. The refusal named the private address a host resolved to (P3). imageToBuffer: db.corp.internal resolves to 10.20.0.7, ... went back to whoever sent the URL. The packs return a refusal to the model as the tool's error, so a model steered to try internal names could map the network one refusal at a time (CWE-209). The message is now imageToBuffer: <host> does not resolve to a public network address. The address stays on the error as a non-enumerable resolvedAddress, for logs. A refused IP literal still names itself, since the caller wrote it.

3. Blocks the IANA registries mark not globally reachable passed as public (P3).

Block What it is
192.88.99.0/24 6to4 relay anycast (deprecated) and 6a44 relay
100:0:0:1::/64 dummy prefix; 100::/63 now covers it and the discard prefix
2001::/23 IETF protocol assignments: Teredo, benchmarking, ORCHID and others
3fff::/20 documentation
5f00::/16 SRv6 segment identifiers

Sources: the IPv4 and IPv6 special-purpose registries. A few globally reachable anycast blocks inside 2001::/23 are refused with the rest; no image is served from them.

4. A data URL with spaces around ;base64 was percent-decoded (P3). data:image/png; base64,... decoded as base64 before #211. WHATWG Fetch reads it as base64: the media type ends with ;, any spaces, then base64 (fetch spec, data: URL processor). The test is now /; *base64 *$/i.

Tests

untrustedImageFetch.test.ts, against the real local server:

  • a 101 upgrade is refused at once, not at the deadline;
  • a server that accepts and never sends headers is stopped by the deadline;
  • a redirect chain whose hops each answer in time, but not together, is stopped by the deadline;
  • a name with one refused address among several is refused in either order, and nothing is sent;
  • one lookup per connection: a resolver that counts its calls answers an allowed documentation address. The request fails, the resolver ran once, and the server saw nothing;
  • [::1] and [::ffff:127.0.0.1] URLs are refused before connecting;
  • deflate and br bodies decode;
  • HTTP:// and FILE: are read in any case;
  • a refused name's message has no address, and resolvedAddress has it.

networkAddress.test.ts lists the new blocks. imageToBuffer.test.ts covers both base64 spacings.

Not in this change

  • The vision-pipeline pack's pre-fetch hands the pipeline a Buffer, and VisionPipeline's TrOCR and Florence-2 tiers then pass transformers.js a data URL string it reads as a path. That is a separate fix in VisionPipeline.
  • The CLIP tier's text task is a known limit, documented in VISION_PIPELINE.md.

Summary by Sourcery

Harden untrusted image loading against hanging requests, private-network disclosure, unsafe address ranges, and non-standard data URL formatting.

Bug Fixes:

  • Ensure untrusted image requests settle on protocol upgrades, connection closes, request deadlines, and other terminal request outcomes instead of hanging.
  • Prevent untrusted image errors from disclosing resolved private addresses while retaining the address for non-enumerable diagnostics.
  • Block additional IPv4 and IPv6 ranges that are not globally reachable.
  • Interpret data URLs with optional spaces around the ;base64 marker correctly.

Enhancements:

  • Reuse the address validated during DNS checks and reject hostnames if any returned address is non-public.
  • Preserve support for compressed image responses and case-insensitive URL schemes in untrusted fetch coverage.

Tests:

  • Expand image-fetch integration coverage for request timeouts, protocol upgrades, redirect-chain deadlines, DNS resolution behavior, address disclosure, IPv6 literals, compressed responses, and URL scheme casing.
  • Add coverage for the newly blocked network address ranges and spaced data URL base64 markers.

…our review follow-ups

A cold security read of #211 found:

- A 101 Switching Protocols reply left the fetch pending forever. Node
  closes such a connection without an error when nothing listens for
  'upgrade', and a closed request ignores destroy(), so neither the
  error nor the deadline ended the wait. The request now settles on a
  response, an error, the deadline, an upgrade or a bare close.
- The refusal named the private address a host resolved to. It reaches
  whoever sent the URL, so a model told to try internal names could map
  the network one refusal at a time. The message leaves it out; the
  address stays on the error as a non-enumerable resolvedAddress.
- isPublicNetworkAddress passed several blocks the IANA special-purpose
  registries mark not globally reachable: 192.88.99.0/24, 100::/63,
  2001::/23, 3fff::/20 and 5f00::/16.
- A data URL with spaces around ;base64 was percent-decoded; WHATWG
  Fetch reads it as base64.

New tests cover each, and the claims that had none: a name with one
refused address among several, one lookup per connection, IPv6 literals
in brackets, deflate and br bodies, a server that never answers, a
redirect chain over the deadline, and URL schemes in upper case.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 10, 2026 01:15
@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 10, 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 4 hours and 24 minutes by commenting @sourcery-ai review. Upgrade to get a review now.

@coderabbitai

coderabbitai Bot commented Oct 10, 2026

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 6 billable files and costs up to $1.50.

  • 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 37 seconds 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: 17e17854-8483-43cc-a0f3-44ab9e264ace

📥 Commits

Reviewing files that changed from the base of the PR and between c105869 and 1a29d92.


📒 Files selected for processing (6)
  • 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/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 10, 2026

Copy link
Copy Markdown

Reviewer's Guide

The PR hardens untrusted image fetching by making every HTTP request termination path settle, preventing DNS-address disclosure and validation/connectivity races, expanding special-purpose address blocking, and fixing WHATWG-compatible data URL base64 parsing, with focused network and parser regression tests.

Sequence diagram for hardened untrusted image fetching

sequenceDiagram
    participant Caller
    participant Fetch as untrustedImageFetch
    participant DNS as DNS resolver
    participant Server as Image server

    Caller->>Fetch: imageToBuffer(url)
    Fetch->>DNS: checkedLookup(hostname)
    DNS-->>Fetch: addresses
    alt refused address
        Fetch-->>Caller: refusal(hostname)
    else allowed address
        Fetch->>Server: http.get(url)
        alt response
            Server-->>Fetch: response
            Fetch-->>Caller: image buffer
        else protocol upgrade
            Server-->>Fetch: 101 upgrade
            Fetch->>Server: socket.destroy()
            Fetch-->>Caller: refusal(error)
        else error, close, or deadline
            Server-->>Fetch: request termination
            Fetch-->>Caller: rejection(error)
        end
    end
Loading

Flow diagram for public-address validation

flowchart TD
    A[Resolve hostname] --> B{Any address is non-public?}
    B -->|Yes| C[Reject without sending request]
    C --> D[Expose resolvedAddress only for logs]
    B -->|No| E[Connect with one lookup per connection]
    E --> F[Fetch image]
Loading

Flow diagram for data URL parsing

flowchart TD
    A[Parse data URL] --> B{Media type ends with ; spaces base64 spaces?}
    B -->|Yes| C[Buffer.from payload as base64]
    B -->|No| D[percentDecodeBytes payload]
Loading

File-Level Changes

Change Details Files
Make untrusted HTTP image fetches settle deterministically across protocol upgrades, connection closure, aborts, and deadlines.
  • Track one-shot promise settlement and clean up abort listeners.
  • Handle 101 upgrades by destroying the socket and rejecting immediately.
  • Reject on bare connection close when no response has arrived.
  • Add integration coverage for upgrades, silent servers, and cumulative redirect timeouts.
src/io/media/images/untrustedImageFetch.ts
src/io/media/images/__tests__/untrustedImageFetch.test.ts
Prevent DNS-based network information disclosure while ensuring validation and connection use the same resolved addresses.
  • Sanitize refused-host error messages while retaining the refused address as a non-enumerable logging property.
  • Reject a hostname if any returned DNS address is disallowed.
  • Use a single lookup and preserve the checked address for the connection.
  • Cover multi-address resolution, IPv6 literals, and sanitized errors.
src/io/media/images/untrustedImageFetch.ts
src/io/media/images/__tests__/untrustedImageFetch.test.ts
Expand public-network filtering to cover additional IANA special-purpose IPv4 and IPv6 ranges.
  • Block the 192.88.99.0/24 IPv4 relay range.
  • Block IPv6 dummy, IETF assignment, documentation, and SRv6 ranges.
  • Add representative address tests for each new block.
src/io/media/images/networkAddress.ts
src/io/media/images/__tests__/networkAddress.test.ts
Align data URL parsing with WHATWG Fetch handling of whitespace around the base64 marker.
  • Recognize optional spaces before and after base64 in the media-type portion.
  • Test both supported spacing forms.
src/io/media/images/imageToBuffer.ts
src/io/media/images/__tests__/imageToBuffer.test.ts
Broaden untrusted image fetch regression coverage for protocol and content handling.
  • Verify deflate and Brotli response decoding.
  • Verify case-insensitive HTTP and FILE scheme handling.
  • Confirm refused requests do not reach the test server.
src/io/media/images/__tests__/untrustedImageFetch.test.ts
src/io/media/images/__tests__/imageToBuffer.test.ts

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

Fix untrusted image fetch hangs and tighten address refusals

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Settle untrusted image requests on protocol upgrades, premature closes, and deadlines to prevent
 indefinite waits.
• Hide resolved private addresses in refusals and block additional non-public network ranges.
• Decode spaced base64 data URLs correctly and expand security and fetch regression coverage.
Diagram

graph TD
  Parser["imageToBuffer"] --> Fetch["Untrusted fetch"] --> Lookup{"Public address?"} --> Request["HTTP GET"] --> Outcome{"Request outcome?"} -->|Response| Body["Image bytes"]
  Lookup -->|No| Refusal["Redacted refusal"]
  Outcome -->|Upgrade, close, deadline| Failure["Fetch error"]
Loading
High-Level Assessment

Keep the targeted changes to the existing checked-lookup HTTP client. Replacing it with a generic fetch client would require recreating its per-connection address checks, redirect enforcement, and response limits without improving these fixes.

Files changed (6) +183 / -25

Bug fix (3) +60 / -22
imageToBuffer.tsRecognize spaced base64 data URL markers +2/-1

Recognize spaced base64 data URL markers

• Allows spaces around the data URL ';base64' marker so those payloads are base64-decoded rather than percent-decoded.

src/io/media/images/imageToBuffer.ts

networkAddress.tsRefuse additional non-globally-reachable IP ranges +20/-10

Refuse additional non-globally-reachable IP ranges

• Extends IPv4 and IPv6 classification to block the specified 6to4 relay, dummy and discard, IETF assignment, documentation, and SRv6 ranges. Documents the policy and its broader refusal of some anycast addresses.

src/io/media/images/networkAddress.ts

untrustedImageFetch.tsSettle every request end and redact DNS refusals +38/-11

Settle every request end and redact DNS refusals

• Makes the HTTP GET promise reject on an upgrade, premature close, or abort, with a settlement guard to avoid competing outcomes. Removes resolved addresses from DNS refusal messages while retaining them as a non-enumerable error property.

src/io/media/images/untrustedImageFetch.ts

Tests (3) +123 / -3
imageToBuffer.test.tsCover spaces around data URL base64 markers +3/-0

Cover spaces around data URL base64 markers

• Adds cases for spaces after the semicolon and after 'base64', confirming both payloads decode as base64.

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

networkAddress.test.tsCover newly refused special-purpose address blocks +8/-0

Cover newly refused special-purpose address blocks

• Adds IPv4 and IPv6 examples from the newly blocked IANA ranges to the non-public-address tests.

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

untrustedImageFetch.test.tsExercise fetch termination and security boundaries +112/-3

Exercise fetch termination and security boundaries

• Adds local-server cases for protocol upgrades, silent servers, cumulative redirect deadlines, and deflate and Brotli bodies. Also checks DNS-answer refusal and single-lookup behavior, bracketed IPv6 literals, case-insensitive schemes, and redacted refusal messages.

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

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. Refused addresses disappear from logs 🐞 Bug ◔ Observability
Description
checkedLookup removes the resolved address from the refusal message and stores it in a
non-enumerable property that the existing error handlers never read. When a hostname resolves to a
refused address, tool execution logs the error or its message and normalizes it without that
property, so operators cannot see which address caused the refusal.
Code

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

+        Object.defineProperty(error, 'resolvedAddress', { value: refused?.address, enumerable: false });
Evidence
The changed refusal puts the address only in a non-enumerable property. The tool failure handler
logs the raw error or its name and message, then retains err.toString(); its error normalizer
retains only standard Error fields. None explicitly reads resolvedAddress.

src/io/media/images/untrustedImageFetch.ts[89-97]
src/core/tools/ToolExecutor.ts[413-427]
src/core/utils/errors.ts[221-278]

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

## Issue description
Refused DNS addresses are removed from the error message but are not captured by the existing logging or error-normalization paths. Preserve the address for operators without returning it in model-visible error details.
## Fix Focus Areas
- src/io/media/images/untrustedImageFetch.ts[91-97]
- src/core/tools/ToolExecutor.ts[413-427]
## Recommended Fix
Add a trusted, server-side logging path that explicitly reads `resolvedAddress` for refused lookups. Keep the address out of the refusal message and tool result, and test both the operator log and the model-visible error.

ⓘ 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 copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@jddunn
jddunn merged commit 9efb4b5 into master Oct 10, 2026
8 checks passed
github-actions Bot pushed a commit that referenced this pull request Oct 10, 2026
## [0.13.23](v0.13.22...v0.13.23) (2026-10-10)

### fix

* **gmi:** follow-ups from the reviews of #193 and #199 (#217) ([2bacb69](2bacb69))
* **gmi:** manager shutdown waits for creations in flight, bounds each GMI and runs once (#222) ([d99b126](d99b126))
* **images:** the untrusted fetch settles on a protocol upgrade, and four review follow-ups (#227) ([9efb4b5](9efb4b5))
* **vision:** the TrOCR and Florence-2 tiers get a Buffer image as a Blob (#229) ([7fe444a](7fe444a))
@jddunn
jddunn deleted the fix/untrusted-fetch-review branch October 10, 2026 19:00
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