/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]>
160 lines
7.9 KiB
TypeScript
160 lines
7.9 KiB
TypeScript
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)
|
||
})
|