From e5be344932589bd71d50b9a08f54f1aeb34df7f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20S=C3=B8gaard?= Date: Wed, 6 Jul 2022 16:09:29 +0200 Subject: [PATCH] Correctly check if width is lte 0 in Image Optimization API (#38226) This PR corrects a mistake where a negative number could pass, as a number greater than 0. This is due to negative numbers being a truthy value in JS. ## Bug - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Errors have helpful link attached, see `contributing.md` ## 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. - [ ] Errors have helpful link attached, see `contributing.md` ## Documentation / Examples - [ ] Make sure the linting passes by running `pnpm lint` - [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples) --- packages/next/server/image-optimizer.ts | 2 +- test/integration/image-optimizer/test/util.js | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/next/server/image-optimizer.ts b/packages/next/server/image-optimizer.ts index 599f7b1254b1..155f994ed496 100644 --- a/packages/next/server/image-optimizer.ts +++ b/packages/next/server/image-optimizer.ts @@ -125,7 +125,7 @@ export class ImageOptimizerCache { const width = parseInt(w, 10) - if (!width || isNaN(width)) { + if (width <= 0 || isNaN(width)) { return { errorMessage: '"w" parameter (width) must be a number greater than 0', } diff --git a/test/integration/image-optimizer/test/util.js b/test/integration/image-optimizer/test/util.js index e49628e9676a..e8a7094fd6c8 100644 --- a/test/integration/image-optimizer/test/util.js +++ b/test/integration/image-optimizer/test/util.js @@ -397,7 +397,7 @@ export function runTests(ctx) { ) }) - it('should fail when w is 0 or less', async () => { + it('should fail when w is 0', async () => { const query = { url: '/test.png', w: 0, q: 100 } const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {}) expect(res.status).toBe(400) @@ -406,6 +406,15 @@ export function runTests(ctx) { ) }) + it('should fail when w is less than 0', async () => { + const query = { url: '/test.png', w: -100, q: 100 } + const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {}) + expect(res.status).toBe(400) + expect(await res.text()).toBe( + `"w" parameter (width) must be a number greater than 0` + ) + }) + it('should fail when w is not a number', async () => { const query = { url: '/test.png', w: 'foo', q: 100 } const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {})