fix(security): prevent path traversal in ocr_service filename handling with sanitization and path verification - #3959
Conversation
…g with sanitization and path verification
|
@Aryanbansal-05 is attempting to deploy a commit to the ritesh Team on Vercel. A member of the Team first needs to authorize it. |
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🔐 Summary
Resolves #3948 by adding strict filename sanitization and path verification to
backend/services/ocr_service.py, preventing path traversal attacks (CWE-22) where user-supplied filenames containing../, NULL bytes, or absolute paths could be used to read arbitrary server files.🛠️ Changes Made
backend/services/ocr_service.pyAdded two security utility functions:
_sanitize_filename(filename)\x00)..traversal sequences/or\prefix)os.path.basename()only — strips all directory componentsValueErrorfor any invalid input_verify_safe_path(base_dir, filename)os.path.realpath()to follow symlinksbase_dirusingos.path.commonpath()ValueErrorif path escapes the upload directoryprocess_document()updated:filenameparameter now sanitized via_sanitize_filename()before use{"success": False, "error": "Invalid filename: ..."}on traversal attemptsbackend/tests/test_path_traversal.py— New Security Regression Tests3 test classes, 18 test cases:
TestSanitizeFilename— traversal sequences, NULL bytes, absolute paths, empty inputsTestVerifySafePath— symlink escape, path escape, valid path resolutionTestProcessDocumentFilenameValidation— integration tests viaprocess_document()✅ Security Issues Fixed
../../etc/passwdtraversal rejected with 400-equivalent errorfile\x00.pdf) rejectedrealpath()Closes #3948