Unverified Commit 0a04ab74 authored by Steven's avatar Steven Committed by GitHub

Fix leaking internal config to user-defined `loader` prop in `next/image` (#36013)

The `config` was changed from a global variable to a function parameter of the `loader()` function in PR https://github.com/vercel/next.js/pull/33559 as an implementation detail, not as a public API. It was not meant to be used by the end user which is why it was [undocumented](https://nextjs.org/docs/api-reference/next/image#loader).

This config is meant for the default Image Optimization API. Since the `loader` prop bypasses the default Image Optimization API in favor of a custom function, that config is no longer be relevant because the function can implement the optimization url however it desires.

- Fixes #35115
parent a0924fc7
...@@ -40,13 +40,25 @@ type ImageConfig = ImageConfigComplete & { allSizes: number[] } ...@@ -40,13 +40,25 @@ type ImageConfig = ImageConfigComplete & { allSizes: number[] }
export type ImageLoader = (resolverProps: ImageLoaderProps) => string export type ImageLoader = (resolverProps: ImageLoaderProps) => string
export type ImageLoaderProps = { export type ImageLoaderProps = {
config: Readonly<ImageConfig>
src: string src: string
width: number width: number
quality?: number quality?: number
} }
const loaders = new Map<LoaderValue, (props: ImageLoaderProps) => string>([ // Do not export - this is an internal type only
// because `next.config.js` is only meant for the
// built-in loaders, not for a custom loader() prop.
type ImageLoaderWithConfig = (
resolverProps: ImageLoaderPropsWithConfig
) => string
type ImageLoaderPropsWithConfig = ImageLoaderProps & {
config: Readonly<ImageConfig>
}
const loaders = new Map<
LoaderValue,
(props: ImageLoaderPropsWithConfig) => string
>([
['default', defaultLoader], ['default', defaultLoader],
['imgix', imgixLoader], ['imgix', imgixLoader],
['cloudinary', cloudinaryLoader], ['cloudinary', cloudinaryLoader],
...@@ -132,7 +144,7 @@ export type ImageProps = Omit< ...@@ -132,7 +144,7 @@ export type ImageProps = Omit<
onLoadingComplete?: OnLoadingComplete onLoadingComplete?: OnLoadingComplete
} }
type ImageElementProps = Omit<ImageProps, 'src'> & { type ImageElementProps = Omit<ImageProps, 'src' | 'loader'> & {
srcString: string srcString: string
imgAttributes: GenImgAttrsResult imgAttributes: GenImgAttrsResult
heightInt: number | undefined heightInt: number | undefined
...@@ -145,7 +157,7 @@ type ImageElementProps = Omit<ImageProps, 'src'> & { ...@@ -145,7 +157,7 @@ type ImageElementProps = Omit<ImageProps, 'src'> & {
loading: LoadingValue loading: LoadingValue
config: ImageConfig config: ImageConfig
unoptimized: boolean unoptimized: boolean
loader: ImageLoader loader: ImageLoaderWithConfig
placeholder: PlaceholderValue placeholder: PlaceholderValue
onLoadingCompleteRef: React.MutableRefObject<OnLoadingComplete | undefined> onLoadingCompleteRef: React.MutableRefObject<OnLoadingComplete | undefined>
setBlurComplete: (b: boolean) => void setBlurComplete: (b: boolean) => void
...@@ -209,7 +221,7 @@ type GenImgAttrsData = { ...@@ -209,7 +221,7 @@ type GenImgAttrsData = {
src: string src: string
unoptimized: boolean unoptimized: boolean
layout: LayoutValue layout: LayoutValue
loader: ImageLoader loader: ImageLoaderWithConfig
width?: number width?: number
quality?: number quality?: number
sizes?: string sizes?: string
...@@ -269,7 +281,7 @@ function getInt(x: unknown): number | undefined { ...@@ -269,7 +281,7 @@ function getInt(x: unknown): number | undefined {
return undefined return undefined
} }
function defaultImageLoader(loaderProps: ImageLoaderProps) { function defaultImageLoader(loaderProps: ImageLoaderPropsWithConfig) {
const loaderKey = loaderProps.config?.loader || 'default' const loaderKey = loaderProps.config?.loader || 'default'
const load = loaders.get(loaderKey) const load = loaders.get(loaderKey)
if (load) { if (load) {
...@@ -357,7 +369,6 @@ export default function Image({ ...@@ -357,7 +369,6 @@ export default function Image({
objectPosition, objectPosition,
onLoadingComplete, onLoadingComplete,
onError, onError,
loader = defaultImageLoader,
placeholder = 'empty', placeholder = 'empty',
blurDataURL, blurDataURL,
...all ...all
...@@ -376,8 +387,23 @@ export default function Image({ ...@@ -376,8 +387,23 @@ export default function Image({
// Override default layout if the user specified one: // Override default layout if the user specified one:
if (rest.layout) layout = rest.layout if (rest.layout) layout = rest.layout
// Remove property so it's not spread into image: // Remove property so it's not spread on <img>:
delete rest['layout'] delete rest.layout
}
let loader: ImageLoaderWithConfig = defaultImageLoader
if ('loader' in rest) {
if (rest.loader) {
const customImageLoader = rest.loader
loader = (obj) => {
const { config: _, ...opts } = obj
// The config object is internal only so we must
// not pass it to the user-defined loader()
return customImageLoader(opts)
}
}
// Remove property so it's not spread on <img>
delete rest.loader
} }
let staticSrc = '' let staticSrc = ''
...@@ -957,7 +983,7 @@ function imgixLoader({ ...@@ -957,7 +983,7 @@ function imgixLoader({
src, src,
width, width,
quality, quality,
}: ImageLoaderProps): string { }: ImageLoaderPropsWithConfig): string {
// Demo: https://static.imgix.net/daisy.png?auto=format&fit=max&w=300 // Demo: https://static.imgix.net/daisy.png?auto=format&fit=max&w=300
const url = new URL(`${config.path}${normalizeSrc(src)}`) const url = new URL(`${config.path}${normalizeSrc(src)}`)
const params = url.searchParams const params = url.searchParams
...@@ -973,7 +999,11 @@ function imgixLoader({ ...@@ -973,7 +999,11 @@ function imgixLoader({
return url.href return url.href
} }
function akamaiLoader({ config, src, width }: ImageLoaderProps): string { function akamaiLoader({
config,
src,
width,
}: ImageLoaderPropsWithConfig): string {
return `${config.path}${normalizeSrc(src)}?imwidth=${width}` return `${config.path}${normalizeSrc(src)}?imwidth=${width}`
} }
...@@ -982,7 +1012,7 @@ function cloudinaryLoader({ ...@@ -982,7 +1012,7 @@ function cloudinaryLoader({
src, src,
width, width,
quality, quality,
}: ImageLoaderProps): string { }: ImageLoaderPropsWithConfig): string {
// Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg // Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg
const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')] const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')]
const paramsString = params.join(',') + '/' const paramsString = params.join(',') + '/'
...@@ -1001,7 +1031,7 @@ function defaultLoader({ ...@@ -1001,7 +1031,7 @@ function defaultLoader({
src, src,
width, width,
quality, quality,
}: ImageLoaderProps): string { }: ImageLoaderPropsWithConfig): string {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const missingValues = [] const missingValues = []
......
import Image from 'next/image'
const LoaderExample = () => {
return (
<div>
<p>Custom loader in both next.config.js and loader prop</p>
<Image
id="loader-prop-img"
src="foo.jpg"
width={300}
height={400}
loader={({ config, src, width }) => {
if (config) {
return 'https://example.vercel.sh/error-unexpected-config'
}
return `https://example.vercel.sh/success/${src}?width=${width}`
}}
/>
</div>
)
}
export default LoaderExample
...@@ -317,6 +317,17 @@ describe('Image Component Tests', () => { ...@@ -317,6 +317,17 @@ describe('Image Component Tests', () => {
await browser.elementById('basic-image').getAttribute('data-nimg') await browser.elementById('basic-image').getAttribute('data-nimg')
).toBe('intrinsic') ).toBe('intrinsic')
}) })
it('should not pass config to custom loader prop', async () => {
browser = await webdriver(appPort, '/loader-prop')
expect(
await browser.elementById('loader-prop-img').getAttribute('src')
).toBe('https://example.vercel.sh/success/foo.jpg?width=1024')
expect(
await browser.elementById('loader-prop-img').getAttribute('srcset')
).toBe(
'https://example.vercel.sh/success/foo.jpg?width=480 1x, https://example.vercel.sh/success/foo.jpg?width=1024 2x'
)
})
}) })
describe('Client-side Image Component Tests', () => { describe('Client-side Image Component Tests', () => {
beforeAll(async () => { beforeAll(async () => {
......
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