import { afterEach, describe, expect, test, vi } from 'vitest' import { AdminLogo } from '../src/modules/branding/adminGraphics.js' import { buildAdminImageEndpoints } from '../src/modules/branding/adminImages.js' import { fetchPublicImage, publicImageDataUri } from '../src/modules/branding/publicImage.js' const png = Buffer.from('89504e470d0a1a0a', 'hex') const respond = (body: BodyInit | null, init: ResponseInit) => vi.fn(async () => new Response(body, init)) afterEach(() => { vi.unstubAllGlobals() }) describe('the brand image for a session the browser cannot load it in', () => { test('fetched without credentials; only an image of a sane size comes back', async () => { const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 }) vi.stubGlobal('fetch', fetchMock) const image = await fetchPublicImage('/api/media/file/logo.png', 'https://example.com') expect(image?.type).toBe('image/png') const [url, init] = fetchMock.mock.calls[0] as unknown as [URL, RequestInit] expect(String(url)).toBe('https://example.com/api/media/file/logo.png') expect(init.credentials).toBe('omit') expect(init.headers).toBeUndefined() // no cookie, no authorization expect(await publicImageDataUri('/api/media/file/logo.png', 'https://example.com')).toMatch(/^data:image\/png;base64,/) }) test.each([ ['media is not public (403)', respond('no', { status: 403 })], ['not an image', respond('', { headers: { 'content-type': 'text/html' }, status: 200 })], ['too large', respond(Buffer.alloc(600 * 1024), { headers: { 'content-type': 'image/png' }, status: 200 })], ])('%s → nothing', async (_, fetchMock) => { vi.stubGlobal('fetch', fetchMock) expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull() }) test('no origin for a relative address, or another scheme → nothing, and no request', async () => { const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 }) vi.stubGlobal('fetch', fetchMock) expect(await fetchPublicImage('/x.png', null)).toBeNull() expect(await fetchPublicImage('file:///etc/passwd', null)).toBeNull() expect(fetchMock).not.toHaveBeenCalled() }) test('the panel logo: a data address for a session that owes its code, the plain address otherwise', async () => { vi.stubGlobal('fetch', respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })) const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } }, serverURL: 'https://example.com' }, findGlobal: async () => ({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Example' }), } const src = async (user: unknown) => ((await AdminLogo({ payload: payload as never, user: user as never })) as { props: { src?: string } }).props.src expect(await src({ _strategy: 'local-jwt', collection: 'users', hasTotp: true })).toMatch(/^data:image\/png;base64,/) expect(await src({ _strategy: 'totp', collection: 'users', hasTotp: true })).toBe('/api/media/file/logo.png') expect(await src(null)).toBe('/api/media/file/logo.png') // the login screen: an anonymous visitor loads it as before }) test('the tab icon endpoint serves the picture itself, so no session is sent to a file it is refused', async () => { const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 }) vi.stubGlobal('fetch', fetchMock) const icon = buildAdminImageEndpoints({ agency: false, language: 'en' } as never).find((e) => e.path.endsWith('admin-icon'))! const req = { 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 }, } const res = await icon.handler(req as never) expect(res.status).toBe(200) expect(res.headers.get('content-type')).toBe('image/png') expect(res.headers.get('location')).toBeNull() expect(String((fetchMock.mock.calls[0] as unknown as [URL])[0])).toBe('https://example.com/api/media/file/icon.png') // not fetchable → the redirect, as before vi.stubGlobal('fetch', respond('no', { status: 403 })) expect((await icon.handler(req as never)).status).toBe(302) }) }) // An uploaded SVG from the site's own origin can run script when opened directly. The upload routes send a sandbox // policy for that; the icon endpoint serves the same bytes and must send the same headers. describe('the tab icon endpoint and an SVG', () => { const SVG = '' const icon = (fields: Record = {}) => buildAdminImageEndpoints({ agency: false, language: 'en' } as never, fields as never).find((e) => e.path.endsWith('admin-icon'))! const req = { 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, } // A Next project's site-wide CSP rule overrides a route's own header, so the sandbox header alone protects // nothing in a real site: the endpoint must not answer with an SVG at all. test.each([ ['an SVG', SVG, 'image/svg+xml'], ['an SVG that the media server calls a PNG', SVG, 'image/png'], ['an SVG with a byte-order mark and an XML header', `\ufeff${SVG}`, 'image/svg+xml'], ['HTML that claims to be an image', '', 'image/gif'], ])('%s is never answered from here: a redirect to the media file instead', async (_name, body, type) => { vi.stubGlobal('fetch', respond(body, { headers: { 'content-type': type }, status: 200 })) const res = await icon().handler(req as never) expect(res.status).toBe(302) expect(res.headers.get('location')).toBe('https://example.com/api/media/file/icon.svg') expect(res.headers.get('content-type') ?? '').not.toContain('svg') expect(await res.text()).toBe('') }) test.each([ ['PNG', Buffer.from('89504e470d0a1a0a0000', 'hex'), 'image/png'], ['JPEG', Buffer.from('ffd8ffe000104a46', 'hex'), 'image/jpeg'], ['GIF', Buffer.from('GIF89a..'), 'image/gif'], ['WebP', Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBPVP8 ')]), 'image/webp'], ['ICO', Buffer.from('000001000100', 'hex'), 'image/x-icon'], ['AVIF', Buffer.concat([Buffer.alloc(4), Buffer.from('ftypavif')]), 'image/avif'], ])('a %s is served, typed by its own bytes, with the sandbox policy and nosniff', async (_name, body, type) => { // the media server's claim is ignored — here it even claims SVG vi.stubGlobal('fetch', respond(body, { headers: { 'content-type': 'image/svg+xml' }, status: 200 })) const res = await icon().handler(req as never) expect(res.status).toBe(200) expect(res.headers.get('content-type')).toBe(type) expect(res.headers.get('content-security-policy')).toBe("default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox") expect(res.headers.get('x-content-type-options')).toBe('nosniff') }) test('rasterImageType knows bitmaps only', async () => { const { rasterImageType } = await import('../src/modules/branding/publicImage.js') expect(rasterImageType(Buffer.from(SVG))).toBeNull() expect(rasterImageType(Buffer.from(''))).toBeNull() expect(rasterImageType(Buffer.from('%PDF-1.7'))).toBeNull() expect(rasterImageType(png)).toBe('image/png') }) test('buildUploadSecurityHeaders also covers the icon path (a second layer; the project lists it after the site-wide rule)', async () => { const { buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } = await import('../src/modules/security/buildSecurityHeaders.js') expect(buildUploadSecurityHeaders().map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/ipal/admin-icon']) expect(buildUploadSecurityHeaders()[1].headers).toEqual([...UPLOAD_SECURITY_HEADERS]) expect(buildUploadSecurityHeaders({ adminIcon: '/cms/ipal/admin-icon', collections: ['media', 'files'] }).map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/files/file/:path*', '/cms/ipal/admin-icon']) expect(buildUploadSecurityHeaders({ adminIcon: false }).map((r) => r.source)).toEqual(['/api/media/file/:path*']) }) test('the headers are the ones of the upload routes', async () => { const { buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } = await import('../src/modules/security/buildSecurityHeaders.js') expect(buildUploadSecurityHeaders()[0].headers).toEqual([...UPLOAD_SECURITY_HEADERS]) expect(UPLOAD_SECURITY_HEADERS.find((h) => h.key === 'Content-Security-Policy')?.value).toContain('sandbox') }) test('adminMeta.serveIcon: false → the redirect to the media file, no fetch', async () => { const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 }) vi.stubGlobal('fetch', fetchMock) const res = await icon({ serveIcon: false }).handler(req as never) expect(res.status).toBe(302) expect(res.headers.get('location')).toBe('https://example.com/api/media/file/icon.svg') expect(fetchMock).not.toHaveBeenCalled() }) }) describe('an image that is too large is not read to the end', () => { test('a declared length over the limit: the body is not read', async () => { const cancel = vi.fn(async () => undefined) const body = new ReadableStream({ cancel, pull: (c) => c.enqueue(new Uint8Array(1024)) }) vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { headers: { 'content-length': String(10 * 1024 * 1024), 'content-type': 'image/png' }, status: 200 }))) expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull() expect(cancel).toHaveBeenCalled() }) test('no declared length: reading stops at the limit', async () => { let sent = 0 const body = new ReadableStream({ pull: (c) => { sent += 64 * 1024 c.enqueue(new Uint8Array(64 * 1024)) // endless }, }) vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { headers: { 'content-type': 'image/png' }, status: 200 }))) expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull() expect(sent).toBeLessThan(2 * 1024 * 1024) // stopped soon after 512 KB, not after "everything" }) test('whiteLabel.inlineImages: false → the logo keeps its address, nothing is fetched', async () => { const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 }) vi.stubGlobal('fetch', fetchMock) const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } }, serverURL: 'https://example.com' }, findGlobal: async () => ({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Example' }), } const out = (await AdminLogo({ inlineImages: false, payload: payload as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } as never })) as { props: { src?: string } } expect(out.props.src).toBe('/api/media/file/logo.png') expect(fetchMock).not.toHaveBeenCalled() }) })