Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
fix(backend:files): harden SVG thumbnail rendering
johavena9e6f17a563a
diff --git a/backend/src/applications/files/services/files-manager.service.spec.ts b/backend/src/applications/files/services/files-manager.service.spec.tsindex 0c360f9f..4a3cfb79 100644--- a/backend/src/applications/files/services/files-manager.service.spec.ts+++ b/backend/src/applications/files/services/files-manager.service.spec.ts@@ -1448,6 +1448,19 @@ describe(FilesManager.name, () => {expect(result).toBe(stream)})++ it('should pass SVG files to the thumbnail renderer', async () => {+ const space = makeSpace({ realPath: '/data/users/john/files/image.svg' })+ vi.mocked(filesUtils.isPathExists).mockResolvedValueOnce(true)+ vi.mocked(filesUtils.getMimeType).mockReturnValueOnce('image-svg+xml')+ const stream = Readable.from(['img'])+ const generateThumbnailSpy = vi.spyOn(imageUtils, 'generateThumbnail').mockReturnValueOnce(stream as any)++ const result = await service.generateThumbnail(space, 256)++ expect(result).toBe(stream)+ expect(generateThumbnailSpy).toHaveBeenCalledWith(space.realPath, 256)+ })})describe('locking', () => {diff --git a/backend/src/applications/files/services/files-manager.service.ts b/backend/src/applications/files/services/files-manager.service.tsindex 0f00fd50..c9dc8fc0 100644--- a/backend/src/applications/files/services/files-manager.service.ts+++ b/backend/src/applications/files/services/files-manager.service.ts@@ -741,7 +741,8 @@ export class FilesManager {if (!(await isPathExists(space.realPath))) {throw new FileError(HttpStatus.NOT_FOUND, 'Location not found')}- if (getMimeType(space.realPath, false).indexOf('image') === -1) {+ const mimeType = getMimeType(space.realPath, false)+ if (!mimeType.startsWith('image-')) {throw new FileError(HttpStatus.BAD_REQUEST, 'File is not an image')}try {diff --git a/backend/src/common/image.spec.ts b/backend/src/common/image.spec.tsnew file mode 100644index 00000000..72a5c3da--- /dev/null+++ b/backend/src/common/image.spec.ts@@ -0,0 +1,76 @@+import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { Readable } from 'node:stream'+import { pathToFileURL } from 'node:url'+import sharp from 'sharp'+import { maxFileSizeExceededError } from '../applications/files/utils/errors'+import { generateThumbnail, maxThumbnailInputSize } from './image'++async function streamToBuffer(stream: Readable): Promise<Buffer> {+ const chunks: Buffer[] = []+ for await (const chunk of stream) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))+ }+ return Buffer.concat(chunks)+}++describe(generateThumbnail.name, () => {+ let tmpDir: string++ beforeEach(async () => {+ tmpDir = await mkdtemp(path.join(os.tmpdir(), 'thumbnail-svg-'))+ })++ afterEach(async () => {+ await rm(tmpDir, { recursive: true, force: true })+ })++ it('generates a WebP thumbnail from an SVG', async () => {+ const svgPath = path.join(tmpDir, 'image.svg')+ await writeFile(svgPath, '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="blue"/></svg>')++ const thumbnail = await streamToBuffer(await generateThumbnail(svgPath, 32))++ await expect(sharp(thumbnail).metadata()).resolves.toMatchObject({ format: 'webp', width: 32, height: 32 })+ })++ it.each(['png', 'svg'])('rejects an oversized %s source before rendering', async (extension) => {+ const imagePath = path.join(tmpDir, `oversized.${extension}`)+ await writeFile(imagePath, '')+ await truncate(imagePath, maxThumbnailInputSize + 1)++ await expect(generateThumbnail(imagePath, 32)).rejects.toEqual(maxFileSizeExceededError())+ })++ it.each([+ ['XInclude', (secretPath: string) => `<xi:include href="${path.basename(secretPath)}"/>`],+ ['relative image xlink:href', (secretPath: string) => `<image xlink:href="${path.basename(secretPath)}" width="32" height="32"/>`],+ ['file image xlink:href', (secretPath: string) => `<image xlink:href="${pathToFileURL(secretPath).href}" width="32" height="32"/>`]+ ])('does not render local resources referenced through %s', async (_name, externalElement) => {+ const secretPath = path.join(tmpDir, 'secret.svg')+ const svgPath = path.join(tmpDir, 'image.svg')+ await writeFile(secretPath, '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="red"/></svg>')+ await writeFile(+ svgPath,+ `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xlink="http://www.w3.org/1999/xlink"+ width="32" height="32">+ <rect width="32" height="32" fill="blue"/>+ ${externalElement(secretPath)}+ </svg>`+ )++ const thumbnail = await streamToBuffer(await generateThumbnail(svgPath, 32))+ const pixel = await sharp(thumbnail).removeAlpha().extract({ left: 16, top: 16, width: 1, height: 1 }).raw().toBuffer()++ expect(pixel[0]).toBeLessThan(50)+ expect(pixel[2]).toBeGreaterThan(200)+ })++ it('blocks file-mode rendering when SVG content is disguised with another extension', async () => {+ const disguisedSvgPath = path.join(tmpDir, 'image.png')+ await writeFile(disguisedSvgPath, '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32"/></svg>')++ await expect((async () => streamToBuffer(await generateThumbnail(disguisedSvgPath, 32)))()).rejects.toThrow()+ })+})diff --git a/backend/src/common/image.ts b/backend/src/common/image.tsindex 54515a17..8baa04e5 100644--- a/backend/src/common/image.ts+++ b/backend/src/common/image.ts@@ -5,24 +5,33 @@ import { Readable } from 'node:stream'import { promisify } from 'node:util'import sharp from 'sharp'import TextToSVG from 'text-to-svg'+import { maxFileSizeExceededError } from '../applications/files/utils/errors'import { moveFiles } from '../applications/files/utils/files'// Sharp settingssharp.cache(false)sharp.concurrency(Math.min(2, os.cpus()?.length || 1))+// SVG files must only be loaded from buffers so librsvg has no base directory+// from which it can resolve local external resources.+sharp.block({ operation: ['VipsForeignLoadSvgFile'] })// Constantsexport const imgMimeTypePrefix = 'image/'export const pngMimeType = 'image/png'export const svgMimeType = 'image/svg+xml'export const webpMimeType = 'image/webp'+export const maxThumbnailInputSize = 50 * 1024 * 1024const avatarSize = 512const fontPath = path.join(__dirname, 'fonts', 'avatar.ttf')const loadTextToSVG = promisify(TextToSVG.load.bind(TextToSVG))let textToSvgCache: Promise<TextToSVG> | null = nullexport async function generateThumbnail(filePath: string, size: number): Promise<Readable> {- return sharp(filePath, {+ if ((await fs.stat(filePath)).size > maxThumbnailInputSize) {+ throw maxFileSizeExceededError()+ }+ const input = path.extname(filePath).toLowerCase() === '.svg' ? await fs.readFile(filePath) : filePath+ return sharp(input, {failOn: 'none',sequentialRead: true, // sequential read = more efficient I/OlimitInputPixels: 268e6 // protects against extremely large images