fix: Potential fix for code scanning alert no. 75: Uncontrolled data used in path expression#421
Conversation
…in path expression Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
src/server/routers/ingest.py
Outdated
| """ | ||
| # Normalize and validate the directory path | ||
| directory = TMP_BASE_PATH / ingest_id | ||
| directory = directory.resolve() |
Check failure
Code scanning / CodeQL
Uncontrolled data used in path expression High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI 8 months ago
To fix the issue, we need to ensure that the constructed path (directory) is normalized and validated against the base directory (TMP_BASE_PATH) after normalization. This involves using os.path.realpath or pathlib.Path.resolve() to normalize the path and then verifying that the normalized path starts with the base directory. This ensures that even if the user provides a malicious ingest_id value, the resulting path cannot escape the intended directory.
Steps to implement the fix:
- Normalize the path using
directory.resolve(). - Validate that the normalized path starts with the base directory (
TMP_BASE_PATH) usingstartswith. - Raise an appropriate HTTP exception if the validation fails.
| @@ -116,3 +116,6 @@ | ||
| directory = TMP_BASE_PATH / ingest_id | ||
| directory = directory.resolve() | ||
| try: | ||
| directory = directory.resolve(strict=True) | ||
| except FileNotFoundError: | ||
| raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Digest {ingest_id!r} not found") | ||
| if not str(directory).startswith(str(TMP_BASE_PATH)): |
There was a problem hiding this comment.
Pull Request Overview
This PR addresses a security vulnerability (code scanning alert no. 75) related to uncontrolled data used in path expressions by implementing path validation and sanitization for the download_ingest endpoint.
- Adds path traversal protection by resolving the directory path and validating it stays within the intended base directory
- Implements security check to prevent directory traversal attacks through malicious
ingest_idparameters - Raises a 403 Forbidden error when path validation fails
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Potential fix for https://github.com/coderamp-labs/gitingest/security/code-scanning/75
To fix this issue, we need to validate and sanitize the
directorypath constructed fromingest_id. This can be done by:os.path.normpathto eliminate any path traversal elements (e.g.,../).TMP_BASE_PATH) by checking that it starts with the absolute path ofTMP_BASE_PATH.This approach ensures that user-provided input cannot escape the boundaries of the intended directory structure.
Suggested fixes powered by Copilot Autofix. Review carefully before merging.