Unverified Commit fad31750 authored by Muhammad Zeeshan's avatar Muhammad Zeeshan Committed by GitHub

fix(next/image): reject non-2xx internal image responses (#97957)

- Fixes https://github.com/vercel/next.js/issues/82357
- Closes https://github.com/vercel/next.js/pull/96985

### What?

`fetchInternalImage()` only rejects the internal response when
`statusCode` is falsy, and `MockedResponse` defaults it to `200`, so
nothing really gets rejected there. A `307` coming from a `redirects()`
entry in `next.config`, or a `404` for a path that isn't there, both
count as a successful image fetch.

That body then reaches `detectContentType()`, which returns `null`, and
all you get is:

```
The requested resource isn't a valid image for /path/to/image.png received null
```

Nothing in that line points back at the response that actually came in,
so a redirect looks exactly like a corrupt image.

### Why?

`fetchExternalImage()` right above already covers this with `if
(!res.ok)` and logs `res.status`. The internal path is the only fetch in
the file without that check, so the same failure gets reported at the
fetch for remote images, and three steps later as "not a valid image"
for local ones.

### How?

The guard now rejects anything outside the 2xx range, which is what
`res.ok` means, and the log line carries the status next to the href.
The thrown `ImageError` message stays generic, same as the external
path, so nothing new shows up in the HTTP response body.

Because that throw passes `mocked.res.statusCode` into `ImageError`, a
non-2xx internal response now reports its own status instead of always
landing on `400`. `ImageError` still maps anything under 400 to `500`,
so a redirect answers `500` and a `404` stays `404`. That is what
`fetchExternalImage()` has always done, and it lines the two up: a
missing local image now returns `404` just like a missing remote one.

Three assertions in `test/e2e/image-optimizer/util.ts` shift because of
that:

- `should not forward cookie header`: `/api/conditional-cookie` answers
`401` when the cookie is missing, so `400` becomes `401`
- `should error if the image file does not exist`: `/does_not_exist.jpg`
returns `404` now, with the internal response message
- `should error if the resource isn't a valid image`: this one requested
`/test.txt`, but the fixture in `public/` is `text.txt`, so it was
quietly exercising a missing file instead of a non-image file. Pointed
at the file that exists, it keeps its original `400` and finally tests
what its name says

Two unit tests cover the new guard, one `307` and one `404`. Every other
test in that file sets `statusCode = 200`, so they are untouched.

#96985 is open against the same report with a different angle: it
threads the status through `ImageUpstream` so the existing "isn't a
valid image" log can print it. This one stops the request at the fetch,
so the redirect never reaches the optimizer at all. Whichever one fits
better, feel free to close mine.

### Verification

- `jest test/unit/image-optimizer/`: 139/139, and the two new tests fail
against a build without the guard
- `pnpm test-dev
test/e2e/image-optimizer/content-disposition-type.test.ts`: 97/97
- `pnpm test-start
test/e2e/image-optimizer/content-disposition-type.test.ts`: 97/97
- `prettier --check` clean on the three changed files

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 49f791cc
......@@ -998,8 +998,16 @@ export async function fetchInternalImage(
await handleRequest(mocked.req, mocked.res, parseReqUrl(href))
await mocked.res.hasStreamed
if (!mocked.res.statusCode) {
Log.error('image response failed for', href, mocked.res.statusCode)
if (
!mocked.res.statusCode ||
mocked.res.statusCode < 200 ||
mocked.res.statusCode > 299
) {
Log.error(
'internal image response failed for',
href,
mocked.res.statusCode
)
throw new ImageError(
mocked.res.statusCode,
'"url" parameter is valid but internal response is invalid'
......
......@@ -410,7 +410,8 @@ export function runTests(ctx: RunTestsCtx) {
const query = { w: ctx.w, q: ctx.q, url: '/api/conditional-cookie' }
const opts = { headers: { accept: 'image/webp', cookie: '1' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(400)
// the cookie is not forwarded so the internal handler responds 401
expect(res.status).toBe(401)
})
if (ctx.nextConfigImages?.dangerouslyAllowSVG) {
......@@ -1606,7 +1607,7 @@ export function runTests(ctx: RunTestsCtx) {
})
it("should error if the resource isn't a valid image", async () => {
const query = { url: '/test.txt', w: ctx.w, q: ctx.q }
const query = { url: '/text.txt', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/webp' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(400)
......@@ -1617,8 +1618,10 @@ export function runTests(ctx: RunTestsCtx) {
const query = { url: '/does_not_exist.jpg', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/webp' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(400)
expect(await res.text()).toBe("The requested resource isn't a valid image.")
expect(res.status).toBe(404)
expect(await res.text()).toBe(
'"url" parameter is valid but internal response is invalid'
)
})
if (domains.length > 0 && dangerouslyAllowLocalIP) {
......
......@@ -6,6 +6,63 @@ import {
import type { IncomingMessage, ServerResponse } from 'http'
describe('fetchInternalImage', () => {
describe('non-2xx responses', () => {
it('should throw error when the internal response is a redirect', async () => {
const mockReq = {} as IncomingMessage
const mockRes = {} as ServerResponse
const maximumResponseBody = 300_000_000
const handleRequest = jest.fn(async (_req: IncomingMessage, res: any) => {
res.statusCode = 307
res.getHeader = jest.fn(() => 'text/plain')
res.write('/redirected')
res.end()
})
const error = await fetchInternalImage(
'/test-image.jpg',
mockReq,
mockRes,
maximumResponseBody,
handleRequest
).catch((e) => e)
expect(error).toBeInstanceOf(ImageError)
// ImageError maps any status below 400 to 500
expect((error as ImageError).statusCode).toBe(500)
expect((error as ImageError).message).toBe(
'"url" parameter is valid but internal response is invalid'
)
})
it('should throw error when the internal response is a 404', async () => {
const mockReq = {} as IncomingMessage
const mockRes = {} as ServerResponse
const maximumResponseBody = 300_000_000
const handleRequest = jest.fn(async (_req: IncomingMessage, res: any) => {
res.statusCode = 404
res.getHeader = jest.fn(() => 'text/html')
res.write('<html>not found</html>')
res.end()
})
const error = await fetchInternalImage(
'/test-image.jpg',
mockReq,
mockRes,
maximumResponseBody,
handleRequest
).catch((e) => e)
expect(error).toBeInstanceOf(ImageError)
expect((error as ImageError).statusCode).toBe(404)
expect((error as ImageError).message).toBe(
'"url" parameter is valid but internal response is invalid'
)
})
})
describe('response size limit', () => {
it('should throw error when response has no buffers', async () => {
const mockReq = {} as IncomingMessage
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment