Files
ipal-kit/test/publicImage.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 75a6f5209e 2FA setup required: review fixes (SR-1 to SR-9)
SR-1: /api/ipal/admin-icon sends the upload security headers (sandbox policy,
nosniff) with the bytes: an SVG is shown, never run. fetchPublicImage stops
reading at the size limit.
SR-2: requireSetup.exempt exempts only on exactly true; an async function, and a
windowHours that is not a number or false, stop the start.
SR-3: on Postgres / SQLite the missing column makes every login fail: the log
says so, the docs call the migration a required step of the same deploy, and
ipal-doctor reports a SQL project without it.
SR-4: an admin's reset also ends the account's sessions.
SR-5: the reset needs a session that entered its own TOTP code by default.
SR-6: the doctor's import-map rule covers TwoFactorStatusField and TwoFactorAlert.
SR-7: building blocks exported; dashboard notice, status field, setup notice and
the server-side image fetch can be switched off one by one.
SR-8: totpSetupFrom is on the 2FA collection whenever 2FA is on.
SR-9: both ways out of "every administrator is blocked" in security.md.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 19:32:34 +01:00

149 lines
8.4 KiB
TypeScript

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('<html>', { 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: {}, 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 = '<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' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: null,
}
test.each([
['an SVG', SVG, 'image/svg+xml'],
['a PNG', png, 'image/png'],
])('%s is served with the sandbox policy and nosniff', 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(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('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(SVG, { headers: { 'content-type': 'image/svg+xml' }, 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<Uint8Array>({ 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<Uint8Array>({
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()
})
})