Better error handling, and handling of numeric config options

This commit is contained in:
Alan Grainger
2026-07-24 22:15:17 +12:00
parent a1e440c146
commit aa6183a95d
13 changed files with 345 additions and 51 deletions
+77
View File
@@ -0,0 +1,77 @@
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import express from 'express'
import type { Server } from 'http'
import type { AddressInfo } from 'net'
import { asyncHandler, errorHandler } from '../src/http'
/*
Regression tests for the per-request crash class: under Express 4 a rejected
promise in an async route became an unhandledRejection, and index.ts used to
respond to that with process.exit(1) - one bad request took down the whole
container. asyncHandler + errorHandler must instead turn any thrown/rejected
route error into a plain 404 (the privacy policy: no upstream detail) while
the server keeps serving.
*/
describe('asyncHandler + errorHandler', () => {
let server: Server
let base: string
beforeAll(async () => {
// Silence errorHandler's expected server-side logging during these tests
vi.spyOn(console, 'error').mockImplementation(() => {})
const app = express()
app.get('/ok', asyncHandler(async (_req, res) => { res.send('ok') }))
app.get('/boom', asyncHandler(async () => {
throw new TypeError("Cannot read properties of undefined (reading 'headers')")
}))
app.get('/mid-stream', asyncHandler(async (_req, res) => {
res.status(200)
res.write('partial')
throw new Error('upstream died mid-response')
}))
app.use(errorHandler)
await new Promise<void>(resolve => {
server = app.listen(0, resolve)
})
base = 'http://127.0.0.1:' + (server.address() as AddressInfo).port
})
afterAll(() => {
server?.close()
vi.restoreAllMocks()
})
it('turns a rejected route promise into a 404 with an empty body', async () => {
const res = await fetch(base + '/boom')
expect(res.status).toBe(404)
expect(await res.text()).toBe('')
})
it('keeps serving other requests after a route has thrown', async () => {
await fetch(base + '/boom')
const res = await fetch(base + '/ok')
expect(res.status).toBe(200)
expect(await res.text()).toBe('ok')
})
it('does not leak error detail to the client', async () => {
const res = await fetch(base + '/boom')
const body = await res.text()
expect(body).not.toContain('TypeError')
expect(body).not.toContain('headers')
})
it('ends the response when the error hits after headers were sent', async () => {
const res = await fetch(base + '/mid-stream')
// Status was already committed before the throw; the handler can only
// end the stream, not rewrite it to a 404.
expect(res.status).toBe(200)
expect(await res.text()).toBe('partial')
// And the server is still alive afterwards
const ok = await fetch(base + '/ok')
expect(ok.status).toBe(200)
})
})
-26
View File
@@ -1,26 +0,0 @@
import { describe, it, expect } from 'vitest'
import { escapeHtml } from '../src/utils/text'
describe('escapeHtml', () => {
it('escapes the five HTML-significant characters', () => {
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
'&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
)
})
it('escapes ampersand first so other escapes are not re-escaped', () => {
expect(escapeHtml('&amp;')).toBe('&amp;amp;')
})
it('escapes single quotes', () => {
expect(escapeHtml("it's")).toBe('it&#039;s')
})
it('returns empty string unchanged', () => {
expect(escapeHtml('')).toBe('')
})
it('passes through strings with no special characters', () => {
expect(escapeHtml('plain text 123')).toBe('plain text 123')
})
})
+59
View File
@@ -0,0 +1,59 @@
import { describe, it, expect } from 'vitest'
import { h } from 'preact'
import { Gallery, GalleryProps, GalleryItem } from '../src/view/gallery'
import { renderPage } from '../src/view/render'
/*
Regression test for the init-JSON XSS: asset strings (originalFileName, EXIF
description/city/make/model) are attacker-influenced and are serialised into
the <script type="application/json"> init block. A raw `</script>` inside
them must not be able to terminate that block and inject markup.
*/
function galleryProps (item: Partial<GalleryItem>): GalleryProps {
return {
items: [{
id: 'a',
type: 'IMAGE',
previewUrl: '/share/photo/k/a/preview',
thumbnailUrl: '/share/photo/k/a/thumbnail',
downloadFilename: 'photo.jpg',
...item
}],
title: 'Test gallery',
description: '',
publicBaseUrl: 'https://example.com',
path: '/share/k',
showDownloadZip: false,
showTitle: false,
lightboxConfig: { showArrows: true, showDownload: true, mobileArrows: false, autoPlayVideos: false },
metadataConfig: { descriptionInCaption: false, descriptionInSidebar: false, sidebarHasContent: false, locationWebLink: false },
groupByDate: false
}
}
const payload = '</script><script>alert(1)</script>'
describe('gallery init JSON escaping', () => {
it('neutralises </script> in a crafted download filename', () => {
const html = renderPage(h(Gallery, galleryProps({ downloadFilename: payload })))
expect(html).not.toContain('<script>alert(1)</script>')
expect(html).toContain('\\u003c/script>')
})
it('neutralises </script> in crafted EXIF metadata', () => {
const html = renderPage(h(Gallery, galleryProps({
description: payload,
exif: { fileName: payload, city: payload, make: payload }
})))
expect(html).not.toContain('<script>alert(1)</script>')
})
it('still produces JSON the client can parse back to the same items', () => {
const html = renderPage(h(Gallery, galleryProps({ downloadFilename: payload })))
const match = html.match(/<script type="application\/json" id="ipp-init">(.*?)<\/script>/s)
expect(match).not.toBeNull()
const params = JSON.parse(match![1])
expect(params.items[0].downloadFilename).toBe(payload)
})
})
+75
View File
@@ -0,0 +1,75 @@
import { describe, it, expect, afterEach } from 'vitest'
import { loadConfig } from '../src/config/loader'
import { getNumericConfigOption } from '../src/config/access'
import { createLimiter } from '../src/utils/limiter'
/*
Regression tests for the non-numeric concurrency bug: a non-numeric
`ipp.downloadFromImmichConcurrencyLimit` used to reach createLimiter as NaN,
where `active >= NaN` is always false - so the limiter never throttled and
every asset in a zip download hit Immich at once.
*/
function loadConfigFrom (config: Record<string, unknown>) {
process.env.CONFIG = JSON.stringify(config)
loadConfig()
}
afterEach(() => {
delete process.env.CONFIG
loadConfig()
})
describe('getNumericConfigOption', () => {
it('returns a configured number', () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 5 } })
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(5)
})
it('coerces a numeric string (docker-compose env values arrive as strings)', () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: '5' } })
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(5)
})
it('falls back to the default for a non-numeric value instead of NaN', () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 'lots' } })
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
})
it('falls back to the default for non-scalar values', () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: { max: 5 } } })
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
})
it('falls back to the default when the option is unset', () => {
loadConfigFrom({})
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
})
})
describe('createLimiter with guarded config', () => {
/** Run `total` tasks through the limiter and report the concurrency peak */
async function peakConcurrency (limit: number, total: number): Promise<number> {
const run = createLimiter(limit)
let active = 0
let peak = 0
await Promise.all(Array.from({ length: total }, () => run(async () => {
active++
peak = Math.max(peak, active)
// Yield so other queued tasks get a chance to start while this one is "active"
await new Promise(resolve => setTimeout(resolve, 1))
active--
})))
return peak
}
it('a NaN limit disables throttling (the failure mode being guarded against)', async () => {
expect(await peakConcurrency(NaN, 10)).toBe(10)
})
it('the guarded value throttles as configured', async () => {
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 'lots' } })
const limit = Math.max(1, getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 3))
expect(await peakConcurrency(limit, 10)).toBe(3)
})
})
+53
View File
@@ -0,0 +1,53 @@
import { describe, it, expect } from 'vitest'
import { escapeHtml, jsonForInlineScript } from '../src/utils/text'
describe('escapeHtml', () => {
it('escapes the five HTML-significant characters', () => {
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
'&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
)
})
it('escapes ampersand first so other escapes are not re-escaped', () => {
expect(escapeHtml('&amp;')).toBe('&amp;amp;')
})
it('escapes single quotes', () => {
expect(escapeHtml("it's")).toBe('it&#039;s')
})
it('returns empty string unchanged', () => {
expect(escapeHtml('')).toBe('')
})
it('passes through strings with no special characters', () => {
expect(escapeHtml('plain text 123')).toBe('plain text 123')
})
})
describe('jsonForInlineScript', () => {
it('escapes < so </script> cannot terminate an inline script block', () => {
const out = jsonForInlineScript({ name: '</script><script>alert(1)</script>' })
expect(out).not.toContain('<')
expect(out).toContain('\\u003c/script>')
})
it('round-trips through JSON.parse unchanged', () => {
const value = {
name: '</script> & <!-- tricky --> \u2028\u2029',
n: 3,
nested: { arr: [1, 'two'] }
}
expect(JSON.parse(jsonForInlineScript(value))).toEqual(value)
})
it('escapes the JS line separators U+2028 and U+2029', () => {
const out = jsonForInlineScript({ s: '\u2028\u2029' })
expect(out).toBe('{"s":"\\u2028\\u2029"}')
})
it('matches JSON.stringify for benign values', () => {
const value = { a: 1, b: 'plain text', c: null }
expect(jsonForInlineScript(value)).toBe(JSON.stringify(value))
})
})