Skip to content

fix(images): the untrusted image fetch closes six gaps a security review found - #278

Merged
jddunn merged 2 commits into
masterfrom
fix/untrusted-fetch-hardening
Oct 11, 2026
Merged

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

Conversation

@jddunn

@jddunn jddunn commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

What this fixes

imageToBuffer(source, { untrusted: true }) is the fetch for a URL a model's tool call or a user gave. Its promise: public network addresses only, checked at every connection and every redirect, within 50 MiB and 30 seconds. A security review found six ways around it.

Gap A concrete case Now
Reserved IPv6 space read as public http://[4000::1]/secret, on a network that routes that space to itself Only 2000::/3 is public: it is the one block allocated for global unicast (IANA). The deprecated IPv4-compatible form (::a.b.c.d) is refused whatever it carries
A network's own NAT64 prefix http://[<prefix>::a9fe:a9fe]/, which a NAT64 gateway sends to 169.254.169.254 An IPv6 address under a NAT64 prefix of the network must carry a public IPv4 address. The prefixes come from the resolver's answer for ipv4only.arpa (RFC 7050), read by the layouts of RFC 6052, kept five minutes on the network they were learned on, and asked for only when a fetch goes to an IPv6 address. When the resolver fails to answer that question, the IPv6 address is refused
The lookup hid an address family On an IPv6-only network, internal.example with the address 10.1.2.3 resolved to the NAT64 address a DNS64 resolver made from it, and nothing else The resolver is asked without ADDRCONFIG, the hint Node adds to a connection's lookup, so both families are checked
Size counted after decoding only A gzip body whose header carries a 60 MiB file name and a small image A compressed body is counted on the wire too
Inline images had no limit data:image/png;base64, followed by 70 MiB An image decoded from the string is held to maxBytes. Its size is worked out from the text, so one over the limit is not decoded
The deadline could miss the decoder A compressed response that ends just before the deadline, with decoding still running The deadline ends the decoder as well as the response

One more change keeps a refusal from telling which internal names exist. The message was already the same for a name that resolves to a refused address and one that does not resolve, but the address and the resolver's error were properties of the error, and util.inspect prints an error's cause. They move off the error: imageUrlRefusalDetail(error) returns them for a log.

A network that announces its NAT64 prefix by other means than DNS64 (a router advertisement, PCP) is not covered; fetchUntrustedImage's allowAddress is the place for a host's own rule.

Behaviour that changes

  • isPublicNetworkAddress returns false for IPv6 outside 2000::/3 and for ::a.b.c.d. It takes an optional second argument, { nat64Prefixes }.
  • error.resolvedAddress and error.cause are gone from a refusal (they were added in 0.13.30); use imageUrlRefusalDetail(error).
  • memory's guardedFetch uses isPublicNetworkAddress, so it gets the first row of the table. The lookup and size changes are in the image fetch alone.

Tests

networkAddress.test.ts: the reserved blocks; an address under a /32, /64 and /96 prefix that carries a private, link-local or loopback IPv4 address; nat64PrefixesFrom against the six layouts of RFC 6052's own example table.

untrustedImageFetch.test.ts, against a local server:

  • the lookup is asked with all and without ADDRCONFIG;
  • a name with a public address in one family and this machine in the other is refused;
  • a resolver that reveals a NAT64 prefix: a name and a literal that reach a private address through it are refused, and the prefix is asked for once;
  • an https: URL: a refused name opens no connection, an allowed one opens its own;
  • a gzip body with a 5 KB header file name is refused at 3,000 bytes and read at 6,000;
  • a data URL (base64 and percent-encoded) and raw base64 over maxBytes are refused when untrusted, and read when trusted.

untrustedImageFetch.deadline.test.ts pins the decoder and the deadline. The real decoder finishes within milliseconds of the response, so the test replaces zlib's gunzip with one that holds its output for 600 ms: the fetch must give up at its 150 ms deadline. Before this change it returned the image at 600 ms.

The review of the first commit added: a resolver that fails the NAT64 question refuses the address and is asked again next time; the prefix cache entry is stored before the resolver is asked (a resolver that answered at once with an error had its failure kept); nat64PrefixesFrom requires byte 8 to be zero where RFC 6052 reserves it.

