diff --git a/server/controllers/MiscController.js b/server/controllers/MiscController.js index 50097e44e..8d860a376 100644 --- a/server/controllers/MiscController.js +++ b/server/controllers/MiscController.js @@ -29,7 +29,8 @@ class MiscController { /** * POST: /api/upload - * Upload files for a new library item. Refuses to overwrite an existing item or file. + * Upload files for a new library item, or add files to an existing folder with update permission. + * Refuses to overwrite existing files unless `overwrite` is true and the user has update and delete permissions. * * @param {RequestWithUser} req * @param {Response} res @@ -50,6 +51,11 @@ class MiscController { if (!libraryId || !folderId || typeof libraryId !== 'string' || typeof folderId !== 'string' || !title || typeof title !== 'string') { return res.status(400).send('Invalid request body') } + const overwrite = req.body.overwrite === true || req.body.overwrite === 'true' || req.body.overwrite === '1' + if (overwrite && (!req.user.canUpdate || !req.user.canDelete)) { + Logger.warn(`[MiscController] User "${req.user.username}" attempted to upload with overwrite without permission`) + return res.sendStatus(403) + } if (!series || typeof series !== 'string') { series = null } @@ -71,11 +77,13 @@ class MiscController { return res.sendStatus(500) } - // A 409 means the destination already belongs to another item. createUploadDirectory - // removes only directories this request created when a later mkdir fails. + // A 409 means a file or parent library item conflict. createUploadDirectory removes only + // directories this request created when a later mkdir fails. // The library lookup is inside the try: Express 4 does not answer a rejected async route. let outputDirectory let firstCreated = null + let createdOutputDirectory = true + let existingFiles = new Set() try { const library = await Database.libraryModel.findByIdWithFolders(libraryId) if (!library) { @@ -102,8 +110,12 @@ class MiscController { const directoryParts = [...parentParts, sanitizedTitle] outputDirectory = Path.join(folder.path, ...directoryParts) - await uploadPath.assertUploadDestination(folder.path, outputDirectory, filenames) - firstCreated = await uploadPath.createUploadDirectory(outputDirectory) + const destination = await uploadPath.assertUploadDestination(folder.path, outputDirectory, filenames, req.user, overwrite) + createdOutputDirectory = !destination?.directoryExists + existingFiles = destination?.existingFiles || new Set() + if (createdOutputDirectory) { + firstCreated = await uploadPath.createUploadDirectory(outputDirectory) + } } catch (error) { if (!(error instanceof uploadPath.UploadError)) { Logger.error('[MiscController] Failed to upload', outputDirectory, error) @@ -111,16 +123,27 @@ class MiscController { return respond(error) } + const createdFiles = [] try { Logger.info(`Uploading ${files.length} files to`, outputDirectory) for (let i = 0; i < files.length; i++) { - await files[i].mv(Path.join(outputDirectory, filenames[i])) + const targetPath = Path.join(outputDirectory, filenames[i]) + if (!overwrite) { + await uploadPath.reserveUploadFile(targetPath) + createdFiles.push(targetPath) + } else if (!existingFiles.has(filenames[i])) { + createdFiles.push(targetPath) + } + await files[i].mv(targetPath) } res.sendStatus(200) } catch (error) { - Logger.error('[MiscController] Failed to upload', outputDirectory, error) - await uploadPath.rollbackFailedUpload(outputDirectory, firstCreated) + if (!(error instanceof uploadPath.UploadError)) { + Logger.error('[MiscController] Failed to upload', outputDirectory, error) + } + await uploadPath.rollbackFailedUpload(outputDirectory, firstCreated, createdOutputDirectory, createdFiles) + if (error instanceof uploadPath.UploadError) return respond(error) const notWritable = uploadPath.notWritableUploadError(error) if (notWritable) return respond(notWritable) return res.sendStatus(500) diff --git a/server/utils/uploadPath.js b/server/utils/uploadPath.js index 1497fda4a..34bbb54fb 100644 --- a/server/utils/uploadPath.js +++ b/server/utils/uploadPath.js @@ -21,6 +21,7 @@ const UPLOAD_DUPLICATE_FILENAME_MESSAGE = 'Duplicate file name in upload' const UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE = 'Cannot write to this library folder' const UPLOAD_INVALID_PATH_MESSAGE = 'Invalid upload path' const UPLOAD_INVALID_FILENAME_MESSAGE = 'Invalid file name' +const UPLOAD_FORBIDDEN_MESSAGE = 'Forbidden' const PLAIN_TEXT_UPLOAD_ERRORS = [UPLOAD_INVALID_PATH_MESSAGE, UPLOAD_INVALID_FILENAME_MESSAGE] module.exports.UPLOAD_ERROR_CODE = UPLOAD_ERROR_CODE @@ -81,6 +82,14 @@ async function libraryItemContainingUpload(folderPath, outputDirectory) { }) } +/** + * @param {string} outputDirectory + * @returns {Promise} + */ +async function libraryItemAtPath(outputDirectory) { + return Database.libraryItemModel.findOneExpanded(libraryItemPathWhere([filePathToPOSIX(outputDirectory)])) +} + class UploadError extends Error { /** * A code makes the response JSON `{ code, error, ...details }`. Without one, the response stays the plain message. @@ -124,26 +133,22 @@ async function lookupUploadDirectory(folderPath, outputDirectory) { /** * Throw when this upload must not be written. - * An existing destination directory is refused outright, so individual files are not checked on disk. + * Allows adding non-conflicting files to an existing directory when the user has update permission + * (and access to any matching library item), and overwriting existing regular files only when + * `overwrite` is true. Nested uploads inside an existing library item are always refused. * * @param {string} folderPath * @param {string} outputDirectory absolute directory the files would be written into * @param {string[]} filenames sanitized file names - * @returns {Promise} + * @param {import('../models/User') | null} [user] + * @param {boolean} [overwrite] + * @returns {Promise<{ directoryExists: boolean, existingFiles: Set }>} */ -async function assertUploadDestination(folderPath, outputDirectory, filenames) { +async function assertUploadDestination(folderPath, outputDirectory, filenames, user = null, overwrite = false) { // The library folder itself is not a valid item directory, even when every name sanitized away. if (!isStrictSubPath(folderPath, outputDirectory)) { throw new UploadError(400, UPLOAD_INVALID_PATH_MESSAGE) } - const existing = await lookupUploadDirectory(folderPath, outputDirectory) - if ('libraryItemTitle' in existing) { - const message = `${UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}${existing.libraryItemTitle}` - throw new UploadError(409, message, UPLOAD_ERROR_CODE.libraryItemExists, { libraryItemTitle: existing.libraryItemTitle }) - } - if (existing.exists) { - throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists) - } const seen = new Set() for (const name of filenames) { @@ -152,6 +157,65 @@ async function assertUploadDestination(folderPath, outputDirectory, filenames) { if (seen.has(key)) throw new UploadError(409, UPLOAD_DUPLICATE_FILENAME_MESSAGE, UPLOAD_ERROR_CODE.duplicateFileName) seen.add(key) } + + const parentLibraryItem = await libraryItemContainingUpload(folderPath, outputDirectory) + if (parentLibraryItem) { + const libraryItemTitle = parentLibraryItem.title || '' + const message = `${UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}${libraryItemTitle}` + throw new UploadError(409, message, UPLOAD_ERROR_CODE.libraryItemExists, { libraryItemTitle }) + } + + let dirStat = null + try { + dirStat = await fs.lstat(outputDirectory) + } catch (error) { + if (error.code === 'ENOTDIR') { + throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists) + } + if (error.code !== 'ENOENT') { + const notWritable = notWritableUploadError(error) + if (notWritable) throw notWritable + throw error + } + } + + if (!dirStat) { + return { directoryExists: false, existingFiles: new Set() } + } + + if (!dirStat.isDirectory()) { + throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists) + } + + if (!user?.canUpdate) { + throw new UploadError(403, UPLOAD_FORBIDDEN_MESSAGE) + } + + const existingLibraryItem = await libraryItemAtPath(outputDirectory) + if (existingLibraryItem && !user.checkCanAccessLibraryItem(existingLibraryItem)) { + throw new UploadError(403, UPLOAD_FORBIDDEN_MESSAGE) + } + + const existingFiles = new Set() + for (const name of filenames) { + const targetPath = Path.join(outputDirectory, name) + let targetStat = null + try { + targetStat = await fs.lstat(targetPath) + } catch (error) { + if (error.code === 'ENOENT') continue + const notWritable = notWritableUploadError(error) + if (notWritable) throw notWritable + throw error + } + + if (targetStat.isDirectory() || targetStat.isSymbolicLink() || !overwrite) { + throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists) + } + existingFiles.add(name) + } + + return { directoryExists: true, existingFiles } } module.exports.assertUploadDestination = assertUploadDestination @@ -242,23 +306,61 @@ async function removeEmptyCreatedDirectories(deepest, firstCreated) { } /** - * Remove the item directory this request created, then empty parents this request created. - * firstCreated is the return value of createUploadDirectory. + * Atomically reserve a destination file path so a concurrent upload cannot overwrite it. + * + * @param {string} targetPath + * @returns {Promise} + */ +async function reserveUploadFile(targetPath) { + let fd + try { + fd = await fs.open(targetPath, 'wx') + } catch (error) { + if (error.code === 'EEXIST' || error.code === 'EISDIR') { + throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists) + } + const notWritable = notWritableUploadError(error) + if (notWritable) throw notWritable + throw error + } + await fs.close(fd) +} +module.exports.reserveUploadFile = reserveUploadFile + +/** + * Roll back a failed upload without touching pre-existing directories or files. + * When this request created outputDirectory, remove it and any empty parents this request created. + * When outputDirectory already existed, remove only files created by this request. * Unmoved temp files are deleted by the multipart parser when the response closes. * * @param {string} outputDirectory * @param {string | null} firstCreated + * @param {boolean} [createdOutputDirectory] + * @param {string[]} [createdFiles] * @returns {Promise} */ -async function rollbackFailedUpload(outputDirectory, firstCreated) { - try { - await fs.remove(outputDirectory) - } catch (error) { - if (error.code !== 'ENOENT') { - Logger.error('[uploadPath] Failed to remove partial upload', outputDirectory, error) +async function rollbackFailedUpload(outputDirectory, firstCreated, createdOutputDirectory = true, createdFiles = []) { + if (createdOutputDirectory) { + try { + await fs.remove(outputDirectory) + } catch (error) { + if (error.code !== 'ENOENT') { + Logger.error('[uploadPath] Failed to remove partial upload', outputDirectory, error) + } } + + await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated) + return } - await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated) + for (const filePath of createdFiles) { + try { + await fs.unlink(filePath) + } catch (error) { + if (error.code !== 'ENOENT') { + Logger.error('[uploadPath] Failed to remove partial upload file', filePath, error) + } + } + } } module.exports.rollbackFailedUpload = rollbackFailedUpload diff --git a/test/server/controllers/MiscController.test.js b/test/server/controllers/MiscController.test.js index d5c0831df..69d74b739 100644 --- a/test/server/controllers/MiscController.test.js +++ b/test/server/controllers/MiscController.test.js @@ -27,7 +27,26 @@ describe('upload path collisions', () => { canUpload: true, canUpdate: false, canDelete: false, - checkCanAccessLibrary: () => true + checkCanAccessLibrary: () => true, + checkCanAccessLibraryItem: () => true + } + + const updateUser = { + username: 'updater', + canUpload: true, + canUpdate: true, + canDelete: false, + checkCanAccessLibrary: () => true, + checkCanAccessLibraryItem: () => true + } + + const deleteUser = { + username: 'admin-delete', + canUpload: true, + canUpdate: true, + canDelete: true, + checkCanAccessLibrary: () => true, + checkCanAccessLibraryItem: () => true } async function pathExists(targetPath) { @@ -160,14 +179,14 @@ describe('upload path collisions', () => { expect(await pathExists(file.tempFilePath)).to.equal(false) }) - it('refuses when the destination directory already exists and leaves it unchanged', async () => { + it('refuses overwriting an existing file by default and leaves it unchanged', async () => { const destinationDir = Path.join(folder.path, 'Author A', 'Book B') await fs.mkdir(destinationDir, { recursive: true }) const existing = Path.join(destinationDir, '01.mp3') await fs.writeFile(existing, 'original') const res = mockRes() - await MiscController.handleUpload(uploadRequest(), res) + await MiscController.handleUpload(uploadRequest({ user: updateUser }), res) expect(res.statusCode).to.equal(409) expect(res.body).to.deep.equal({ @@ -177,6 +196,309 @@ describe('upload path collisions', () => { expect(await fs.readFile(existing, 'utf8')).to.equal('original') }) + it('allows adding new files to an existing folder for users with update permission', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: updateUser, + files: { + 0: fakeUploadFile('02.mp3', 'second-track') + } + }), + res + ) + + expect(res.statusCode).to.equal(200) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + expect(await fs.readFile(Path.join(destinationDir, '02.mp3'), 'utf8')).to.equal('second-track') + }) + + it('refuses an upload-only user adding files to an existing folder', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: uploadUser, + files: { + 0: fakeUploadFile('02.mp3', 'second-track') + } + }), + res + ) + + expect(res.statusCode).to.equal(403) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + expect(await pathExists(Path.join(destinationDir, '02.mp3'))).to.equal(false) + }) + + it('refuses adding files to an existing library item the user cannot access', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const book = await Database.bookModel.create({ + title: 'Book B', + tags: ['restricted'], + explicit: false + }) + await Database.libraryItemModel.create({ + path: filePathToPOSIX(destinationDir), + title: 'Book B', + mediaId: book.id, + mediaType: 'book', + libraryFiles: [], + libraryId: library.id, + libraryFolderId: folder.id + }) + + const restrictedUpdater = { + ...updateUser, + checkCanAccessLibraryItem: () => false + } + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: restrictedUpdater, + files: { + 0: fakeUploadFile('02.mp3', 'second-track') + } + }), + res + ) + + expect(res.statusCode).to.equal(403) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + expect(await pathExists(Path.join(destinationDir, '02.mp3'))).to.equal(false) + }) + + it('refuses overwrite=true when the user lacks delete permission', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: updateUser, + body: { + title: 'Book B', + author: 'Author A', + series: '', + library: library.id, + folder: folder.id, + overwrite: 'true' + } + }), + res + ) + + expect(res.statusCode).to.equal(403) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + }) + + it('overwrites existing files and adds new files when overwrite is true and user has delete permission', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: deleteUser, + files: { + 0: fakeUploadFile('01.mp3', 'replaced'), + 1: fakeUploadFile('02.mp3', 'added') + }, + body: { + title: 'Book B', + author: 'Author A', + series: '', + library: library.id, + folder: folder.id, + overwrite: 'true' + } + }), + res + ) + + expect(res.statusCode).to.equal(200) + expect(await fs.readFile(existing, 'utf8')).to.equal('replaced') + expect(await fs.readFile(Path.join(destinationDir, '02.mp3'), 'utf8')).to.equal('added') + }) + + it('accepts overwrite="1" when user has delete permission', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: deleteUser, + files: { + 0: fakeUploadFile('01.mp3', 'replaced') + }, + body: { + title: 'Book B', + author: 'Author A', + series: '', + library: library.id, + folder: folder.id, + overwrite: '1' + } + }), + res + ) + + expect(res.statusCode).to.equal(200) + expect(await fs.readFile(existing, 'utf8')).to.equal('replaced') + }) + + it('treats overwrite="false" as false and refuses overwriting existing files', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: deleteUser, + files: { + 0: fakeUploadFile('02.mp3', 'added'), + 1: fakeUploadFile('01.mp3', 'replaced') + }, + body: { + title: 'Book B', + author: 'Author A', + series: '', + library: library.id, + folder: folder.id, + overwrite: 'false' + } + }), + res + ) + + expect(res.statusCode).to.equal(409) + expect(res.body).to.deep.equal({ + code: uploadPath.UPLOAD_ERROR_CODE.pathExists, + error: uploadPath.UPLOAD_PATH_EXISTS_MESSAGE + }) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + expect(await pathExists(Path.join(destinationDir, '02.mp3'))).to.equal(false) + }) + + it('refuses when the destination path is an existing file even with overwrite=true', async () => { + const authorDir = Path.join(folder.path, 'Author A') + await fs.mkdir(authorDir, { recursive: true }) + const bookFile = Path.join(authorDir, 'Book B') + await fs.writeFile(bookFile, 'not-a-directory') + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: deleteUser, + body: { + title: 'Book B', + author: 'Author A', + series: '', + library: library.id, + folder: folder.id, + overwrite: true + } + }), + res + ) + + expect(res.statusCode).to.equal(409) + expect(res.body).to.deep.equal({ + code: uploadPath.UPLOAD_ERROR_CODE.pathExists, + error: uploadPath.UPLOAD_PATH_EXISTS_MESSAGE + }) + expect(await fs.readFile(bookFile, 'utf8')).to.equal('not-a-directory') + }) + + it('refuses when a target filename is an existing subdirectory even with overwrite=true', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + const conflictingDir = Path.join(destinationDir, '01.mp3') + await fs.mkdir(conflictingDir, { recursive: true }) + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: deleteUser, + body: { + title: 'Book B', + author: 'Author A', + series: '', + library: library.id, + folder: folder.id, + overwrite: true + } + }), + res + ) + + expect(res.statusCode).to.equal(409) + expect(res.body).to.deep.equal({ + code: uploadPath.UPLOAD_ERROR_CODE.pathExists, + error: uploadPath.UPLOAD_PATH_EXISTS_MESSAGE + }) + expect((await fs.lstat(conflictingDir)).isDirectory()).to.equal(true) + }) + + it('refuses a nested upload inside an existing library item even when overwrite=true and the subdirectory exists', async () => { + const parentPath = filePathToPOSIX(Path.join(folder.path, 'Author A', 'Book B')) + const nestedDir = Path.join(folder.path, 'Author A', 'Book B', 'Sequel') + await fs.mkdir(nestedDir, { recursive: true }) + await Database.libraryItemModel.create({ + path: parentPath, + title: 'Book B', + mediaType: 'book', + libraryFiles: [], + libraryId: library.id, + libraryFolderId: folder.id + }) + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: deleteUser, + body: { + title: 'Sequel', + author: 'Author A', + series: 'Book B', + library: library.id, + folder: folder.id, + overwrite: true + } + }), + res + ) + + expect(res.statusCode).to.equal(409) + expect(res.body).to.deep.equal({ + code: uploadPath.UPLOAD_ERROR_CODE.libraryItemExists, + libraryItemTitle: 'Book B', + error: `${uploadPath.UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}Book B` + }) + expect(await pathExists(Path.join(nestedDir, '01.mp3'))).to.equal(false) + }) + it('refuses when a parent path is a file and leaves that file unchanged', async () => { const authorFile = Path.join(folder.path, 'Author A') await fs.writeFile(authorFile, 'not-a-directory') @@ -577,7 +899,7 @@ describe('upload path collisions', () => { expect(await pathExists(Path.join(folder.path, '...'))).to.equal(false) }) - it('does not let an upload-only user overwrite an existing item', async () => { + it('does not let an upload-only user modify or overwrite an existing item', async () => { const destinationDir = Path.join(folder.path, 'Author A', 'Book B') await fs.mkdir(destinationDir, { recursive: true }) await fs.writeFile(Path.join(destinationDir, '01.mp3'), 'original') @@ -587,8 +909,140 @@ describe('upload path collisions', () => { expect(uploadUser.canUpdate).to.equal(false) expect(uploadUser.canDelete).to.equal(false) - expect(res.statusCode).to.equal(409) + expect(res.statusCode).to.equal(403) expect(await fs.readFile(Path.join(destinationDir, '01.mp3'), 'utf8')).to.equal('original') + + const overwriteRes = mockRes() + await MiscController.handleUpload( + uploadRequest({ + body: { + title: 'Book B', + author: 'Author A', + series: '', + library: library.id, + folder: folder.id, + overwrite: true + } + }), + overwriteRes + ) + expect(overwriteRes.statusCode).to.equal(403) + expect(await fs.readFile(Path.join(destinationDir, '01.mp3'), 'utf8')).to.equal('original') + }) + + it('keeps an existing folder and its files when adding a file fails', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const first = fakeUploadFile('02.mp3', 'second') + const second = fakeUploadFile('03.mp3', 'third', { fail: true }) + await fs.writeFile(second.tempFilePath, 'third') + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: updateUser, + files: { 0: first, 1: second } + }), + res + ) + + expect(res.statusCode).to.equal(500) + expect(await pathExists(destinationDir)).to.equal(true) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + expect(await pathExists(Path.join(destinationDir, '02.mp3'))).to.equal(false) + expect(await pathExists(Path.join(destinationDir, '03.mp3'))).to.equal(false) + }) + + it('removes only newly created files when a later overwrite move fails', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const added = fakeUploadFile('02.mp3', 'added') + const failingOverwrite = fakeUploadFile('01.mp3', 'replaced', { fail: true }) + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: deleteUser, + files: { 0: added, 1: failingOverwrite }, + body: { + title: 'Book B', + author: 'Author A', + series: '', + library: library.id, + folder: folder.id, + overwrite: true + } + }), + res + ) + + expect(res.statusCode).to.equal(500) + expect(await pathExists(destinationDir)).to.equal(true) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + expect(await pathExists(Path.join(destinationDir, '02.mp3'))).to.equal(false) + }) + + it('refuses with 409 and rolls back earlier new files if a file appears concurrently during upload', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + const racedFile = Path.join(destinationDir, '03.mp3') + await fs.writeFile(racedFile, 'concurrent') + + sinon.stub(uploadPath, 'assertUploadDestination').resolves({ directoryExists: true, existingFiles: new Set() }) + + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: updateUser, + files: { + 0: fakeUploadFile('02.mp3', 'added'), + 1: fakeUploadFile('03.mp3', 'conflict') + } + }), + res + ) + + expect(res.statusCode).to.equal(409) + expect(res.body).to.deep.equal({ + code: uploadPath.UPLOAD_ERROR_CODE.pathExists, + error: uploadPath.UPLOAD_PATH_EXISTS_MESSAGE + }) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + expect(await fs.readFile(racedFile, 'utf8')).to.equal('concurrent') + expect(await pathExists(Path.join(destinationDir, '02.mp3'))).to.equal(false) + }) + + it('answers 403 when adding a file to an existing folder is denied and leaves existing files intact', async () => { + const destinationDir = Path.join(folder.path, 'Author A', 'Book B') + await fs.mkdir(destinationDir, { recursive: true }) + const existing = Path.join(destinationDir, '01.mp3') + await fs.writeFile(existing, 'original') + + const file = fakeUploadFile('02.mp3', 'second', { fail: true, failCode: 'EACCES' }) + const res = mockRes() + await MiscController.handleUpload( + uploadRequest({ + user: updateUser, + files: { 0: file } + }), + res + ) + + expect(res.statusCode).to.equal(403) + expect(res.body).to.deep.equal({ + code: uploadPath.UPLOAD_ERROR_CODE.folderNotWritable, + error: uploadPath.UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE + }) + expect(await fs.readFile(existing, 'utf8')).to.equal('original') + expect(await pathExists(Path.join(destinationDir, '02.mp3'))).to.equal(false) }) it('removes partial files when a move fails and does not answer 200', async () => {