mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-12-02 05:04:13 +01:00
Refuse uploads that would overwrite an existing library item
This commit is contained in:
1 parent
03cca94403
commit
0afb582f09
4 files changed
+1108
-68
No files matched your search
@@ -4,6 +4,7 @@ const Logger = require('../Logger')
|
|||||||
const fs = require('../libs/fsExtra')
|
const fs = require('../libs/fsExtra')
|
||||||
const { toNumber } = require('../utils/index')
|
const { toNumber } = require('../utils/index')
|
||||||
const fileUtils = require('../utils/fileUtils')
|
const fileUtils = require('../utils/fileUtils')
|
||||||
|
const uploadPath = require('../utils/uploadPath')
|
||||||
const Database = require('../Database')
|
const Database = require('../Database')
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -96,7 +97,8 @@ class FileSystemController {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check that library folder exists
|
// Check that library folder exists. The lookup is inside the try: Express 4 does not answer a rejected async route.
|
||||||
|
try {
|
||||||
const libraryFolder = await Database.libraryFolderModel.findOne({
|
const libraryFolder = await Database.libraryFolderModel.findOne({
|
||||||
where: {
|
where: {
|
||||||
path: folderPath
|
path: folderPath
|
||||||
@@ -113,50 +115,26 @@ class FileSystemController {
|
|||||||
return res.sendStatus(403)
|
return res.sendStatus(403)
|
||||||
}
|
}
|
||||||
|
|
||||||
let filepath = Path.join(libraryFolder.path, directory)
|
// Same rules as POST /api/upload: the directory itself, then a library item in a parent folder.
|
||||||
filepath = fileUtils.filePathToPOSIX(filepath)
|
|
||||||
|
|
||||||
// Ensure filepath is inside library folder (prevents directory traversal)
|
|
||||||
if (!fileUtils.isSameOrSubPath(libraryFolder.path, filepath)) {
|
|
||||||
Logger.error(`[FileSystemController] Filepath is not inside library folder: ${filepath}`)
|
|
||||||
return res.sendStatus(400)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (await fs.pathExists(filepath)) {
|
|
||||||
return res.json({
|
|
||||||
exists: true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if a library item exists in a subdirectory
|
|
||||||
// See: https://github.com/advplyr/audiobookshelf/issues/4146
|
// See: https://github.com/advplyr/audiobookshelf/issues/4146
|
||||||
const cleanedDirectory = directory.split('/').filter(Boolean).join('/')
|
const existing = await uploadPath.checkUploadDirectory(libraryFolder.path, directory)
|
||||||
if (cleanedDirectory.includes('/')) {
|
if ('libraryItemTitle' in existing) {
|
||||||
// Can only be 2 levels deep
|
|
||||||
const possiblePaths = []
|
|
||||||
const subdir = Path.dirname(directory)
|
|
||||||
possiblePaths.push(fileUtils.filePathToPOSIX(Path.join(folderPath, subdir)))
|
|
||||||
if (subdir.includes('/')) {
|
|
||||||
possiblePaths.push(fileUtils.filePathToPOSIX(Path.join(folderPath, Path.dirname(subdir))))
|
|
||||||
}
|
|
||||||
|
|
||||||
const libraryItem = await Database.libraryItemModel.findOne({
|
|
||||||
where: {
|
|
||||||
path: possiblePaths
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if (libraryItem) {
|
|
||||||
return res.json({
|
return res.json({
|
||||||
exists: true,
|
exists: true,
|
||||||
libraryItemTitle: libraryItem.title
|
libraryItemTitle: existing.libraryItemTitle
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return res.json({
|
return res.json({
|
||||||
exists: false
|
exists: existing.exists
|
||||||
})
|
})
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof uploadPath.UploadError) {
|
||||||
|
Logger.error(`[FileSystemController] Filepath is not inside library folder: ${directory}`)
|
||||||
|
return res.sendStatus(error.statusCode)
|
||||||
|
}
|
||||||
|
Logger.error('[FileSystemController] Failed to check if path exists', directory, error)
|
||||||
|
return res.sendStatus(500)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
module.exports = new FileSystemController()
|
module.exports = new FileSystemController()
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
const Sequelize = require('sequelize')
|
const Sequelize = require('sequelize')
|
||||||
const Path = require('path')
|
const Path = require('path')
|
||||||
const { Request, Response } = require('express')
|
const { Request, Response } = require('express')
|
||||||
const fs = require('../libs/fsExtra')
|
|
||||||
const Logger = require('../Logger')
|
const Logger = require('../Logger')
|
||||||
const SocketAuthority = require('../SocketAuthority')
|
const SocketAuthority = require('../SocketAuthority')
|
||||||
const Database = require('../Database')
|
const Database = require('../Database')
|
||||||
@@ -12,6 +11,7 @@ const cron = require('../libs/nodeCron')
|
|||||||
const { isObject, getTitleIgnorePrefix } = require('../utils/index')
|
const { isObject, getTitleIgnorePrefix } = require('../utils/index')
|
||||||
const ServerSettings = require('../objects/settings/ServerSettings')
|
const ServerSettings = require('../objects/settings/ServerSettings')
|
||||||
const { sanitizeFilename } = require('../utils/fileUtils')
|
const { sanitizeFilename } = require('../utils/fileUtils')
|
||||||
|
const uploadPath = require('../utils/uploadPath')
|
||||||
const { sanitize } = require('../utils/htmlSanitizer')
|
const { sanitize } = require('../utils/htmlSanitizer')
|
||||||
|
|
||||||
const TaskManager = require('../managers/TaskManager')
|
const TaskManager = require('../managers/TaskManager')
|
||||||
@@ -29,7 +29,7 @@ class MiscController {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* POST: /api/upload
|
* POST: /api/upload
|
||||||
* Update library item
|
* Upload files for a new library item. Refuses to overwrite an existing item or file.
|
||||||
*
|
*
|
||||||
* @param {RequestWithUser} req
|
* @param {RequestWithUser} req
|
||||||
* @param {Response} res
|
* @param {Response} res
|
||||||
@@ -39,12 +39,12 @@ class MiscController {
|
|||||||
Logger.warn(`User "${req.user.username}" attempted to upload without permission`)
|
Logger.warn(`User "${req.user.username}" attempted to upload without permission`)
|
||||||
return res.sendStatus(403)
|
return res.sendStatus(403)
|
||||||
}
|
}
|
||||||
if (!req.files || !Object.values(req.files).length) {
|
// Flatten first. A field can be present and still hold no files.
|
||||||
|
const files = Object.values(req.files || {}).flat()
|
||||||
|
if (!files.length) {
|
||||||
Logger.error('Invalid request, no files')
|
Logger.error('Invalid request, no files')
|
||||||
return res.sendStatus(400)
|
return res.sendStatus(400)
|
||||||
}
|
}
|
||||||
|
|
||||||
const files = Object.values(req.files).flat()
|
|
||||||
let { title, author, series, folder: folderId, library: libraryId } = req.body
|
let { title, author, series, folder: folderId, library: libraryId } = req.body
|
||||||
// Validate request body
|
// Validate request body
|
||||||
if (!libraryId || !folderId || typeof libraryId !== 'string' || typeof folderId !== 'string' || !title || typeof title !== 'string') {
|
if (!libraryId || !folderId || typeof libraryId !== 'string' || typeof folderId !== 'string' || !title || typeof title !== 'string') {
|
||||||
@@ -57,6 +57,23 @@ class MiscController {
|
|||||||
author = null
|
author = null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const filenames = files.map((file) => sanitizeFilename(file.name))
|
||||||
|
|
||||||
|
const respond = (error) => {
|
||||||
|
if (error instanceof uploadPath.UploadError) {
|
||||||
|
Logger.warn(`[MiscController] User "${req.user.username}" upload failed (${error.statusCode}): ${error.message}`)
|
||||||
|
if (error.body) return res.status(error.statusCode).json(error.body)
|
||||||
|
return res.status(error.statusCode).send(error.message)
|
||||||
|
}
|
||||||
|
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.
|
||||||
|
// The library lookup is inside the try: Express 4 does not answer a rejected async route.
|
||||||
|
let outputDirectory
|
||||||
|
let firstCreated = null
|
||||||
|
try {
|
||||||
const library = await Database.libraryModel.findByIdWithFolders(libraryId)
|
const library = await Database.libraryModel.findByIdWithFolders(libraryId)
|
||||||
if (!library) {
|
if (!library) {
|
||||||
return res.status(404).send('Library not found')
|
return res.status(404).send('Library not found')
|
||||||
@@ -72,40 +89,40 @@ class MiscController {
|
|||||||
return res.status(404).send('Folder not found')
|
return res.status(404).send('Folder not found')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Podcasts should only be one folder deep
|
// Podcasts should only be one folder deep. A title that sanitizes to an empty name
|
||||||
const outputDirectoryParts = library.isPodcast ? [title] : [author, series, title]
|
// must not fall through to the author folder or the library folder.
|
||||||
// `.filter(Boolean)` to strip out all the potentially missing details (eg: `author`)
|
const sanitizedTitle = sanitizeFilename(title)
|
||||||
// before sanitizing all the directory parts to remove illegal chars and finally prepending
|
if (!sanitizedTitle) {
|
||||||
// the base folder path
|
return res.status(400).send('Invalid upload path')
|
||||||
const cleanedOutputDirectoryParts = outputDirectoryParts.filter(Boolean).map((part) => sanitizeFilename(part))
|
}
|
||||||
const outputDirectory = Path.join(...[folder.path, ...cleanedOutputDirectoryParts])
|
const parentParts = library.isPodcast ? [] : [author, series].map((part) => sanitizeFilename(part)).filter(Boolean)
|
||||||
|
const directoryParts = [...parentParts, sanitizedTitle]
|
||||||
|
outputDirectory = Path.join(folder.path, ...directoryParts)
|
||||||
|
|
||||||
try {
|
await uploadPath.assertUploadDestination(folder.path, outputDirectory, filenames)
|
||||||
await fs.ensureDir(outputDirectory)
|
firstCreated = await uploadPath.createUploadDirectory(outputDirectory)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Logger.error('[MiscController] Failed to create upload directory', outputDirectory, error)
|
if (!(error instanceof uploadPath.UploadError)) {
|
||||||
return res.sendStatus(500)
|
Logger.error('[MiscController] Failed to upload', outputDirectory, error)
|
||||||
|
}
|
||||||
|
return respond(error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
Logger.info(`Uploading ${files.length} files to`, outputDirectory)
|
Logger.info(`Uploading ${files.length} files to`, outputDirectory)
|
||||||
|
for (let i = 0; i < files.length; i++) {
|
||||||
for (const file of files) {
|
await files[i].mv(Path.join(outputDirectory, filenames[i]))
|
||||||
const path = Path.join(outputDirectory, sanitizeFilename(file.name))
|
|
||||||
|
|
||||||
await file
|
|
||||||
.mv(path)
|
|
||||||
.then(() => {
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
Logger.error('Failed to move file', path, error)
|
|
||||||
return false
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
res.sendStatus(200)
|
res.sendStatus(200)
|
||||||
|
} catch (error) {
|
||||||
|
Logger.error('[MiscController] Failed to upload', outputDirectory, error)
|
||||||
|
await uploadPath.rollbackFailedUpload(outputDirectory, firstCreated)
|
||||||
|
const notWritable = uploadPath.notWritableUploadError(error)
|
||||||
|
if (notWritable) return respond(notWritable)
|
||||||
|
return res.sendStatus(500)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET: /api/tasks
|
* GET: /api/tasks
|
||||||
* Get tasks for task manager
|
* Get tasks for task manager
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
const Path = require('path')
|
||||||
|
const { Op, where, fn, col } = require('sequelize')
|
||||||
|
const fs = require('../libs/fsExtra')
|
||||||
|
const Database = require('../Database')
|
||||||
|
const Logger = require('../Logger')
|
||||||
|
const { filePathToPOSIX, isSameOrSubPath, isStrictSubPath } = require('./fileUtils')
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stable codes for new upload failures. `error` stays an English sentence so older clients
|
||||||
|
* can keep displaying the body. Existing plain-text 400/404 responses are unchanged.
|
||||||
|
*/
|
||||||
|
const UPLOAD_ERROR_CODE = {
|
||||||
|
pathExists: 'UPLOAD_PATH_EXISTS',
|
||||||
|
libraryItemExists: 'UPLOAD_LIBRARY_ITEM_EXISTS',
|
||||||
|
duplicateFileName: 'UPLOAD_DUPLICATE_FILENAME',
|
||||||
|
folderNotWritable: 'UPLOAD_FOLDER_NOT_WRITABLE'
|
||||||
|
}
|
||||||
|
const UPLOAD_PATH_EXISTS_MESSAGE = 'File already exists'
|
||||||
|
const UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX = 'Library item exists: '
|
||||||
|
const UPLOAD_DUPLICATE_FILENAME_MESSAGE = 'Duplicate file name in upload'
|
||||||
|
const UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE = 'Cannot write to this library folder'
|
||||||
|
|
||||||
|
module.exports.UPLOAD_ERROR_CODE = UPLOAD_ERROR_CODE
|
||||||
|
module.exports.UPLOAD_PATH_EXISTS_MESSAGE = UPLOAD_PATH_EXISTS_MESSAGE
|
||||||
|
module.exports.UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX = UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX
|
||||||
|
module.exports.UPLOAD_DUPLICATE_FILENAME_MESSAGE = UPLOAD_DUPLICATE_FILENAME_MESSAGE
|
||||||
|
module.exports.UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE = UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paths of library items this upload would be nested inside (issue #4146).
|
||||||
|
* At most two levels above the upload directory, matching the previous pathexists check.
|
||||||
|
*
|
||||||
|
* @param {string} folderPath
|
||||||
|
* @param {string} outputDirectory
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
function parentLibraryItemPaths(folderPath, outputDirectory) {
|
||||||
|
const relative = filePathToPOSIX(Path.relative(folderPath, outputDirectory))
|
||||||
|
if (!relative || relative === '.' || relative === '..' || relative.startsWith('../') || !relative.includes('/')) return []
|
||||||
|
|
||||||
|
const parent = Path.posix.dirname(relative)
|
||||||
|
const paths = [filePathToPOSIX(Path.join(folderPath, parent))]
|
||||||
|
if (parent.includes('/')) {
|
||||||
|
paths.push(filePathToPOSIX(Path.join(folderPath, Path.posix.dirname(parent))))
|
||||||
|
}
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Windows and macOS treat paths that differ only by case as the same directory.
|
||||||
|
* A case-sensitive match would miss `Author A/Book B` and write `author a/book b/extra` inside it.
|
||||||
|
*
|
||||||
|
* @param {string[]} paths
|
||||||
|
* @returns {import('sequelize').WhereOptions}
|
||||||
|
*/
|
||||||
|
function libraryItemPathWhere(paths) {
|
||||||
|
if (global.isWin || process.platform === 'darwin') {
|
||||||
|
// Apply SQL lower() on both sides so both match SQLite's active lower() implementation
|
||||||
|
// (Unicode via libnusqlite3 when loaded, or ASCII fallback without breaking exact Unicode matches).
|
||||||
|
return where(fn('lower', col('path')), {
|
||||||
|
[Op.in]: paths.map((libraryItemPath) => fn('lower', libraryItemPath))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return { path: paths }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} folderPath
|
||||||
|
* @param {string} outputDirectory
|
||||||
|
* @returns {Promise<import('../models/LibraryItem') | null>}
|
||||||
|
*/
|
||||||
|
async function libraryItemContainingUpload(folderPath, outputDirectory) {
|
||||||
|
const paths = parentLibraryItemPaths(folderPath, outputDirectory)
|
||||||
|
if (!paths.length) return null
|
||||||
|
return Database.libraryItemModel.findOne({
|
||||||
|
where: libraryItemPathWhere(paths)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
class UploadError extends Error {
|
||||||
|
/**
|
||||||
|
* A code makes the response JSON `{ code, error, ...details }`. Without one, the response stays the plain message.
|
||||||
|
*
|
||||||
|
* @param {number} statusCode
|
||||||
|
* @param {string} message plain-text response, also used as Error.message and as the JSON `error`
|
||||||
|
* @param {string | null} [code]
|
||||||
|
* @param {object} [details] extra JSON fields, such as libraryItemTitle
|
||||||
|
*/
|
||||||
|
constructor(statusCode, message, code = null, details = {}) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'UploadError'
|
||||||
|
this.statusCode = statusCode
|
||||||
|
this.body = code ? { code, error: message, ...details } : null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports.UploadError = UploadError
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared lookup for the upload handler and POST /api/filesystem/pathexists.
|
||||||
|
* Throws when the path escapes the library folder.
|
||||||
|
*
|
||||||
|
* @param {string} folderPath
|
||||||
|
* @param {string} outputDirectory
|
||||||
|
* @returns {Promise<{ exists: boolean, libraryItemTitle?: string }>}
|
||||||
|
*/
|
||||||
|
async function lookupUploadDirectory(folderPath, outputDirectory) {
|
||||||
|
if (!isSameOrSubPath(folderPath, outputDirectory)) {
|
||||||
|
throw new UploadError(400, 'Invalid upload path')
|
||||||
|
}
|
||||||
|
if (await fs.pathExists(outputDirectory)) {
|
||||||
|
return { exists: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
const libraryItem = await libraryItemContainingUpload(folderPath, outputDirectory)
|
||||||
|
if (libraryItem) {
|
||||||
|
return { exists: true, libraryItemTitle: libraryItem.title || '' }
|
||||||
|
}
|
||||||
|
return { exists: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throw when this upload must not be written.
|
||||||
|
* An existing destination directory is refused outright, so individual files are not checked on disk.
|
||||||
|
*
|
||||||
|
* @param {string} folderPath
|
||||||
|
* @param {string} outputDirectory absolute directory the files would be written into
|
||||||
|
* @param {string[]} filenames sanitized file names
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async function assertUploadDestination(folderPath, outputDirectory, filenames) {
|
||||||
|
// The library folder itself is not a valid item directory, even when every name sanitized away.
|
||||||
|
if (!isStrictSubPath(folderPath, outputDirectory)) {
|
||||||
|
throw new UploadError(400, 'Invalid upload path')
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
if (!name) throw new UploadError(400, 'Invalid file name')
|
||||||
|
const key = name.toLowerCase()
|
||||||
|
if (seen.has(key)) throw new UploadError(409, UPLOAD_DUPLICATE_FILENAME_MESSAGE, UPLOAD_ERROR_CODE.duplicateFileName)
|
||||||
|
seen.add(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports.assertUploadDestination = assertUploadDestination
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/filesystem/pathexists. `directory` is the client path relative to the library folder.
|
||||||
|
*
|
||||||
|
* @param {string} folderPath
|
||||||
|
* @param {string} directory
|
||||||
|
* @returns {Promise<{ exists: boolean, libraryItemTitle?: string }>}
|
||||||
|
*/
|
||||||
|
async function checkUploadDirectory(folderPath, directory) {
|
||||||
|
return lookupUploadDirectory(folderPath, Path.join(folderPath, directory))
|
||||||
|
}
|
||||||
|
module.exports.checkUploadDirectory = checkUploadDirectory
|
||||||
|
|
||||||
|
const NOT_WRITABLE_CODES = ['EACCES', 'EPERM', 'EROFS']
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Permission errors from mkdir or move. Null for every other failure.
|
||||||
|
*
|
||||||
|
* @param {NodeJS.ErrnoException} error
|
||||||
|
* @returns {UploadError | null}
|
||||||
|
*/
|
||||||
|
function notWritableUploadError(error) {
|
||||||
|
if (!error || !NOT_WRITABLE_CODES.includes(error.code)) return null
|
||||||
|
return new UploadError(403, UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE, UPLOAD_ERROR_CODE.folderNotWritable)
|
||||||
|
}
|
||||||
|
module.exports.notWritableUploadError = notWritableUploadError
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the upload directory. Returns the first parent this call created, or null when
|
||||||
|
* every parent already existed. The leaf mkdir is not recursive: an existing directory
|
||||||
|
* would count as success, and a later failure would delete it.
|
||||||
|
*
|
||||||
|
* @param {string} outputDirectory
|
||||||
|
* @returns {Promise<string | null>}
|
||||||
|
*/
|
||||||
|
async function createUploadDirectory(outputDirectory) {
|
||||||
|
let firstCreated = null
|
||||||
|
try {
|
||||||
|
firstCreated = (await fs.mkdir(Path.dirname(outputDirectory), { recursive: true })) || null
|
||||||
|
await fs.mkdir(outputDirectory)
|
||||||
|
} catch (error) {
|
||||||
|
if (firstCreated) await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated)
|
||||||
|
// An existing directory is EEXIST. A parent segment that is a file is ENOTDIR on Linux and macOS, and EEXIST on Windows.
|
||||||
|
if (error.code === 'EEXIST' || error.code === 'ENOTDIR') {
|
||||||
|
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||||
|
}
|
||||||
|
const notWritable = notWritableUploadError(error)
|
||||||
|
if (notWritable) throw notWritable
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
return firstCreated
|
||||||
|
}
|
||||||
|
module.exports.createUploadDirectory = createUploadDirectory
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove empty directories this request created, from deepest up through firstCreated.
|
||||||
|
* Directories that already existed are left alone, including empty ones.
|
||||||
|
*
|
||||||
|
* @param {string} deepest
|
||||||
|
* @param {string} firstCreated
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async function removeEmptyCreatedDirectories(deepest, firstCreated) {
|
||||||
|
if (!firstCreated) return
|
||||||
|
let current = deepest
|
||||||
|
while (isSameOrSubPath(firstCreated, current)) {
|
||||||
|
let names
|
||||||
|
try {
|
||||||
|
names = await fs.readdir(current)
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') return
|
||||||
|
Logger.error('[uploadPath] Failed to read upload directory during rollback', current, error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (names.length) return
|
||||||
|
try {
|
||||||
|
await fs.rmdir(current)
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'ENOENT') {
|
||||||
|
Logger.error('[uploadPath] Failed to remove upload directory', current, error)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
current = Path.dirname(current)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the item directory this request created, then empty parents this request created.
|
||||||
|
* firstCreated is the return value of createUploadDirectory.
|
||||||
|
* Unmoved temp files are deleted by the multipart parser when the response closes.
|
||||||
|
*
|
||||||
|
* @param {string} outputDirectory
|
||||||
|
* @param {string | null} firstCreated
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated)
|
||||||
|
}
|
||||||
|
module.exports.rollbackFailedUpload = rollbackFailedUpload
|
||||||
@@ -0,0 +1,785 @@
|
|||||||
|
const { expect } = require('chai')
|
||||||
|
const { Sequelize } = require('sequelize')
|
||||||
|
const sinon = require('sinon')
|
||||||
|
const os = require('os')
|
||||||
|
const Path = require('path')
|
||||||
|
const fs = require('fs/promises')
|
||||||
|
const fsExtra = require('../../../server/libs/fsExtra')
|
||||||
|
|
||||||
|
const Database = require('../../../server/Database')
|
||||||
|
const MiscController = require('../../../server/controllers/MiscController')
|
||||||
|
const FileSystemController = require('../../../server/controllers/FileSystemController')
|
||||||
|
const Logger = require('../../../server/Logger')
|
||||||
|
const uploadPath = require('../../../server/utils/uploadPath')
|
||||||
|
const fileUtils = require('../../../server/utils/fileUtils')
|
||||||
|
const { filePathToPOSIX } = fileUtils
|
||||||
|
|
||||||
|
describe('upload path collisions', () => {
|
||||||
|
/** @type {string} */
|
||||||
|
let root
|
||||||
|
/** @type {import('../../../server/models/Library')} */
|
||||||
|
let library
|
||||||
|
/** @type {import('../../../server/models/LibraryFolder')} */
|
||||||
|
let folder
|
||||||
|
|
||||||
|
const uploadUser = {
|
||||||
|
username: 'uploader',
|
||||||
|
canUpload: true,
|
||||||
|
canUpdate: false,
|
||||||
|
canDelete: false,
|
||||||
|
checkCanAccessLibrary: () => true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pathExists(targetPath) {
|
||||||
|
try {
|
||||||
|
await fs.access(targetPath)
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findNusqlite3Extension() {
|
||||||
|
const ext = process.platform === 'win32' ? '.dll' : process.platform === 'darwin' ? '.dylib' : '.so'
|
||||||
|
const candidates = [process.env.NUSQLITE3_PATH, Path.resolve(process.cwd(), `libnusqlite3${ext}`)].filter(Boolean)
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
if (await pathExists(candidate)) return candidate
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockRes() {
|
||||||
|
return {
|
||||||
|
statusCode: 200,
|
||||||
|
body: undefined,
|
||||||
|
status(code) {
|
||||||
|
this.statusCode = code
|
||||||
|
return this
|
||||||
|
},
|
||||||
|
send(body) {
|
||||||
|
this.body = body
|
||||||
|
return this
|
||||||
|
},
|
||||||
|
sendStatus(code) {
|
||||||
|
this.statusCode = code
|
||||||
|
return this
|
||||||
|
},
|
||||||
|
json(body) {
|
||||||
|
this.body = body
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} name
|
||||||
|
* @param {string} contents
|
||||||
|
* @param {{ fail?: boolean, failCode?: string }} [options]
|
||||||
|
*/
|
||||||
|
function fakeUploadFile(name, contents, options = {}) {
|
||||||
|
const tempFilePath = Path.join(root, `tmp-${name}-${Math.random().toString(16).slice(2)}`)
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
tempFilePath,
|
||||||
|
contents,
|
||||||
|
async mv(destination) {
|
||||||
|
if (options.fail) {
|
||||||
|
const error = new Error('mv failed')
|
||||||
|
if (options.failCode) error.code = options.failCode
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
await fs.writeFile(destination, contents)
|
||||||
|
await fs.rm(tempFilePath, { force: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} [overrides]
|
||||||
|
*/
|
||||||
|
function uploadRequest(overrides = {}) {
|
||||||
|
return {
|
||||||
|
user: uploadUser,
|
||||||
|
files: {
|
||||||
|
0: fakeUploadFile('01.mp3', 'new-audio')
|
||||||
|
},
|
||||||
|
body: {
|
||||||
|
title: 'Book B',
|
||||||
|
author: 'Author A',
|
||||||
|
series: '',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
},
|
||||||
|
...overrides
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
global.isWin = process.platform === 'win32'
|
||||||
|
global.ServerSettings = {}
|
||||||
|
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||||
|
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||||
|
await Database.buildModels()
|
||||||
|
|
||||||
|
sinon.stub(Logger, 'info')
|
||||||
|
sinon.stub(Logger, 'warn')
|
||||||
|
sinon.stub(Logger, 'error')
|
||||||
|
sinon.stub(Logger, 'debug')
|
||||||
|
|
||||||
|
root = await fs.mkdtemp(Path.join(os.tmpdir(), 'abs-upload-'))
|
||||||
|
const folderPath = Path.join(root, 'library')
|
||||||
|
await fs.mkdir(folderPath)
|
||||||
|
|
||||||
|
library = await Database.libraryModel.create({ name: 'Test Library', mediaType: 'book' })
|
||||||
|
folder = await Database.libraryFolderModel.create({ path: folderPath, libraryId: library.id })
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
sinon.restore()
|
||||||
|
if (root) {
|
||||||
|
await fs.rm(root, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
await Database.sequelize.close()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('writes a new item when the destination does not exist', async () => {
|
||||||
|
const file = fakeUploadFile('01.mp3', 'new-audio')
|
||||||
|
const req = uploadRequest({ files: { 0: file } })
|
||||||
|
const res = mockRes()
|
||||||
|
|
||||||
|
await MiscController.handleUpload(req, res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(200)
|
||||||
|
const destination = Path.join(folder.path, 'Author A', 'Book B', '01.mp3')
|
||||||
|
expect(await fs.readFile(destination, 'utf8')).to.equal('new-audio')
|
||||||
|
expect(await pathExists(file.tempFilePath)).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses when the destination directory already exists 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)
|
||||||
|
|
||||||
|
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')
|
||||||
|
})
|
||||||
|
|
||||||
|
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')
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest(), 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(authorFile, 'utf8')).to.equal('not-a-directory')
|
||||||
|
expect(await pathExists(Path.join(folder.path, 'Author A', 'Book B'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not delete an existing item when the upload check throws', 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')
|
||||||
|
sinon.stub(uploadPath, 'assertUploadDestination').rejects(new Error('database unavailable'))
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest(), res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
expect(await fs.readFile(existing, 'utf8')).to.equal('original')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not delete an existing item when the directory appears before it is created', 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')
|
||||||
|
sinon.stub(uploadPath, 'assertUploadDestination').resolves()
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest(), 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')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses an upload nested inside an existing library item', async () => {
|
||||||
|
const parentPath = filePathToPOSIX(Path.join(folder.path, 'Author A', 'Book B'))
|
||||||
|
await Database.libraryItemModel.create({
|
||||||
|
path: parentPath,
|
||||||
|
title: 'Book B',
|
||||||
|
mediaType: 'book',
|
||||||
|
libraryFiles: [],
|
||||||
|
libraryId: library.id,
|
||||||
|
libraryFolderId: folder.id
|
||||||
|
})
|
||||||
|
|
||||||
|
const req = uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: 'Sequel',
|
||||||
|
author: 'Author A',
|
||||||
|
series: 'Book B',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(req, 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(folder.path, 'Author A', 'Book B', 'Sequel'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses an upload nested in a library item whose name starts with two dots', async () => {
|
||||||
|
const parentPath = filePathToPOSIX(Path.join(folder.path, '..foo'))
|
||||||
|
await Database.libraryItemModel.create({
|
||||||
|
path: parentPath,
|
||||||
|
title: 'Dot Book',
|
||||||
|
mediaType: 'book',
|
||||||
|
libraryFiles: [],
|
||||||
|
libraryId: library.id,
|
||||||
|
libraryFolderId: folder.id
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(
|
||||||
|
uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: 'Sequel',
|
||||||
|
author: '..foo',
|
||||||
|
series: '',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(409)
|
||||||
|
expect(res.body).to.deep.equal({
|
||||||
|
code: uploadPath.UPLOAD_ERROR_CODE.libraryItemExists,
|
||||||
|
libraryItemTitle: 'Dot Book',
|
||||||
|
error: `${uploadPath.UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}Dot Book`
|
||||||
|
})
|
||||||
|
expect(await pathExists(Path.join(folder.path, '..foo', 'Sequel'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses an upload nested in a library item that differs only by case', async () => {
|
||||||
|
global.isWin = true
|
||||||
|
const parentPath = filePathToPOSIX(Path.join(folder.path, 'Author A', 'Book B'))
|
||||||
|
await Database.libraryItemModel.create({
|
||||||
|
path: parentPath,
|
||||||
|
title: 'Book B',
|
||||||
|
mediaType: 'book',
|
||||||
|
libraryFiles: [],
|
||||||
|
libraryId: library.id,
|
||||||
|
libraryFolderId: folder.id
|
||||||
|
})
|
||||||
|
|
||||||
|
const req = uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: 'Sequel',
|
||||||
|
author: 'author a',
|
||||||
|
series: 'book b',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(req, 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(folder.path, 'author a', 'book b', 'Sequel'))).to.equal(false)
|
||||||
|
|
||||||
|
const pathExistsRes = mockRes()
|
||||||
|
await FileSystemController.checkPathExists(
|
||||||
|
{
|
||||||
|
user: uploadUser,
|
||||||
|
body: {
|
||||||
|
directory: Path.join('author a', 'book b', 'Sequel'),
|
||||||
|
folderPath: folder.path
|
||||||
|
}
|
||||||
|
},
|
||||||
|
pathExistsRes
|
||||||
|
)
|
||||||
|
expect(pathExistsRes.body).to.deep.equal({
|
||||||
|
exists: true,
|
||||||
|
libraryItemTitle: 'Book B'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('writes a podcast under the title and ignores author and series', async () => {
|
||||||
|
await library.update({ mediaType: 'podcast' })
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(
|
||||||
|
uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: 'Show A',
|
||||||
|
author: 'Ignored Author',
|
||||||
|
series: 'Ignored Series',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(200)
|
||||||
|
expect(await fs.readFile(Path.join(folder.path, 'Show A', '01.mp3'), 'utf8')).to.equal('new-audio')
|
||||||
|
expect(await pathExists(Path.join(folder.path, 'Ignored Author'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pathexists rejects a directory that leaves the library folder', async () => {
|
||||||
|
const res = mockRes()
|
||||||
|
await FileSystemController.checkPathExists(
|
||||||
|
{
|
||||||
|
user: uploadUser,
|
||||||
|
body: {
|
||||||
|
directory: '../outside',
|
||||||
|
folderPath: folder.path
|
||||||
|
}
|
||||||
|
},
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(400)
|
||||||
|
expect(await pathExists(Path.join(folder.path, '..', 'outside'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('matches non-ASCII parent library item paths even without libnusqlite3 loaded', async () => {
|
||||||
|
global.isWin = true
|
||||||
|
const parentPath = filePathToPOSIX(Path.join(folder.path, 'Émile Zola', 'Germinal'))
|
||||||
|
await Database.libraryItemModel.create({
|
||||||
|
path: parentPath,
|
||||||
|
title: 'Germinal',
|
||||||
|
mediaType: 'book',
|
||||||
|
libraryFiles: [],
|
||||||
|
libraryId: library.id,
|
||||||
|
libraryFolderId: folder.id
|
||||||
|
})
|
||||||
|
|
||||||
|
const req = uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: 'Sequel',
|
||||||
|
author: 'Émile Zola',
|
||||||
|
series: 'Germinal',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(req, res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(409)
|
||||||
|
expect(res.body).to.deep.equal({
|
||||||
|
code: uploadPath.UPLOAD_ERROR_CODE.libraryItemExists,
|
||||||
|
libraryItemTitle: 'Germinal',
|
||||||
|
error: `${uploadPath.UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}Germinal`
|
||||||
|
})
|
||||||
|
expect(await pathExists(Path.join(folder.path, 'Émile Zola', 'Germinal', 'Sequel'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a different-case non-ASCII upload when libnusqlite3 is loaded', async function () {
|
||||||
|
const extensionPath = await findNusqlite3Extension()
|
||||||
|
if (!extensionPath) {
|
||||||
|
if (process.env.CI || process.env.NUSQLITE3_PATH) {
|
||||||
|
throw new Error('libnusqlite3 extension not found')
|
||||||
|
}
|
||||||
|
this.skip()
|
||||||
|
}
|
||||||
|
await Database.loadExtension(extensionPath)
|
||||||
|
|
||||||
|
global.isWin = true
|
||||||
|
const parentPath = filePathToPOSIX(Path.join(folder.path, 'Émile Zola', 'Germinal'))
|
||||||
|
await Database.libraryItemModel.create({
|
||||||
|
path: parentPath,
|
||||||
|
title: 'Germinal',
|
||||||
|
mediaType: 'book',
|
||||||
|
libraryFiles: [],
|
||||||
|
libraryId: library.id,
|
||||||
|
libraryFolderId: folder.id
|
||||||
|
})
|
||||||
|
|
||||||
|
const req = uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: 'Sequel',
|
||||||
|
author: 'émile zola',
|
||||||
|
series: 'germinal',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(req, res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(409)
|
||||||
|
expect(res.body).to.deep.equal({
|
||||||
|
code: uploadPath.UPLOAD_ERROR_CODE.libraryItemExists,
|
||||||
|
libraryItemTitle: 'Germinal',
|
||||||
|
error: `${uploadPath.UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}Germinal`
|
||||||
|
})
|
||||||
|
expect(await pathExists(Path.join(folder.path, 'émile zola', 'germinal', 'Sequel'))).to.equal(false)
|
||||||
|
|
||||||
|
const pathExistsRes = mockRes()
|
||||||
|
await FileSystemController.checkPathExists(
|
||||||
|
{
|
||||||
|
user: uploadUser,
|
||||||
|
body: {
|
||||||
|
directory: Path.join('émile zola', 'germinal', 'Sequel'),
|
||||||
|
folderPath: folder.path
|
||||||
|
}
|
||||||
|
},
|
||||||
|
pathExistsRes
|
||||||
|
)
|
||||||
|
expect(pathExistsRes.body).to.deep.equal({
|
||||||
|
exists: true,
|
||||||
|
libraryItemTitle: 'Germinal'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows a different-case path when the filesystem is case-sensitive', async function () {
|
||||||
|
// Windows and macOS compare case-insensitively. Flipping global.isWin here would also
|
||||||
|
// switch path checks to POSIX rules, which do not apply to a Windows path.
|
||||||
|
if (process.platform === 'win32' || process.platform === 'darwin') {
|
||||||
|
this.skip()
|
||||||
|
}
|
||||||
|
const parentPath = filePathToPOSIX(Path.join(folder.path, 'Author A', 'Book B'))
|
||||||
|
await Database.libraryItemModel.create({
|
||||||
|
path: parentPath,
|
||||||
|
title: 'Book B',
|
||||||
|
mediaType: 'book',
|
||||||
|
libraryFiles: [],
|
||||||
|
libraryId: library.id,
|
||||||
|
libraryFolderId: folder.id
|
||||||
|
})
|
||||||
|
|
||||||
|
const req = uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: 'Sequel',
|
||||||
|
author: 'author a',
|
||||||
|
series: 'book b',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(req, res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(200)
|
||||||
|
expect(await fs.readFile(Path.join(folder.path, 'author a', 'book b', 'Sequel', '01.mp3'), 'utf8')).to.equal('new-audio')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses duplicate file names in one request', async () => {
|
||||||
|
const req = uploadRequest({
|
||||||
|
files: {
|
||||||
|
0: fakeUploadFile('01.mp3', 'a'),
|
||||||
|
1: fakeUploadFile('01.MP3', 'b')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(req, res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(409)
|
||||||
|
expect(res.body).to.deep.equal({
|
||||||
|
code: uploadPath.UPLOAD_ERROR_CODE.duplicateFileName,
|
||||||
|
error: uploadPath.UPLOAD_DUPLICATE_FILENAME_MESSAGE
|
||||||
|
})
|
||||||
|
expect(await pathExists(Path.join(folder.path, 'Author A', 'Book B'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a title that sanitizes to an empty directory name', async () => {
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(
|
||||||
|
uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: '...',
|
||||||
|
author: 'NewAuthor',
|
||||||
|
series: '',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(400)
|
||||||
|
expect(res.body).to.equal('Invalid upload path')
|
||||||
|
expect(await pathExists(Path.join(folder.path, 'NewAuthor'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops an author name that sanitizes to empty', async () => {
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(
|
||||||
|
uploadRequest({
|
||||||
|
body: {
|
||||||
|
title: 'Book B',
|
||||||
|
author: '...',
|
||||||
|
series: '',
|
||||||
|
library: library.id,
|
||||||
|
folder: folder.id
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(200)
|
||||||
|
const destination = Path.join(folder.path, 'Book B', '01.mp3')
|
||||||
|
expect(await fs.readFile(destination, 'utf8')).to.equal('new-audio')
|
||||||
|
expect(await pathExists(Path.join(folder.path, '...'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not let an upload-only user 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')
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest(), res)
|
||||||
|
|
||||||
|
expect(uploadUser.canUpdate).to.equal(false)
|
||||||
|
expect(uploadUser.canDelete).to.equal(false)
|
||||||
|
expect(res.statusCode).to.equal(409)
|
||||||
|
expect(await fs.readFile(Path.join(destinationDir, '01.mp3'), 'utf8')).to.equal('original')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('removes partial files when a move fails and does not answer 200', async () => {
|
||||||
|
const first = fakeUploadFile('01.mp3', 'first')
|
||||||
|
const second = fakeUploadFile('02.mp3', 'second', { fail: true })
|
||||||
|
await fs.writeFile(second.tempFilePath, 'second')
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(
|
||||||
|
uploadRequest({
|
||||||
|
files: { 0: first, 1: second }
|
||||||
|
}),
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
const outputDirectory = Path.join(folder.path, 'Author A', 'Book B')
|
||||||
|
expect(await pathExists(outputDirectory)).to.equal(false)
|
||||||
|
expect(await pathExists(Path.join(folder.path, 'Author A'))).to.equal(false)
|
||||||
|
expect(await pathExists(second.tempFilePath)).to.equal(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a pre-existing empty parent when a move fails', async () => {
|
||||||
|
const authorDir = Path.join(folder.path, 'Author A')
|
||||||
|
await fs.mkdir(authorDir)
|
||||||
|
const file = fakeUploadFile('01.mp3', 'new-audio', { fail: true })
|
||||||
|
await fs.writeFile(file.tempFilePath, 'new-audio')
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest({ files: { 0: file } }), res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
expect(await pathExists(authorDir)).to.equal(true)
|
||||||
|
expect(await pathExists(Path.join(authorDir, 'Book B'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a pre-existing empty directory when the upload check throws', async () => {
|
||||||
|
const authorDir = Path.join(folder.path, 'Author A')
|
||||||
|
await fs.mkdir(authorDir)
|
||||||
|
sinon.stub(uploadPath, 'assertUploadDestination').rejects(new Error('database unavailable'))
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest(), res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
expect(await pathExists(authorDir)).to.equal(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the library folder when its path has a trailing separator and a move fails', async () => {
|
||||||
|
const folderWithSeparator = folder.path.endsWith(Path.sep) ? folder.path : folder.path + Path.sep
|
||||||
|
await folder.update({ path: folderWithSeparator })
|
||||||
|
|
||||||
|
const first = fakeUploadFile('01.mp3', 'first')
|
||||||
|
const second = fakeUploadFile('02.mp3', 'second', { fail: true })
|
||||||
|
await fs.writeFile(second.tempFilePath, 'second')
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(
|
||||||
|
uploadRequest({
|
||||||
|
files: { 0: first, 1: second }
|
||||||
|
}),
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
expect(await pathExists(folderWithSeparator)).to.equal(true)
|
||||||
|
expect(await pathExists(Path.join(folderWithSeparator, 'Author A'))).to.equal(false)
|
||||||
|
expect(await pathExists(second.tempFilePath)).to.equal(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a pre-existing empty parent when the library folder path has a trailing separator', async () => {
|
||||||
|
const folderWithSeparator = folder.path.endsWith(Path.sep) ? folder.path : folder.path + Path.sep
|
||||||
|
await folder.update({ path: folderWithSeparator })
|
||||||
|
const authorDir = Path.join(folderWithSeparator, 'Author A')
|
||||||
|
await fs.mkdir(authorDir)
|
||||||
|
const file = fakeUploadFile('01.mp3', 'new-audio', { fail: true })
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest({ files: { 0: file } }), res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
expect(await pathExists(folderWithSeparator)).to.equal(true)
|
||||||
|
expect(await pathExists(authorDir)).to.equal(true)
|
||||||
|
expect(await pathExists(Path.join(authorDir, 'Book B'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 403 when the library folder is not writable', async () => {
|
||||||
|
const mkdirError = new Error('permission denied')
|
||||||
|
mkdirError.code = 'EACCES'
|
||||||
|
sinon.stub(fsExtra, 'mkdir').rejects(mkdirError)
|
||||||
|
const res = mockRes()
|
||||||
|
|
||||||
|
await MiscController.handleUpload(uploadRequest(), 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 pathExists(Path.join(folder.path, 'Author A'))).to.equal(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 403 when a move is denied and removes the new directory', async () => {
|
||||||
|
const file = fakeUploadFile('01.mp3', 'new-audio', { fail: true, failCode: 'EPERM' })
|
||||||
|
await fs.writeFile(file.tempFilePath, 'new-audio')
|
||||||
|
const res = mockRes()
|
||||||
|
|
||||||
|
await MiscController.handleUpload(uploadRequest({ 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 pathExists(Path.join(folder.path, 'Author A', 'Book B'))).to.equal(false)
|
||||||
|
expect(await pathExists(folder.path)).to.equal(true)
|
||||||
|
expect(await pathExists(file.tempFilePath)).to.equal(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pathexists reports a library item that already uses a parent directory', async () => {
|
||||||
|
const parentPath = filePathToPOSIX(Path.join(folder.path, 'Author A', 'Book B'))
|
||||||
|
await Database.libraryItemModel.create({
|
||||||
|
path: parentPath,
|
||||||
|
title: 'Book B',
|
||||||
|
mediaType: 'book',
|
||||||
|
libraryFiles: [],
|
||||||
|
libraryId: library.id,
|
||||||
|
libraryFolderId: folder.id
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await FileSystemController.checkPathExists(
|
||||||
|
{
|
||||||
|
user: uploadUser,
|
||||||
|
body: {
|
||||||
|
directory: Path.join('Author A', 'Book B', 'Sequel'),
|
||||||
|
folderPath: folder.path
|
||||||
|
}
|
||||||
|
},
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.body).to.deep.equal({
|
||||||
|
exists: true,
|
||||||
|
libraryItemTitle: 'Book B'
|
||||||
|
})
|
||||||
|
|
||||||
|
const slashRes = mockRes()
|
||||||
|
await FileSystemController.checkPathExists(
|
||||||
|
{
|
||||||
|
user: uploadUser,
|
||||||
|
body: {
|
||||||
|
directory: 'Author A/Book B/Sequel',
|
||||||
|
folderPath: folder.path
|
||||||
|
}
|
||||||
|
},
|
||||||
|
slashRes
|
||||||
|
)
|
||||||
|
expect(slashRes.body).to.deep.equal({
|
||||||
|
exists: true,
|
||||||
|
libraryItemTitle: 'Book B'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 500 when pathexists fails unexpectedly', async () => {
|
||||||
|
sinon.stub(Database.libraryItemModel, 'findOne').rejects(new Error('database unavailable'))
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await FileSystemController.checkPathExists(
|
||||||
|
{
|
||||||
|
user: uploadUser,
|
||||||
|
body: {
|
||||||
|
directory: Path.join('Author A', 'Book B', 'Sequel'),
|
||||||
|
folderPath: folder.path
|
||||||
|
}
|
||||||
|
},
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 400 when a file field is an empty list', async () => {
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest({ files: { 0: [] } }), res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(400)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 500 when the library lookup fails', async () => {
|
||||||
|
sinon.stub(Database.libraryModel, 'findByIdWithFolders').rejects(new Error('database unavailable'))
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await MiscController.handleUpload(uploadRequest(), res)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 500 when the pathexists folder lookup fails', async () => {
|
||||||
|
sinon.stub(Database.libraryFolderModel, 'findOne').rejects(new Error('database unavailable'))
|
||||||
|
|
||||||
|
const res = mockRes()
|
||||||
|
await FileSystemController.checkPathExists(
|
||||||
|
{
|
||||||
|
user: uploadUser,
|
||||||
|
body: {
|
||||||
|
directory: Path.join('Author A', 'Book B'),
|
||||||
|
folderPath: folder.path
|
||||||
|
}
|
||||||
|
},
|
||||||
|
res
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.statusCode).to.equal(500)
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in new issue
Block a user