2FA setup required: review round 2 — no SVG from the icon endpoint, migrations at container start

R2-1: /api/ipal/admin-icon answers with bytes only for a bitmap recognised by its
first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF). An SVG favicon keeps the redirect
to the media file: a site-wide CSP rule overrides a route's own sandbox header,
so the header alone protected nothing in a built site. buildUploadSecurityHeaders
also returns a rule for the icon path, as a second layer.
R2-2: the SQL migration runs when the new container starts (prodMigrations, or
the start command), never in Coolify's pre-deployment command; docs and the log
line say so and point to deployment.md 4.3.
R2-3: requireSetup: null is the default. R2-4: the missing-column log line only
for a column error. R2-5, R2-6: the resetAccess example keeps the code check;
with guard: false the reset endpoint does not exist.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 20:18:47 +01:00
co-authored by Claude Fable 5.2
parent 75a6f5209e
commit 01e3813723
20 changed files with 155 additions and 53 deletions
+40 -3
View File
@@ -84,18 +84,55 @@ describe('the tab icon endpoint and an SVG', () => {
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'],
['a PNG', png, 'image/png'],
])('%s is served with the sandbox policy and nosniff', async (_name, body, type) => {
['an SVG that the media server calls a PNG', SVG, 'image/png'],
['an SVG with a byte-order mark and an XML header', `\ufeff<?xml version="1.0"?>${SVG}`, 'image/svg+xml'],
['HTML that claims to be an image', '<html><script>1</script></html>', '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])
@@ -103,7 +140,7 @@ describe('the tab icon endpoint and an SVG', () => {
})
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 })
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)
+14 -4
View File
@@ -414,6 +414,13 @@ describe('ipalKit and the 2FA plugin', () => {
expect(() => resolveRequireSetup({ windowHours: windowHours as never })).toThrow(/windowHours/)
})
test('requireSetup: null is the default, like leaving it out', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: null as never } })({ collections: [], secret: 'x' } as unknown as Config)
expect((config.custom as { ipal: { twoFactor: Record<string, unknown> } }).ipal.twoFactor).toMatchObject({ requireSetup: true, setupWindowMs: 72 * 3_600_000 })
expect(JSON.stringify(config.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert')
expect(resolveRequireSetup(null as never)).toEqual({ requireSetup: true, setupWindowMs: 72 * 3_600_000 })
})
test('windowHours: a number, 0 or false still work', () => {
expect(resolveRequireSetup({ windowHours: 1.5 }).setupWindowMs).toBe(1.5 * 3_600_000)
expect(resolveRequireSetup({ windowHours: 0 }).setupWindowMs).toBe(0)
@@ -483,10 +490,13 @@ describe('ipalKit and the 2FA plugin', () => {
const sqlite = fake('sqlite', 'no such column: totp_setup_from')
await backfillSetupFrom(sqlite.payload as never, 'users')
expect(sqlite.logger.error).toHaveBeenCalledTimes(1)
const mongo = fake('mongoose', 'connection lost')
await backfillSetupFrom(mongo.payload as never, 'users')
expect(mongo.logger.error).not.toHaveBeenCalled()
expect(mongo.logger.warn).toHaveBeenCalledTimes(1)
// any other failure — also on a SQL adapter — is not "the column is missing"
for (const other of [fake('mongoose', 'connection lost'), fake('postgres', 'connect ECONNREFUSED 127.0.0.1:5432'), fake('sqlite', 'database is locked'), fake('postgres', 'relation "users" does not exist')]) {
await backfillSetupFrom(other.payload as never, 'users')
expect(other.logger.error).not.toHaveBeenCalled()
expect(other.logger.warn).toHaveBeenCalledTimes(1)
}
expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/prodMigrations.*not in a pre-deployment command/s)
})
// The reset removes a second factor: by default only a session that entered its own TOTP code may do it.
+2 -1
View File
@@ -232,7 +232,8 @@ describe('buildUploadSecurityHeaders', () => {
test('sandboxes files served from upload routes', async () => {
const { buildUploadSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js')
const rules = buildUploadSecurityHeaders({ collections: ['media', 'documents'] })
expect(rules.map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/documents/file/:path*'])
// the upload routes, and the panel icon endpoint (it answers with a file's bytes too)
expect(rules.map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/documents/file/:path*', '/api/ipal/admin-icon'])
const csp = rules[0].headers.find((h) => h.key === 'Content-Security-Policy')?.value ?? ''
expect(csp).toContain('sandbox')
expect(csp).toContain("default-src 'none'")