…iew found

- IPv6 outside 2000::/3 is not public. Only that block is allocated for
  global unicast; the rest is special-purpose or unallocated space, which
  a network can route to itself. The deprecated IPv4-compatible form
  (::a.b.c.d) is refused whatever it carries.
- A network's own NAT64 prefix (RFC 6052) is honoured: an IPv6 address
  under it stands for an IPv4 address, which must be public too. The
  prefixes are read from the resolver's answer for ipv4only.arpa (RFC
  7050), kept five minutes, and asked for only when a fetch goes to an
  IPv6 address.
- The resolver is asked for every address of a name without ADDRCONFIG,
  the hint Node adds that leaves out a family the machine has no address
  of. On an IPv6-only network it hid a name's private IPv4 address behind
  the NAT64 address made from it.
- A compressed body is counted on the wire as well as decoded: a gzip
  header's file name is megabytes that decode to nothing.
- The deadline ends the decoder too, which can hold input after the
  response has ended, and an image given in the string itself (a data
  URL, raw base64) is held to maxBytes.
- The address a name resolved to, and the resolver's error, are no longer
  properties of the refusal: imageUrlRefusalDetail(error) gives them for a
  log. util.inspect prints an error's cause, which told a missing name
  from a refused one.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 11, 2026 00:34
@sourcery-ai

sourcery-ai Bot commented Oct 11, 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 12 minutes by commenting @sourcery-ai review. Upgrade to get a review now.

@coderabbitai

coderabbitai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 7 billable files and costs up to $1.75.

  • 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 2 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: 55e73b6c-fb4d-400c-ab97-b2c1d13e2ce9

📥 Commits

Reviewing files that changed from the base of the PR and between d4d3c6d and ce6633d.


📒 Files selected for processing (7)
  • docs/features/IMAGE_EDITING.md
  • src/io/media/images/__tests__/networkAddress.test.ts
  • src/io/media/images/__tests__/untrustedImageFetch.deadline.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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 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-10-11T00:36:43.330327Z 0f2a34c PR opened
ℹ️ 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.

@sourcery-ai

sourcery-ai Bot commented Oct 11, 2026

Copy link
Copy Markdown

Reviewer's Guide

Closes six untrusted-image-fetch security gaps by validating all relevant IPv4/IPv6 and DNS64/NAT64 paths, enforcing byte limits before and after content decoding—including inline inputs—and making timeouts terminate decoder work, while separating sensitive refusal diagnostics from exposed errors.

Sequence diagram for the hardened untrusted image fetch

sequenceDiagram
    participant Caller
    participant Fetch as fetchUntrustedImage
    participant DNS as dns.lookup
    participant Server as HTTP_Server
    participant Decoder as Content_Decoder

    Caller->>Fetch: fetchUntrustedImage(source, options)
    Fetch->>Fetch: isPublicNetworkAddress(source)
    Fetch->>DNS: lookup(hostname, all, without ADDRCONFIG)
    DNS-->>Fetch: IPv4 and IPv6 addresses
    opt IPv6 address resolved
        Fetch->>DNS: lookup(ipv4only.arpa, family 6, all)
        DNS-->>Fetch: NAT64 prefix addresses
        Fetch->>Fetch: nat64PrefixesFrom(addresses)
        Fetch->>Fetch: isPublicNetworkAddress(address, nat64Prefixes)
    end
    Fetch->>Server: GET with checked connection
    Server-->>Fetch: response and redirects
    opt redirect
        Fetch->>Fetch: check redirect address
        Fetch->>Server: GET redirected URL
    end
    Server-->>Decoder: compressed response body
    Decoder->>Decoder: enforce encoded and decoded maxBytes
    Fetch->>Decoder: readBody(response, signal)
    alt timeout or size limit
        Fetch->>Decoder: destroy(error)
        Fetch->>Server: destroy(error)
    else valid body
        Decoder-->>Caller: image Buffer
    end
Loading

Flow diagram for bounded trusted and untrusted image inputs

