From 98211405a60d286a8769dc1b76723016153355a6 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Thu, 25 Mar 2021 01:59:00 +0800 Subject: [PATCH] Make sure the image optimization endpoint only response with images (#23366) If the upstream MIME type isn't prefixed with `image/`, the endpoint should directly response with a 400 error. ## Bug - [x] Fixes #23312 - [x] Integration tests added ## Feature - [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Documentation added - [ ] Telemetry added. In case of a feature if it's used or not. ## Documentation / Examples - [ ] Make sure the linting passes --- packages/next/next-server/server/image-optimizer.ts | 7 +++++++ test/integration/image-optimizer/public/text.txt | 1 + test/integration/image-optimizer/test/index.test.js | 8 ++++++++ 3 files changed, 16 insertions(+) create mode 100644 test/integration/image-optimizer/public/text.txt diff --git a/packages/next/next-server/server/image-optimizer.ts b/packages/next/next-server/server/image-optimizer.ts index 69bb10f261..eef496c15f 100644 --- a/packages/next/next-server/server/image-optimizer.ts +++ b/packages/next/next-server/server/image-optimizer.ts @@ -230,6 +230,13 @@ export async function imageOptimizer( sendResponse(req, res, upstreamType, upstreamBuffer) return { finished: true } } + + // If upstream type is not a valid image type, return 400 error. + if (!upstreamType.startsWith('image/')) { + res.statusCode = 400 + res.end("The requested resource isn't a valid image.") + return { finished: true } + } } let contentType: string diff --git a/test/integration/image-optimizer/public/text.txt b/test/integration/image-optimizer/public/text.txt new file mode 100644 index 0000000000..32f95c0d12 --- /dev/null +++ b/test/integration/image-optimizer/public/text.txt @@ -0,0 +1 @@ +hi \ No newline at end of file diff --git a/test/integration/image-optimizer/test/index.test.js b/test/integration/image-optimizer/test/index.test.js index 41cb945cb3..f5bf0e2847 100644 --- a/test/integration/image-optimizer/test/index.test.js +++ b/test/integration/image-optimizer/test/index.test.js @@ -481,6 +481,14 @@ function runTests({ w, isDev, domains }) { expect(res.headers.get('etag')).toBeTruthy() await expectWidth(res, 400) }) + + it("should error if the resource isn't a valid image", async () => { + const query = { url: '/test.txt', w, q: 80 } + const opts = { headers: { accept: 'image/webp' } } + const res = await fetchViaHTTP(appPort, '/_next/image', query, opts) + expect(res.status).toBe(400) + expect(await res.text()).toBe("The requested resource isn't a valid image.") + }) } describe('Image Optimizer', () => { -- GitLab