fix: validation of upload filename

This commit is contained in:
Ben Irvin 2024-04-03 09:13:44 +02:00 committed by GitHub
parent 971168147b
commit 791bc2c971
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -81,6 +81,31 @@ export default ({ strapi }: { strapi: Core.Strapi }) => {
return tmpWorkingDirectory;
};
function filenameReservedRegex() {
// eslint-disable-next-line no-control-regex
return /[<>:"/\\|?*\u0000-\u001F]/g;
}
function windowsReservedNameRegex() {
return /^(con|prn|aux|nul|com\d|lpt\d)$/i;
}
/**
* Copied from https://github.com/sindresorhus/valid-filename package
*/
function isValidFilename(string: string) {
if (!string || string.length > 255) {
return false;
}
if (filenameReservedRegex().test(string) || windowsReservedNameRegex().test(string)) {
return false;
}
if (string === '.' || string === '..') {
return false;
}
return true;
}
async function emitEvent(event: string, data: Record<string, any>) {
const modelDef = strapi.getModel(FILE_MODEL_UID);
const sanitizedData = await sanitize.sanitizers.defaultSanitizeOutput(
@ -109,6 +134,10 @@ export default ({ strapi }: { strapi: Core.Strapi }) => {
): Promise<Omit<UploadableFile, 'getStream'>> {
const fileService = getService('file');
if (!isValidFilename(filename)) {
throw new ApplicationError('File name contains invalid characters');
}
let ext = path.extname(filename);
if (!ext) {
ext = `.${extension(type)}`;
@ -116,6 +145,11 @@ export default ({ strapi }: { strapi: Core.Strapi }) => {
const usedName = (fileInfo.name || filename).normalize();
const basename = path.basename(usedName, ext);
// Prevent null characters in file name
if (!isValidFilename(filename)) {
throw new ApplicationError('File name contains invalid characters');
}
const entity: Omit<UploadableFile, 'getStream'> = {
name: usedName,
alternativeText: fileInfo.alternativeText,