flowchart TD
    A["imageToBuffer(input, options)"] --> B{untrusted?}
    B -- no --> C[Decode or fetch input]
    B -- yes --> D["untrustedByteLimit(maxBytes)"]
    D --> E{Input kind}
    E -- data URL --> F[Decode payload]
    E -- raw base64 --> G[Decode base64]
    E -- http or https URL --> H[fetchUntrustedImage]
    F --> I[sizeCheck]
    G --> I
    I --> J{Within maxBytes?}
    J -- no --> K[Refuse oversized image]
    J -- yes --> L[Return image Buffer]
    H --> M[Check URL, DNS results, and redirects]
    M --> N[Read wire bytes and decoded bytes]
    N --> O{Within maxBytes and timeout?}
    O -- no --> K
    O -- yes --> L
Loading

File-Level Changes

Change Details Files
Tighten public-address validation for IPv6 and network-specific NAT64 mappings.
  • Restrict IPv6 public space to 2000::/3 and preserve checks for embedded IPv4 forms and special ranges.
  • Decode RFC 6052 NAT64 prefixes and evaluate embedded IPv4 addresses against private/reserved ranges.
  • Cache DNS64-derived prefixes for five minutes and apply them to IPv6 URL and hostname connection checks.
  • Resolve hostnames with all address families while removing ADDRCONFIG, and keep refusal diagnostics outside error properties.
src/io/media/images/networkAddress.ts
src/io/media/images/untrustedImageFetch.ts
src/io/media/images/imageToBuffer.ts
src/io/media/images/__tests__/networkAddress.test.ts
src/io/media/images/__tests__/untrustedImageFetch.test.ts
Enforce untrusted image size limits across both encoded network data and string-decoded inputs.
  • Apply maxBytes to data URLs and raw base64 decoded by imageToBuffer.
  • Count compressed response bytes on the wire in addition to decoded bytes.
  • Centralize positive maxBytes validation and reuse the limit for fetches and inline images.
src/io/media/images/imageToBuffer.ts
src/io/media/images/untrustedImageFetch.ts
src/io/media/images/__tests__/untrustedImageFetch.test.ts
Ensure fetch deadlines terminate response decoders as well as network responses.
  • Abort and destroy the active decoder when the timeout signal fires.
  • Race address-check waits against the fetch deadline and reject after abort.
  • Retain response completeness and decoded-size checks after stream termination.
src/io/media/images/untrustedImageFetch.ts
Document the expanded SSRF, size, timeout, and refusal-detail behavior.
  • Describe IPv6/NAT64 address policy, both-family DNS checks, and unsupported non-DNS64 NAT64 announcements.
  • Document maxBytes coverage for fetched and inline images and the imageUrlRefusalDetail logging API.
docs/features/IMAGE_EDITING.md

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

Harden untrusted image fetching against network and size-limit bypasses

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Refuse reserved IPv6 addresses and NAT64 routes to private IPv4 destinations.
• Check both DNS address families and enforce size limits on encoded responses and inline images.
• Extend decoder deadlines and keep diagnostic refusal details off user-visible errors.
Diagram

