Unverified Commit 8d415853 authored by Steven's avatar Steven Committed by GitHub

[Breaking] feat(next/image)!: add support for `images.dangerouslyAllowLocalIP`…

[Breaking] feat(next/image)!: add support for `images.dangerouslyAllowLocalIP` and `images.maximumRedirects` (#84676)

This PR adds a two new options and sets a strict default value for each.

- `images.dangerouslyAllowLocalIP`
- `images.maximumRedirects`

### dangerouslyAllowLocalIP

In rare cases when self-hosting Next.js on a private network, you may
want to allow optimizing images from local IP addresses on the same
network.

However, this is not recommended for most users so the default is
`false`.

> [!NOTE]
> BREAKING CHANGE: This change is breaking for those who self-hosting
Next.js on a private network and want to allow optimizing images from
local IP addresses on the same network. In those cases, you can still
enable the config.

### maximumRedirects

Since are also testing redirects for local IPs, we can also reduce the
maximum number of redirects to 3 by default.

Unlike normal websites which might redirect for features like auth, its
unusual to have more than 3 redirects for an image.

In some rare cases, developers may need to increase this value or set to
`0` to disable redirects.

> [!NOTE]
> BREAKING CHANGE: This change is breaking for those who need image
optimization to follow more than 3 redirects.
parent 8041a382
...@@ -30,6 +30,8 @@ ...@@ -30,6 +30,8 @@
"disableStaticImages": false, "disableStaticImages": false,
"minimumCacheTTL": 60, "minimumCacheTTL": 60,
"formats": ["image/avif", "image/webp"], "formats": ["image/avif", "image/webp"],
"maximumRedirects": 3,
"dangerouslyAllowLocalIP": false,
"dangerouslyAllowSVG": false, "dangerouslyAllowSVG": false,
"contentSecurityPolicy": "script-src 'none'; frame-src 'none'; sandbox;", "contentSecurityPolicy": "script-src 'none'; frame-src 'none'; sandbox;",
"contentDispositionType": "inline", "contentDispositionType": "inline",
......
...@@ -804,6 +804,52 @@ module.exports = { ...@@ -804,6 +804,52 @@ module.exports = {
} }
``` ```
#### `maximumRedirects`
The default image optimization loader will follow HTTP redirects when fetching remote images up to 3 times.
```js filename="next.config.js"
module.exports = {
images: {
maximumRedirects: 3,
},
}
```
You can configure the number of redirects to follow when fetching remote images. Setting the value to `0` will disable following redirects.
```js filename="next.config.js"
module.exports = {
images: {
maximumRedirects: 0,
},
}
```
#### `dangerouslyAllowLocalIP`
In rare cases when self-hosting Next.js on a private network, you may want to allow optimizing images from local IP addresses on the same network. This is not recommended for most users because it could allow malicious users to access content on your internal network.
By default, the value is false.
```js filename="next.config.js"
module.exports = {
images: {
dangerouslyAllowLocalIP: false,
},
}
```
If you need to optimize remote images hosted elsewhere in your local network, you can set the value to true.
```js filename="next.config.js"
module.exports = {
images: {
dangerouslyAllowLocalIP: true,
},
}
```
#### `dangerouslyAllowSVG` #### `dangerouslyAllowSVG`
`dangerouslyAllowSVG` allows you to serve SVG images. `dangerouslyAllowSVG` allows you to serve SVG images.
...@@ -1284,7 +1330,7 @@ export default function Home() { ...@@ -1284,7 +1330,7 @@ export default function Home() {
| Version | Changes | | Version | Changes |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `v16.0.0` | `qualities` default configuration changed to `[75]`, `preload` prop added, `priority` prop deprecated. | | `v16.0.0` | `qualities` default configuration changed to `[75]`, `preload` prop added, `priority` prop deprecated, `dangerouslyAllowLocalIP` config added, `maximumRedirects` config added. |
| `v15.3.0` | `remotePatterns` added support for array of `URL` objects. | | `v15.3.0` | `remotePatterns` added support for array of `URL` objects. |
| `v15.0.0` | `contentDispositionType` configuration default changed to `attachment`. | | `v15.0.0` | `contentDispositionType` configuration default changed to `attachment`. |
| `v14.2.23` | `qualities` configuration added. | | `v14.2.23` | `qualities` configuration added. |
......
...@@ -270,6 +270,7 @@ ...@@ -270,6 +270,7 @@
"ignore-loader": "0.1.2", "ignore-loader": "0.1.2",
"image-size": "1.2.1", "image-size": "1.2.1",
"is-docker": "2.0.0", "is-docker": "2.0.0",
"is-local-address": "2.2.2",
"is-wsl": "2.2.0", "is-wsl": "2.2.0",
"jest-worker": "27.5.1", "jest-worker": "27.5.1",
"json5": "2.2.3", "json5": "2.2.3",
......
(()=>{"use strict";var e={555:(e,f,a)=>{e.exports=e=>a(276)(e)||a(628)(e)},276:e=>{const f=["0(?:\\.\\d{1,3}){3}","10(?:\\.\\d{1,3}){3}","127(?:\\.\\d{1,3}){3}","169\\.254\\.(?:[1-9]|1?\\d\\d|2[0-4]\\d|25[0-4])\\.\\d{1,3}","172\\.(?:1[6-9]|2\\d|3[01])(?:\\.\\d{1,3}){2}","192\\.(?:0\\.0(?:\\.\\d{1,3})|0\\.2(?:\\.\\d{1,3})|168(?:\\.\\d{1,3}){2})","100\\.(?:6[4-9]|[7-9]\\d|1[01]\\d|12[0-7])(?:\\.\\d{1,3}){2}","198\\.(?:1[89](?:\\.\\d{1,3}){2}|51\\.100(?:\\.\\d{1,3}))","203\\.0\\.113(?:\\.\\d{1,3})","22[4-9](?:\\.\\d{1,3}){3}|23[0-9](?:\\.\\d{1,3}){3}","24[0-9](?:\\.\\d{1,3}){3}|25[0-5](?:\\.\\d{1,3}){3}","localhost"];const a=new RegExp(`^(${f.join("|")})$`);e.exports=a.test.bind(a);e.exports.regex=a},628:e=>{const f=[/^::f{4}:0?([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/,/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/,/^100:(:[0-9a-fA-F]{0,4}){0,6}$/,/^2001:(:[0-9a-fA-F]{0,4}){0,6}$/,/^2001:1[0-9a-fA-F]:([0-9a-fA-F]{0,4}:){0,7}[0-9a-fA-F]{0,4}$/,/^2001:2[0-9a-fA-F]?:([0-9a-fA-F]{0,4}:){0,7}[0-9a-fA-F]{0,4}$/,/^2001:db8:([0-9a-fA-F]{0,4}:){0,7}[0-9a-fA-F]{0,4}$/,/^3fff:([0-9a-fA-F]{0,4}:){0,7}[0-9a-fA-F]{0,4}$/,/^f[b-d][0-9a-fA-F]{2}:([0-9a-fA-F]{0,4}:){0,7}[0-9a-fA-F]{0,4}$/i,/^fe[8-9a-bA-B][0-9a-fA-F]:/i,/^ff([0-9a-fA-F]{2,2}):/i,/^ff00:([0-9a-fA-F]{0,4}:){0,7}[0-9a-fA-F]{0,4}$/,/^::1?$/,/^fec0:([0-9a-fA-F]{0,4}:){0,7}[0-9a-fA-F]{0,4}$/i,/^2002:([0-9a-fA-F]{0,4}:){0,7}[0-9a-fA-F]{0,4}$/];const a=new RegExp(`^(${f.map((e=>e.source)).join("|")})$`);e.exports=e=>{if(e.startsWith("[")&&e.endsWith("]")){e=e.slice(1,-1)}return a.test(e)};e.exports.regex=a}};var f={};function __nccwpck_require__(a){var r=f[a];if(r!==undefined){return r.exports}var d=f[a]={exports:{}};var t=true;try{e[a](d,d.exports,__nccwpck_require__);t=false}finally{if(t)delete f[a]}return d.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var a=__nccwpck_require__(555);module.exports=a})();
\ No newline at end of file
{"name":"is-local-address","main":"index.js","author":{"email":"josefrancisco.verdu@gmail.com","name":"Kiko Beats","url":"https://kikobeats.com"},"license":"MIT"}
...@@ -551,6 +551,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -551,6 +551,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
contentSecurityPolicy: z.string().optional(), contentSecurityPolicy: z.string().optional(),
contentDispositionType: z.enum(['inline', 'attachment']).optional(), contentDispositionType: z.enum(['inline', 'attachment']).optional(),
dangerouslyAllowSVG: z.boolean().optional(), dangerouslyAllowSVG: z.boolean().optional(),
dangerouslyAllowLocalIP: z.boolean().optional(),
deviceSizes: z deviceSizes: z
.array(z.number().int().gte(1).lte(10000)) .array(z.number().int().gte(1).lte(10000))
.max(25) .max(25)
...@@ -568,6 +569,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -568,6 +569,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
loader: z.enum(VALID_LOADERS).optional(), loader: z.enum(VALID_LOADERS).optional(),
loaderFile: z.string().optional(), loaderFile: z.string().optional(),
maximumRedirects: z.number().int().min(0).max(20).optional(),
minimumCacheTTL: z.number().int().gte(0).optional(), minimumCacheTTL: z.number().int().gte(0).optional(),
path: z.string().optional(), path: z.string().optional(),
qualities: z qualities: z
......
...@@ -6,6 +6,7 @@ import contentDisposition from 'next/dist/compiled/content-disposition' ...@@ -6,6 +6,7 @@ import contentDisposition from 'next/dist/compiled/content-disposition'
import imageSizeOf from 'next/dist/compiled/image-size' import imageSizeOf from 'next/dist/compiled/image-size'
import { detector } from 'next/dist/compiled/image-detector/detector.js' import { detector } from 'next/dist/compiled/image-detector/detector.js'
import isAnimated from 'next/dist/compiled/is-animated' import isAnimated from 'next/dist/compiled/is-animated'
import isLocalAddress from 'next/dist/compiled/is-local-address'
import { join } from 'path' import { join } from 'path'
import nodeUrl, { type UrlWithParsedQuery } from 'url' import nodeUrl, { type UrlWithParsedQuery } from 'url'
...@@ -30,6 +31,9 @@ import isError from '../lib/is-error' ...@@ -30,6 +31,9 @@ import isError from '../lib/is-error'
import { parseUrl } from '../lib/url' import { parseUrl } from '../lib/url'
import type { CacheControl } from './lib/cache-control' import type { CacheControl } from './lib/cache-control'
import { InvariantError } from '../shared/lib/invariant-error' import { InvariantError } from '../shared/lib/invariant-error'
import { lookup } from 'dns/promises'
import { isIP } from 'net'
import { ALL } from 'dns'
type XCacheHeader = 'MISS' | 'HIT' | 'STALE' type XCacheHeader = 'MISS' | 'HIT' | 'STALE'
...@@ -700,9 +704,40 @@ export async function optimizeImage({ ...@@ -700,9 +704,40 @@ export async function optimizeImage({
return optimizedBuffer return optimizedBuffer
} }
export async function fetchExternalImage(href: string): Promise<ImageUpstream> { function isRedirect(statusCode: number) {
return [301, 302, 303, 307, 308].includes(statusCode)
}
export async function fetchExternalImage(
href: string,
dangerouslyAllowLocalIP: boolean,
count = 3
): Promise<ImageUpstream> {
if (!dangerouslyAllowLocalIP) {
const { hostname } = new URL(href)
let ips = [hostname]
if (!isIP(hostname)) {
const records = await lookup(hostname, {
family: 0,
all: true,
hints: ALL,
}).catch((_) => [{ address: hostname }])
ips = records.map((record) => record.address)
}
const privateIps = ips.filter((ip) => isLocalAddress(ip))
if (privateIps.length > 0) {
Log.error(
'upstream image',
href,
'resolved to private ip',
JSON.stringify(privateIps)
)
throw new ImageError(400, '"url" parameter is not allowed')
}
}
const res = await fetch(href, { const res = await fetch(href, {
signal: AbortSignal.timeout(7_000), signal: AbortSignal.timeout(7_000),
redirect: 'manual',
}).catch((err) => err as Error) }).catch((err) => err as Error)
if (res instanceof Error) { if (res instanceof Error) {
...@@ -717,6 +752,23 @@ export async function fetchExternalImage(href: string): Promise<ImageUpstream> { ...@@ -717,6 +752,23 @@ export async function fetchExternalImage(href: string): Promise<ImageUpstream> {
throw err throw err
} }
const locationHeader = res.headers.get('Location')
if (
isRedirect(res.status) &&
locationHeader &&
URL.canParse(locationHeader, href)
) {
if (count === 0) {
Log.error('upstream image response had too many redirects', href)
throw new ImageError(
508,
'"url" parameter is valid but upstream response is invalid'
)
}
const redirect = new URL(locationHeader, href).href
return fetchExternalImage(redirect, dangerouslyAllowLocalIP, count - 1)
}
if (!res.ok) { if (!res.ok) {
Log.error('upstream image response failed for', href, res.status) Log.error('upstream image response failed for', href, res.status)
throw new ImageError( throw new ImageError(
......
...@@ -780,7 +780,11 @@ export default class NextNodeServer extends BaseServer< ...@@ -780,7 +780,11 @@ export default class NextNodeServer extends BaseServer<
const { isAbsolute, href } = paramsResult const { isAbsolute, href } = paramsResult
const imageUpstream = isAbsolute const imageUpstream = isAbsolute
? await fetchExternalImage(href) ? await fetchExternalImage(
href,
this.nextConfig.images.dangerouslyAllowLocalIP,
this.nextConfig.images.maximumRedirects
)
: await fetchInternalImage( : await fetchInternalImage(
href, href,
req.originalRequest, req.originalRequest,
......
...@@ -103,6 +103,12 @@ export type ImageConfigComplete = { ...@@ -103,6 +103,12 @@ export type ImageConfigComplete = {
/** @see [Acceptable formats](https://nextjs.org/docs/api-reference/next/image#acceptable-formats) */ /** @see [Acceptable formats](https://nextjs.org/docs/api-reference/next/image#acceptable-formats) */
formats: ImageFormat[] formats: ImageFormat[]
/** @see [Maximum Redirects](https://nextjs.org/docs/api-reference/next/image#maximumredirects) */
maximumRedirects: number
/** @see [Dangerously Allow Local IP](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-local-ip) */
dangerouslyAllowLocalIP: boolean
/** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */ /** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */
dangerouslyAllowSVG: boolean dangerouslyAllowSVG: boolean
...@@ -140,6 +146,8 @@ export const imageConfigDefault: ImageConfigComplete = { ...@@ -140,6 +146,8 @@ export const imageConfigDefault: ImageConfigComplete = {
disableStaticImages: false, disableStaticImages: false,
minimumCacheTTL: 14400, // 4 hours minimumCacheTTL: 14400, // 4 hours
formats: ['image/webp'], formats: ['image/webp'],
maximumRedirects: 3,
dangerouslyAllowLocalIP: false,
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`, contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,
contentDispositionType: 'attachment', contentDispositionType: 'attachment',
......
...@@ -1275,6 +1275,14 @@ export async function ncc_is_animated(task, opts) { ...@@ -1275,6 +1275,14 @@ export async function ncc_is_animated(task, opts) {
.target('src/compiled/is-animated') .target('src/compiled/is-animated')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['is-local-address'] = 'next/dist/compiled/is-local-address'
export async function ncc_is_local_address(task, opts) {
await task
.source(relative(__dirname, require.resolve('is-local-address')))
.ncc({ packageName: 'is-local-address', externals })
.target('src/compiled/is-local-address')
}
// eslint-disable-next-line camelcase
externals['is-docker'] = 'next/dist/compiled/is-docker' externals['is-docker'] = 'next/dist/compiled/is-docker'
export async function ncc_is_docker(task, opts) { export async function ncc_is_docker(task, opts) {
await task await task
...@@ -2349,6 +2357,7 @@ export async function ncc(task, opts) { ...@@ -2349,6 +2357,7 @@ export async function ncc(task, opts) {
'ncc_http_proxy', 'ncc_http_proxy',
'ncc_ignore_loader', 'ncc_ignore_loader',
'ncc_is_animated', 'ncc_is_animated',
'ncc_is_local_address',
'ncc_is_docker', 'ncc_is_docker',
'ncc_is_wsl', 'ncc_is_wsl',
'ncc_json5', 'ncc_json5',
......
...@@ -856,6 +856,10 @@ declare module 'next/dist/compiled/is-animated' { ...@@ -856,6 +856,10 @@ declare module 'next/dist/compiled/is-animated' {
export default function isAnimated(buffer: Buffer): boolean export default function isAnimated(buffer: Buffer): boolean
} }
declare module 'next/dist/compiled/is-local-address' {
export default function isLocalAddress(ip: string): boolean
}
declare module 'next/dist/compiled/@opentelemetry/api' { declare module 'next/dist/compiled/@opentelemetry/api' {
import * as m from '@opentelemetry/api' import * as m from '@opentelemetry/api'
export = m export = m
......
This diff is collapsed.
import { join } from 'path'
import { setupTests } from './util'
const appDir = join(__dirname, '../app')
describe('with maximumRedirects 0', () => {
setupTests({
nextConfigImages: {
dangerouslyAllowLocalIP: true,
// Configure external domains so we can try out external redirects
domains: [
'localhost',
'127.0.0.1',
'example.com',
'assets.vercel.com',
'image-optimization-test.vercel.app',
],
// Prevent redirects
maximumRedirects: 0,
},
appDir,
})
})
import { join } from 'path'
import { setupTests } from './util'
const appDir = join(__dirname, '../app')
describe('with maximumRedirects 1', () => {
setupTests({
nextConfigImages: {
dangerouslyAllowLocalIP: true,
// Configure external domains so we can try out external redirects
domains: [
'localhost',
'127.0.0.1',
'example.com',
'assets.vercel.com',
'image-optimization-test.vercel.app',
],
// Only one redirect
maximumRedirects: 1,
},
appDir,
})
})
...@@ -6,6 +6,7 @@ const appDir = join(__dirname, '../app') ...@@ -6,6 +6,7 @@ const appDir = join(__dirname, '../app')
describe('with minimumCacheTTL of 5 sec', () => { describe('with minimumCacheTTL of 5 sec', () => {
setupTests({ setupTests({
nextConfigImages: { nextConfigImages: {
dangerouslyAllowLocalIP: true,
// Configure external domains so we can try out // Configure external domains so we can try out
// variations of the upstream Cache-Control header. // variations of the upstream Cache-Control header.
domains: [ domains: [
......
...@@ -36,6 +36,7 @@ type RunTestsCtx = SetupTestsCtx & { ...@@ -36,6 +36,7 @@ type RunTestsCtx = SetupTestsCtx & {
nextOutput?: string nextOutput?: string
} }
let infiniteRedirect = 0
const largeSize = 1080 // defaults defined in server/config.ts const largeSize = 1080 // defaults defined in server/config.ts
const animatedWarnText = const animatedWarnText =
'is an animated image so it will not be optimized. Consider adding the "unoptimized" property to the <Image>.' 'is an animated image so it will not be optimized. Consider adding the "unoptimized" property to the <Image>.'
...@@ -44,15 +45,32 @@ export async function serveSlowImage() { ...@@ -44,15 +45,32 @@ export async function serveSlowImage() {
const port = await findPort() const port = await findPort()
const server = http.createServer(async (req, res) => { const server = http.createServer(async (req, res) => {
const parsedUrl = new URL(req.url, 'http://localhost') const parsedUrl = new URL(req.url, 'http://localhost')
const delay = Number(parsedUrl.searchParams.get('delay')) || 500 const delay = Number(parsedUrl.searchParams.get('delay')) || 0
const status = Number(parsedUrl.searchParams.get('status')) || 200 const status = Number(parsedUrl.searchParams.get('status')) || 200
const location = parsedUrl.searchParams.get('location')
console.log('delaying image for', delay) console.log('delaying image for', delay)
await waitFor(delay) await waitFor(delay)
res.statusCode = status res.statusCode = status
if (status === 308) { if (infiniteRedirect > 0 && infiniteRedirect < 1000) {
infiniteRedirect++
res.statusCode = 308
console.log('infinite redirect', location)
res.setHeader('location', '/')
res.end()
return
}
if (status === 301 && location) {
console.log('redirecting to location', location)
res.setHeader('location', location)
res.end()
return
}
if (status === 399) {
res.end('invalid status') res.end('invalid status')
return return
} }
...@@ -163,6 +181,8 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -163,6 +181,8 @@ export function runTests(ctx: RunTestsCtx) {
domains = [], domains = [],
formats = [], formats = [],
minimumCacheTTL = 14400, minimumCacheTTL = 14400,
maximumRedirects = 3,
dangerouslyAllowLocalIP,
} = nextConfigImages || {} } = nextConfigImages || {}
const avifEnabled = formats[0] === 'image/avif' const avifEnabled = formats[0] === 'image/avif'
let slowImageServer: Awaited<ReturnType<typeof serveSlowImage>> let slowImageServer: Awaited<ReturnType<typeof serveSlowImage>>
...@@ -173,9 +193,9 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -173,9 +193,9 @@ export function runTests(ctx: RunTestsCtx) {
slowImageServer.stop() slowImageServer.stop()
}) })
if (domains.length > 0) { if (domains.length > 0 && dangerouslyAllowLocalIP) {
it('should normalize invalid status codes', async () => { it('should normalize invalid status codes', async () => {
const url = `http://localhost:${slowImageServer.port}/slow.png?delay=${1}&status=308` const url = `http://localhost:${slowImageServer.port}/slow.png?status=399`
const query = { url, w: ctx.w, q: ctx.q } const query = { url, w: ctx.w, q: ctx.q }
const opts: RequestInit = { const opts: RequestInit = {
headers: { accept: 'image/webp' }, headers: { accept: 'image/webp' },
...@@ -194,6 +214,35 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -194,6 +214,35 @@ export function runTests(ctx: RunTestsCtx) {
}) })
} }
if (domains.length > 0) {
it('should follow redirect from http to https when maximumRedirects > 0', async () => {
const url = `http://image-optimization-test.vercel.app/frog.png`
const query = { url, w: ctx.w, q: ctx.q }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {})
expect(res.status).toBe(maximumRedirects > 0 ? 200 : 508)
})
it('should follow redirect when dangerouslyAllowLocalIP enabled', async () => {
const url = `http://localhost:${slowImageServer.port}?status=301&location=%2Fslow.png`
const query = { url, w: ctx.w, q: ctx.q }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {})
let expectedStatus = dangerouslyAllowLocalIP ? 200 : 400
if (maximumRedirects === 0) {
expectedStatus = 508
}
expect(res.status).toBe(expectedStatus)
})
it('should return 508 after redirecting too many times', async () => {
infiniteRedirect = 1
const url = `http://localhost:${slowImageServer.port}`
const query = { url, w: ctx.w, q: ctx.q }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {})
expect(res.status).toBe(508)
infiniteRedirect = 0
})
}
it('should return home page', async () => { it('should return home page', async () => {
const res = await fetchViaHTTP(ctx.appPort, '/', null, {}) const res = await fetchViaHTTP(ctx.appPort, '/', null, {})
expect(await res.text()).toMatch(/Image Optimizer Home/m) expect(await res.text()).toMatch(/Image Optimizer Home/m)
...@@ -887,7 +936,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -887,7 +936,7 @@ export function runTests(ctx: RunTestsCtx) {
}) })
} }
if (domains.length > 0) { if (domains.length > 0 && dangerouslyAllowLocalIP) {
it('should resize absolute url from localhost', async () => { it('should resize absolute url from localhost', async () => {
const url = `http://localhost:${ctx.appPort}/test.png` const url = `http://localhost:${ctx.appPort}/test.png`
const query = { url, w: ctx.w, q: ctx.q } const query = { url, w: ctx.w, q: ctx.q }
...@@ -1043,7 +1092,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -1043,7 +1092,7 @@ export function runTests(ctx: RunTestsCtx) {
} }
it('should fail when url has file protocol', async () => { it('should fail when url has file protocol', async () => {
const url = `file://localhost:${ctx.appPort}/test.png` const url = `file://example.vercel.sh:${ctx.appPort}/test.png`
const query = { url, w: ctx.w, q: ctx.q } const query = { url, w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/webp' } } const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
...@@ -1052,7 +1101,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -1052,7 +1101,7 @@ export function runTests(ctx: RunTestsCtx) {
}) })
it('should fail when url has ftp protocol', async () => { it('should fail when url has ftp protocol', async () => {
const url = `ftp://localhost:${ctx.appPort}/test.png` const url = `ftp://example.vercel.sh:${ctx.appPort}/test.png`
const query = { url, w: ctx.w, q: ctx.q } const query = { url, w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/webp' } } const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
...@@ -1068,7 +1117,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -1068,7 +1117,7 @@ export function runTests(ctx: RunTestsCtx) {
}) })
it('should fail when url is protocol relative', async () => { it('should fail when url is protocol relative', async () => {
const query = { url: `//example.com`, w: ctx.w, q: ctx.q } const query = { url: `//example.vercel.sh`, w: ctx.w, q: ctx.q }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {}) const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, {})
expect(res.status).toBe(400) expect(res.status).toBe(400)
expect(await res.text()).toBe( expect(await res.text()).toBe(
...@@ -1139,7 +1188,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -1139,7 +1188,7 @@ export function runTests(ctx: RunTestsCtx) {
) )
}) })
if (domains.length > 0) { if (domains.length > 0 && dangerouslyAllowLocalIP) {
it('should fail when url fails to load an image', async () => { it('should fail when url fails to load an image', async () => {
const url = `http://localhost:${ctx.appPort}/not-an-image` const url = `http://localhost:${ctx.appPort}/not-an-image`
const query = { w: ctx.w, url, q: ctx.q } const query = { w: ctx.w, url, q: ctx.q }
...@@ -1489,7 +1538,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -1489,7 +1538,7 @@ export function runTests(ctx: RunTestsCtx) {
expect(await res.text()).toBe("The requested resource isn't a valid image.") expect(await res.text()).toBe("The requested resource isn't a valid image.")
}) })
if (domains.length > 0) { if (domains.length > 0 && dangerouslyAllowLocalIP) {
it('should handle concurrent requests', async () => { it('should handle concurrent requests', async () => {
await cleanImagesDir(ctx.imagesDir) await cleanImagesDir(ctx.imagesDir)
const delay = 500 const delay = 500
...@@ -1614,6 +1663,7 @@ export const setupTests = (ctx: SetupTestsCtx) => { ...@@ -1614,6 +1663,7 @@ export const setupTests = (ctx: SetupTestsCtx) => {
q: 100, q: 100,
isDev, isDev,
nextConfigImages: { nextConfigImages: {
dangerouslyAllowLocalIP: true,
domains: [ domains: [
'localhost', 'localhost',
'127.0.0.1', '127.0.0.1',
...@@ -1710,6 +1760,7 @@ export const setupTests = (ctx: SetupTestsCtx) => { ...@@ -1710,6 +1760,7 @@ export const setupTests = (ctx: SetupTestsCtx) => {
q: 100, q: 100,
isDev, isDev,
nextConfigImages: { nextConfigImages: {
dangerouslyAllowLocalIP: true,
domains: [ domains: [
'localhost', 'localhost',
'127.0.0.1', '127.0.0.1',
......
...@@ -75,6 +75,7 @@ function runTests(mode: 'dev' | 'server') { ...@@ -75,6 +75,7 @@ function runTests(mode: 'dev' | 'server') {
contentDispositionType: 'attachment', contentDispositionType: 'attachment',
contentSecurityPolicy: contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;", "script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowLocalIP: false,
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false, disableStaticImages: false,
...@@ -96,6 +97,7 @@ function runTests(mode: 'dev' | 'server') { ...@@ -96,6 +97,7 @@ function runTests(mode: 'dev' | 'server') {
search: '', search: '',
}, },
], ],
maximumRedirects: 3,
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [75], qualities: [75],
......
...@@ -92,6 +92,7 @@ function runTests(mode: 'dev' | 'server') { ...@@ -92,6 +92,7 @@ function runTests(mode: 'dev' | 'server') {
contentDispositionType: 'attachment', contentDispositionType: 'attachment',
contentSecurityPolicy: contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;", "script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowLocalIP: false,
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false, disableStaticImages: false,
...@@ -108,6 +109,7 @@ function runTests(mode: 'dev' | 'server') { ...@@ -108,6 +109,7 @@ function runTests(mode: 'dev' | 'server') {
search: '', search: '',
}, },
], ],
maximumRedirects: 3,
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [42, 69, 88], qualities: [42, 69, 88],
......
...@@ -1778,6 +1778,7 @@ function runTests(mode: 'dev' | 'server') { ...@@ -1778,6 +1778,7 @@ function runTests(mode: 'dev' | 'server') {
contentDispositionType: 'attachment', contentDispositionType: 'attachment',
contentSecurityPolicy: contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;", "script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowLocalIP: false,
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false, disableStaticImages: false,
...@@ -1794,6 +1795,7 @@ function runTests(mode: 'dev' | 'server') { ...@@ -1794,6 +1795,7 @@ function runTests(mode: 'dev' | 'server') {
search: '', search: '',
}, },
], ],
maximumRedirects: 3,
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [75], qualities: [75],
......
...@@ -75,6 +75,7 @@ function runTests(mode: 'server' | 'dev') { ...@@ -75,6 +75,7 @@ function runTests(mode: 'server' | 'dev') {
contentDispositionType: 'attachment', contentDispositionType: 'attachment',
contentSecurityPolicy: contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;", "script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowLocalIP: false,
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false, disableStaticImages: false,
...@@ -101,6 +102,7 @@ function runTests(mode: 'server' | 'dev') { ...@@ -101,6 +102,7 @@ function runTests(mode: 'server' | 'dev') {
search: '', search: '',
}, },
], ],
maximumRedirects: 3,
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [75], qualities: [75],
......
...@@ -100,6 +100,7 @@ function runTests(url: string, mode: 'dev' | 'server') { ...@@ -100,6 +100,7 @@ function runTests(url: string, mode: 'dev' | 'server') {
contentDispositionType: 'attachment', contentDispositionType: 'attachment',
contentSecurityPolicy: contentSecurityPolicy:
"script-src 'none'; frame-src 'none'; sandbox;", "script-src 'none'; frame-src 'none'; sandbox;",
dangerouslyAllowLocalIP: false,
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
disableStaticImages: false, disableStaticImages: false,
...@@ -116,6 +117,7 @@ function runTests(url: string, mode: 'dev' | 'server') { ...@@ -116,6 +117,7 @@ function runTests(url: string, mode: 'dev' | 'server') {
search: '', search: '',
}, },
], ],
maximumRedirects: 3,
minimumCacheTTL: 14400, minimumCacheTTL: 14400,
path: '/_next/image', path: '/_next/image',
qualities: [75], qualities: [75],
......
...@@ -138,6 +138,7 @@ const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18 ...@@ -138,6 +138,7 @@ const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
"/node_modules/next/dist/compiled/image-detector/detector.js", "/node_modules/next/dist/compiled/image-detector/detector.js",
"/node_modules/next/dist/compiled/image-size/index.js", "/node_modules/next/dist/compiled/image-size/index.js",
"/node_modules/next/dist/compiled/is-animated/index.js", "/node_modules/next/dist/compiled/is-animated/index.js",
"/node_modules/next/dist/compiled/is-local-address/index.js",
"/node_modules/next/dist/compiled/jsonwebtoken/index.js", "/node_modules/next/dist/compiled/jsonwebtoken/index.js",
"/node_modules/next/dist/compiled/nanoid/index.cjs", "/node_modules/next/dist/compiled/nanoid/index.cjs",
"/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js", "/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js",
......
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