Public brand image fetch: the site's configured origin only, no redirect followed, a time and a byte limit

/api/ipal/admin-og resolved a relative logo address against the request's own host and fetched it with
Node's defaults (redirects followed, no timeout, no size cap); /api/ipal/admin-icon resolved the same way.
Both now resolve against serverURL / NEXT_PUBLIC_SERVER_URL (never the request) and fetch through
fetchPublicImage, which asks one address with redirect: 'manual' (a 3xx is no image), within
PUBLIC_IMAGE_TIMEOUT_MS, reading at most 512 KB. The renderer still draws PNG, JPEG, GIF (by their bytes)
and SVG (by its type, as before). Tests against local servers: hostile Host / X-Forwarded-Host, a 302 to an
internal host, an endless body, a hanging server, the normal logo. Docs say 1.17.1 instead of 1.18.0.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 22:03:52 +01:00
co-authored by Claude Fable 5.2
parent 562bf5388d
commit aef1efac73
13 changed files with 244 additions and 29 deletions
+7 -2
View File
@@ -137,7 +137,7 @@ describe('plugin wiring', () => {
describe('preview image endpoints', () => {
const req = (settings: Record<string, unknown>) =>
({ payload: { config: { localization: false }, findGlobal: vi.fn(async () => settings) }, url: 'http://localhost:3000/api/ipal/admin-og' }) as unknown as PayloadRequest
({ payload: { config: { localization: false, serverURL: 'http://localhost:3000' }, findGlobal: vi.fn(async () => settings) }, url: 'http://localhost:3000/api/ipal/admin-og' }) as unknown as PayloadRequest
const [og, icon] = buildAdminImageEndpoints(buildAdminMeta({ agency: DEFAULT_AGENCY }).resolved) as [Endpoint, Endpoint]
test('renders a PNG from the site name when there is no logo', async () => {
@@ -153,14 +153,19 @@ describe('preview image endpoints', () => {
try {
const res = (await og.handler(req({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Acme' })))
expect(res.headers.get('content-type')).toBe('image/png')
expect(fetchMock).toHaveBeenCalledWith('http://localhost:3000/api/media/file/logo.png')
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/media/file/logo.png')
expect((fetchMock.mock.calls[0][1] as RequestInit).redirect).toBe('manual')
} finally {
fetchMock.mockRestore()
}
}, 30_000)
test('icon redirects to the site favicon, else draws initials', async () => {
// the favicon cannot be fetched here (nothing is asked of a real server in this test): the redirect
const fetchMock = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('ECONNREFUSED'))
const redirect = (await icon.handler(req({ favicon: { url: '/api/media/file/icon.png' }, siteName: 'Acme' })))
fetchMock.mockRestore()
expect(redirect.status).toBe(302)
expect(redirect.headers.get('location')).toBe('http://localhost:3000/api/media/file/icon.png')
const drawn = (await icon.handler(req({ siteName: 'Acme Studio' })))
+159
View File
@@ -0,0 +1,159 @@
import type { Endpoint, PayloadRequest } from 'payload'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildAdminImageEndpoints } from '../src/modules/branding/adminImages.js'
import { buildAdminMeta, DEFAULT_AGENCY } from '../src/modules/branding/adminMeta.js'
import { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, PUBLIC_IMAGE_TIMEOUT_MS } from '../src/modules/branding/publicImage.js'
/**
* The server-side fetch of a brand image (the public endpoints `/api/ipal/admin-og` and `/api/ipal/admin-icon`,
* the logo and icon on the 2FA screens) against REAL local servers: the site's own, one standing for an
* internal address, and one standing for a host an attacker names in the request.
* The fetch may reach the site's configured origin only, once, without following a redirect, for a bounded
* time and a bounded number of bytes.
*/
// 1×1 transparent PNG
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64')
type Started = { hits: string[]; origin: string; server: Server }
const start = (handler: (req: IncomingMessage, res: ServerResponse) => void): Promise<Started> =>
new Promise((resolve) => {
const hits: string[] = []
const server = createServer((req, res) => {
hits.push(req.url ?? '')
handler(req, res)
})
server.listen(0, '127.0.0.1', () => {
const address = server.address() as { port: number }
resolve({ hits, origin: `http://127.0.0.1:${address.port}`, server })
})
})
let site: Started
let internal: Started
let attacker: Started
/** Bytes the endless answer has written, and whether its connection was closed by the reader. */
const endless = { closed: false, sent: 0 }
beforeAll(async () => {
const png = (_req: IncomingMessage, res: ServerResponse) => res.writeHead(200, { 'content-type': 'image/png' }).end(PNG)
internal = await start(png) // stands for 169.254.169.254 or any host only the server can reach
attacker = await start(png)
site = await start((req, res) => {
if (req.url === '/api/media/file/logo.png') {return png(req, res)}
if (req.url === '/to-internal') {return res.writeHead(302, { location: `${internal.origin}/latest/meta-data/` }).end()}
if (req.url === '/to-metadata') {return res.writeHead(302, { location: 'http://169.254.169.254/latest/meta-data/' }).end()}
if (req.url === '/endless') {
res.writeHead(200, { 'content-type': 'image/png' }) // no content-length: only reading can find the size
const chunk = Buffer.alloc(64 * 1024, 1)
const timer = setInterval(() => {
endless.sent += chunk.length
res.write(chunk)
}, 2)
res.on('close', () => {
endless.closed = true
clearInterval(timer)
})
return
}
if (req.url === '/hang') {return} // never answers
res.writeHead(404).end()
})
})
afterAll(async () => {
for (const s of [site, internal, attacker]) {
s.server.closeAllConnections()
await new Promise((resolve) => s.server.close(resolve))
}
})
afterEach(() => {
vi.unstubAllEnvs()
for (const s of [site, internal, attacker]) {s.hits.length = 0}
})
describe('fetchPublicImage against a real server', () => {
test('the picture is fetched', async () => {
const image = await fetchPublicImage('/api/media/file/logo.png', site.origin)
expect(image?.type).toBe('image/png')
expect(image?.bytes.equals(PNG)).toBe(true)
})
test('a 302 to an internal host is not followed: no image, and the internal host is never asked', async () => {
expect(await fetchPublicImage('/to-internal', site.origin)).toBeNull()
expect(await fetchPublicImage('/to-metadata', site.origin)).toBeNull() // 169.254.169.254: answered at once, no connection attempt
expect(site.hits).toEqual(['/to-internal', '/to-metadata'])
expect(internal.hits).toEqual([])
})
test('an endless body stops at the cap: no image, the connection is dropped, little more than the cap was read', async () => {
expect(await fetchPublicImage('/endless', site.origin)).toBeNull()
await vi.waitFor(() => expect(endless.closed).toBe(true), { timeout: 3000 })
expect(endless.sent).toBeGreaterThan(PUBLIC_IMAGE_MAX_BYTES)
expect(endless.sent).toBeLessThan(PUBLIC_IMAGE_MAX_BYTES * 8) // some more is in flight when reading stops
})
test('a server that never answers is given up on within the timeout', async () => {
expect(PUBLIC_IMAGE_TIMEOUT_MS).toBe(5000)
const started = Date.now()
expect(await fetchPublicImage('/hang', site.origin, { timeoutMs: 400 })).toBeNull()
expect(Date.now() - started).toBeLessThan(2000)
})
})
describe('the public preview-image and icon endpoints', () => {
const [og, icon] = buildAdminImageEndpoints(buildAdminMeta({ agency: DEFAULT_AGENCY }).resolved) as [Endpoint, Endpoint]
/** A request as an attacker sends it: its own host in the URL and in the forwarding headers. */
const hostile = (settings: Record<string, unknown>, serverURL: string | undefined, path: string) =>
({
headers: new Headers({ host: new URL(attacker.origin).host, 'x-forwarded-host': new URL(attacker.origin).host, 'x-forwarded-proto': 'http' }),
payload: { config: { localization: false, ...(serverURL ? { serverURL } : {}) }, findGlobal: () => Promise.resolve(settings) },
url: `${attacker.origin}${path}`,
}) as unknown as PayloadRequest
const logo = { logo: { url: '/api/media/file/logo.png' }, siteName: 'Acme' }
const favicon = { favicon: { url: '/api/media/file/logo.png' }, siteName: 'Acme' }
test('the normal logo still renders: one request, to the site\'s configured origin', async () => {
const res = await og.handler(hostile(logo, site.origin, '/api/ipal/admin-og'))
expect(res.headers.get('content-type')).toBe('image/png')
expect((await res.arrayBuffer()).byteLength).toBeGreaterThan(1000)
expect(site.hits).toEqual(['/api/media/file/logo.png'])
expect(attacker.hits).toEqual([])
}, 30_000)
test('a hostile Host / X-Forwarded-Host makes no fetch to that host — also when the site has no configured origin', async () => {
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', '')
const preview = await og.handler(hostile(logo, undefined, '/api/ipal/admin-og'))
expect(preview.headers.get('content-type')).toBe('image/png') // the site's name is drawn instead
const tab = await icon.handler(hostile(favicon, undefined, '/api/ipal/admin-icon'))
expect(tab.status).toBe(302)
expect(tab.headers.get('location')).toBe('/api/media/file/logo.png') // as stored: the browser resolves it, not the request's host
expect(attacker.hits).toEqual([])
expect(site.hits).toEqual([])
const served = await icon.handler(hostile(favicon, site.origin, '/api/ipal/admin-icon'))
expect(served.status).toBe(200)
expect(served.headers.get('content-type')).toBe('image/png')
expect(site.hits).toEqual(['/api/media/file/logo.png'])
expect(attacker.hits).toEqual([])
}, 30_000)
test('a logo address that redirects to an internal host: not followed, the name is drawn, the icon redirects the browser', async () => {
const preview = await og.handler(hostile({ logo: { url: '/to-internal' }, siteName: 'Acme' }, site.origin, '/api/ipal/admin-og'))
expect(preview.headers.get('content-type')).toBe('image/png')
const tab = await icon.handler(hostile({ favicon: { url: '/to-internal' }, siteName: 'Acme' }, site.origin, '/api/ipal/admin-icon'))
expect(tab.status).toBe(302)
expect(tab.headers.get('location')).toBe(`${site.origin}/to-internal`)
expect(internal.hits).toEqual([])
expect(attacker.hits).toEqual([])
}, 30_000)
test('an endless logo does not hold the endpoint: the name is drawn', async () => {
const res = await og.handler(hostile({ logo: { url: '/endless' }, siteName: 'Acme' }, site.origin, '/api/ipal/admin-og'))
expect(res.headers.get('content-type')).toBe('image/png')
}, 30_000)
})
+2 -2
View File
@@ -58,7 +58,7 @@ describe('the brand image for a session the browser cannot load it in', () => {
vi.stubGlobal('fetch', fetchMock)
const icon = buildAdminImageEndpoints({ agency: false, language: 'en' } as never).find((e) => e.path.endsWith('admin-icon'))!
const req = {
payload: { config: {}, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.png' }, siteName: 'Example' }) },
payload: { config: { serverURL: 'https://example.com' }, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.png' }, siteName: 'Example' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true },
}
@@ -79,7 +79,7 @@ describe('the tab icon endpoint and an SVG', () => {
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"><script>document.title="XSS"</script></svg>'
const icon = (fields: Record<string, unknown> = {}) => buildAdminImageEndpoints({ agency: false, language: 'en' } as never, fields as never).find((e) => e.path.endsWith('admin-icon'))!
const req = {
payload: { config: {}, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.svg' }, siteName: 'Example' }) },
payload: { config: { serverURL: 'https://example.com' }, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.svg' }, siteName: 'Example' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: null,
}