graph TD
  Input["Image input"] --> Policy{"Address allowed?"} --> Transport["HTTP transport"] --> Decode["Bounded decoding"]
  DNS["DNS resolver"] --> NAT64["NAT64 discovery"] --> Policy
  DNS --> Policy
  Input --> Decode
  Policy --> Detail["Refusal details"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Preflight or incrementally decode inline images
  • ➕ Rejects oversized encoded inputs before allocating the complete decoded Buffer.
  • ➖ Adds parsing complexity for base64 and percent-encoded data URLs.

Recommendation: The PR's connection-time checks and separate wire/decoded limits directly address the identified fetch bypasses. Consider preflight or incremental inline decoding if maxBytes must also bound peak memory: the current inline check runs after decoding.

Files changed (6) +598 / -87

Bug fix (3) +346 / -72
imageToBuffer.tsApply untrusted byte limits to inline image strings +36/-9

Apply untrusted byte limits to inline image strings

• Validates maxBytes for untrusted strings and rejects oversized data URLs or raw base64 after decoding. Re-exports the refusal-detail accessor.

src/io/media/images/imageToBuffer.ts

networkAddress.tsRestrict IPv6 classification and inspect NAT64-carried IPv4 +119/-29

Restrict IPv6 classification and inspect NAT64-carried IPv4

• Limits ordinary public IPv6 addresses to eligible space within 2000::/3 and rejects deprecated IPv4-compatible addresses. Adds RFC 6052 prefix extraction and optional NAT64-aware address checks.

src/io/media/images/networkAddress.ts

untrustedImageFetch.tsHarden connection checks, body limits, and refusal privacy +191/-34

Harden connection checks, body limits, and refusal privacy

• Checks all resolved address families without ADDRCONFIG and consults cached DNS64-discovered prefixes for IPv6 destinations. Counts compressed wire bytes, aborts the decoder at the deadline, and stores refusal diagnostics in a WeakMap rather than on errors.

src/io/media/images/untrustedImageFetch.ts

Tests (2) +245 / -14
networkAddress.test.tsCover reserved IPv6 space and NAT64 address extraction +71/-1

Cover reserved IPv6 space and NAT64 address extraction

• Adds cases for unallocated IPv6 ranges, private IPv4 destinations under NAT64 prefixes, and all six RFC 6052 prefix layouts.

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

untrustedImageFetch.test.tsExercise DNS, refusal, transport, and size protections +174/-13

Exercise DNS, refusal, transport, and size protections

• Tests both-family lookups without ADDRCONFIG, NAT64 refusals, HTTPS connection checks, hidden refusal diagnostics, compressed wire limits, and inline-image limits.

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

Documentation (1) +7 / -1
IMAGE_EDITING.mdDocument tightened untrusted-image guarantees +7/-1

Document tightened untrusted-image guarantees

• Explains both-family address checks, IPv6 and NAT64 restrictions, refusal diagnostics, and byte limits for fetched and inline images.

docs/features/IMAGE_EDITING.md

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

qodo-free-for-open-source-projects Bot commented Oct 11, 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


Action required

1. A failed prefix lookup permits private targets ✓ Resolved
Description
nat64Prefixes turns resolver errors other than ENOTFOUND into an empty prefix list, which
addressCheck treats as permission to use a public-looking IPv6 address. If the target address
resolves but the separate ipv4only.arpa lookup fails transiently, a NAT64 address carrying a
private or link-local IPv4 destination passes the connection check.
Code

src/io/media/images/untrustedImageFetch.ts[R147-150]

+        if (error) {
+          if ((error as NodeJS.ErrnoException).code !== 'ENOTFOUND') nat64PrefixCache.delete(resolve);
+          done([]);
+          return;
Evidence
The discovery callback resolves [] on any error; the address check then applies that empty list to
otherwise public-looking IPv6 addresses before returning them to the connection lookup.

src/io/media/images/untrustedImageFetch.ts[141-161]
src/io/media/images/untrustedImageFetch.ts[175-183]
src/io/media/images/untrustedImageFetch.ts[213-220]

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

## Issue description
A transient failure discovering a DNS64 prefix is treated as an empty prefix list, allowing an IPv6 NAT64 address carrying a private IPv4 target through the untrusted fetch check.
## Fix Focus Areas
- src/io/media/images/untrustedImageFetch.ts[141-161]
- src/io/media/images/untrustedImageFetch.ts[175-184]
## Recommended Fix
Distinguish a confirmed absence of DNS64 from a transient discovery failure. Reject or retry IPv6 fetches when prefix discovery fails transiently, and add a test where the target resolves but `ipv4only.arpa` returns an error.

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



Remediation recommended

2. Decoder deadline failures go untested ✓ Resolved
Description
readBody now destroys the decoder as well as the response when the deadline expires, but no
compressed-response test exercises that abort path. The existing /stall test uses an uncompressed
response, while /gzip-padded checks size without a deadline, so neither catches a regression when
decoding outlives the response.
Code

src/io/media/images/untrustedImageFetch.ts[R358-361]

+  const onAbort = () => {
+    const error = new Error('aborted');
+    body.destroy(error);
+    response.destroy(error);
Evidence
The changed abort handler explicitly destroys the decoded stream. The existing deadline test covers
an uncompressed stall, and the added compressed-body test covers byte limits rather than deadline
cancellation.

AGENTS.md: Use Meaningful Integration and Unit Tests: AGENTS.md: Use Meaningful Integration and Unit Tests: AGENTS.md: Use Meaningful Integration and Unit Tests: AGENTS.md: Use Meaningful Integration and Unit Tests
src/io/media/images/untrustedImageFetch.ts[357-362]
src/io/media/images/tests/untrustedImageFetch.test.ts[446-450]
src/io/media/images/tests/untrustedImageFetch.test.ts[489-497]

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 changed decoder-abort behavior has no test exercising a deadline during compressed-body decoding.
## Fix Focus Areas
- src/io/media/images/untrustedImageFetch.ts[358-361]
- src/io/media/images/__tests__/untrustedImageFetch.test.ts[446-450]
- src/io/media/images/__tests__/untrustedImageFetch.test.ts[489-497]
## Recommended Fix
Add a real-path compressed-response timeout test that verifies the fetch rejects promptly at its deadline. If the post-response decoder window cannot be controlled reliably in an integration test, add a focused deterministic test for that abort path.

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


3. A network change permits private targets ✓ Resolved
Description
nat64PrefixCache reuses a prefix set for five minutes based only on resolver function identity. If
the network changes its NAT64 prefix during that interval, an address under the new prefix that
carries a private IPv4 destination is checked only against the old prefix and can reach the
connection.
Code

src/io/media/images/untrustedImageFetch.ts[R141-143]

+function nat64Prefixes(resolve: LookupFunction): Promise<Nat64Prefix[]> {
+  const cached = nat64PrefixCache.get(resolve);
+  if (cached && Date.now() - cached.at < NAT64_PREFIX_TTL_MS) return cached.prefixes;
Evidence
The cache key and TTL do not include network state, while addressCheck checks IPv6 destinations
exclusively against the returned cached prefixes.

src/io/media/images/untrustedImageFetch.ts[127-161]
src/io/media/images/untrustedImageFetch.ts[175-183]
src/io/media/images/untrustedImageFetch.ts[213-220]

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

## Issue description
A prefix cached under a stable resolver function remains in use after the network's NAT64 prefix changes, so validation can miss a newly synthesized private destination.
## Fix Focus Areas
- src/io/media/images/untrustedImageFetch.ts[127-161]
- src/io/media/images/untrustedImageFetch.ts[175-183]
## Recommended Fix
Invalidate prefix discovery on network or resolver configuration changes, or avoid reusing a prefix set where current network identity cannot be established. Test a resolver whose advertised prefix changes between fetches.

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


4. Some public IPv6 images are refused ✓ Resolved
Description
nat64PrefixesFrom accepts an apparent embedded IPv4 address without checking the reserved byte
that embeddedIPv4 skips for shorter prefixes. If an ipv4only.arpa answer has a nonzero reserved
byte but the extracted bytes match 192.0.0.170 or .171, it creates a spurious prefix that can
cause a subsequent public IPv6 address to be refused.
Code

src/io/media/images/networkAddress.ts[R158-162]

+    for (const length of NAT64_PREFIX_LENGTHS) {
+      const [a, b, c, d] = embeddedIPv4(bytes, length);
+      if (a === 192 && b === 0 && c === 0 && (d === 170 || d === 171)) {
+        const prefix = bytes.slice(0, length / 8);
+        found.set(`${prefix.join('.')}/${length}`, { bytes: prefix, length });
Evidence
embeddedIPv4 skips byte 8 without validating it, and prefix discovery records any address whose
remaining bytes match the probe IPv4 addresses. The resulting prefix is applied to later IPv6
destination checks.

src/io/media/images/networkAddress.ts[125-135]
src/io/media/images/networkAddress.ts[152-166]
src/io/media/images/untrustedImageFetch.ts[175-183]

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

## Issue description
Prefix discovery recognizes malformed synthesized addresses because it checks the extracted IPv4 bytes but not the reserved byte skipped by the shorter NAT64 layouts.
## Fix Focus Areas
- src/io/media/images/networkAddress.ts[125-135]
- src/io/media/images/networkAddress.ts[152-166]
## Recommended Fix
For the 32-, 40-, 48-, 56-, and 64-bit layouts, require the reserved byte at index 8 to be zero before recording a prefix. Add a malformed-answer test demonstrating that it produces no prefix.

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


View review recommended (1)
5. A failed NAT64 prefix query can stay cached for five minutes ✓ Resolved
Description
In nat64Prefixes, the error path calls nat64PrefixCache.delete(resolve) (and so does the catch
for a resolver that throws), but nat64PrefixCache.set(resolve, …) only runs after the Promise
executor has returned. A resolver that calls back synchronously with an error other than
ENOTFOUND, or throws synchronously, therefore runs the delete first, then the set stores the
empty-prefix promise for NAT64_PREFIX_TTL_MS, so for five minutes no NAT64 prefix is checked and
IPv6 addresses that reach private IPv4 hosts through the network's own prefix are allowed, even
though the docstring promises such failures are not kept.
Code

src/io/media/images/untrustedImageFetch.ts[R157-160]

+      done([]);
+    }
+  });
+  nat64PrefixCache.set(resolve, { at: Date.now(), prefixes });
Evidence
The Promise executor runs synchronously. With a synchronous callback (the kind the test lookups use)
or a synchronous throw, the delete at line 148 or 156 runs while there is still nothing cached. Line
160 then stores { at: Date.now(), prefixes }, a promise that has already resolved to [].
addressCheck uses that cached [] for every IPv6 address until the TTL runs out, so the NAT64
check quietly stops refusing addresses.

src/io/media/images/untrustedImageFetch.ts[141-162]
src/io/media/images/untrustedImageFetch.ts[175-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
`nat64Prefixes` deletes the cache entry when a lookup fails, but it sets the entry only after the Promise executor returns. A resolver that fails synchronously or throws therefore leaves its failure cached for five minutes, and the NAT64 check is turned off for that time.
## Fix Focus Areas
- src/io/media/images/untrustedImageFetch.ts[141-162]
## Recommended Fix
Create the cache entry before calling the resolver. For example, build the promise with a deferred `done`, call `nat64PrefixCache.set(resolve, entry)`, and only then call `resolve(...)`. In the failure paths, delete only when `nat64PrefixCache.get(resolve) === entry`. Another option is to record a `failed` flag in the executor and skip the `set` when it is true. Add a test with a lookup that calls back synchronously with an `EAI_AGAIN`-style error and check that the next fetch asks again.

ⓘ 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 tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/io/media/images/networkAddress.ts Resolved

@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: 0f2a34c5ef

ℹ️ 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 thread src/io/media/images/imageToBuffer.ts Resolved
- A resolver that fails to say whether the network has a NAT64 prefix
  (any error but "no such address") no longer counts as "no prefix": the
  IPv6 address is refused, and the question is asked again next time.
- The prefix cache entry is stored before the resolver is asked. A
  resolver that answered at once with an error removed nothing and then
  had its failure kept for five minutes.
- A cached prefix is used only on the network it was learned on: the
  entry carries the machine's interface addresses.
- nat64PrefixesFrom requires byte 8 to be zero where RFC 6052 reserves
  it, so bytes that only happen to spell 192.0.0.170 name no prefix.
- An inline image's size is worked out from its text before decoding, so
  one over the limit is not allocated.
- A test holds zlib's gunzip open past the end of the response and shows
  the fetch gives up at its deadline, not when the decoder is done.
@jddunn
jddunn merged commit b99ecbc into master Oct 11, 2026
9 checks passed
@jddunn
jddunn deleted the fix/untrusted-fetch-hardening branch October 11, 2026 00:53
github-actions Bot pushed a commit that referenced this pull request Oct 11, 2026
## [0.13.40](v0.13.39...v0.13.40) (2026-10-11)

### feat

* **auth:** OAuth for a web server: a redirect flow, sealed secrets and a sealed token store (#242) ([59a20d1](59a20d1))
* **voice-pipeline:** build a speech-to-text chain from provider entries (#176) ([29046f2](29046f2))

### fix

* **images:** a local A1111 edit reports the checkpoint the server rendered with (#279) ([3744044](3744044))
* **images:** the untrusted image fetch closes six gaps a security review found (#278) ([b99ecbc](b99ecbc))
* **memory:** the guarded fetch's deadline covers decoding, and a network refusal names no resolver detail (#280) ([7d8bc9e](7d8bc9e))

### docs

* eleventh round of audit follow-ups (two pages published, the agent() and gmi() guides aligned) (#264) ([d4d3c6d](d4d3c6d))
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