From 372a462d522a5af71544f2d9bb2e514e91b4b168 Mon Sep 17 00:00:00 2001 From: Shad Date: Tue, 14 Jan 2025 13:49:04 +0530 Subject: [PATCH] Fix code scanning alert no. 49: Uncontrolled data used in path expression Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- src/pages/api/v1/course/update.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/pages/api/v1/course/update.ts b/src/pages/api/v1/course/update.ts index bdbb5391..11e8625a 100644 --- a/src/pages/api/v1/course/update.ts +++ b/src/pages/api/v1/course/update.ts @@ -5,6 +5,7 @@ import { withMethods } from "@/lib/api-middlewares/with-method"; import { withUserAuthorized } from "@/lib/api-middlewares/with-authorized"; import { createSlug, getFileExtension } from "@/lib/utils"; import fs from "fs"; +import path from "path"; import { APIResponse } from "@/types/apis"; import { readFieldWithSingleFile } from "@/lib/upload/utils"; import { ContentManagementService } from "@/services/cms/ContentManagementService"; @@ -59,8 +60,12 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => { } const extension = getFileExtension(files.file[0].originalFilename); - const sourcePath = files.file[0].filepath; - const fileBuffer = await fs.promises.readFile(`${sourcePath}`); + const sourcePath = path.resolve(files.file[0].filepath); + const safeDir = path.resolve("/var/www/uploads"); // Replace with your safe directory + if (!sourcePath.startsWith(safeDir)) { + throw new Error("Invalid file path"); + } + const fileBuffer = await fs.promises.readFile(sourcePath); //now upload the image const newThumbnailResponse = await cms.uploadVideoThumbnail( cmsConfig,