Snyk помечает код как уязвимость при обходе пути, но код, похоже, в порядке

In my django python application I have such functions:



def get_sanitized_file_path(file_path: str) -> Path:    
    ALLOWED_BASE_DIR = Path(settings.MEDIA_ROOT).resolve()
    if not file_path:
        raise SuspiciousOperation("No file path provided")

    try:
        file_path = os.path.normpath(file_path)

        if ".." in file_path:
            raise SuspiciousOperation("Path traversal attempt detected")

        # Security: Prevent path traversal - this will raise ValueError if outside MEDIA_ROOT
        request_path = Path(file_path).resolve()
        request_path.relative_to(ALLOWED_BASE_DIR)

        if not request_path.exists():
            raise FileNotFoundError("File not found")
        if not request_path.is_file():
            raise SuspiciousOperation("Path is not a regular file")

        return request_path

    except (ValueError, OSError, PermissionError) as e:
        raise SuspiciousOperation(f"File access error: {e}")


def load_file(file_path):
    file_path = get_sanitized_file_path(file_path)
    if not file_path:
        raise exceptions.FileNotFoundException
    if not os.path.exists(file_path):
        raise exceptions.FileNotFoundException
    try:
        with open(file_path, "rb") as file:
            file_data = io.BytesIO(file.read())
    except Exception as e:
        raise exceptions.FileReadError from e
    return file_data




def render_file(file_path, filename=None, content_type="application/pdf"):
    file_data = load_file(file_path)
    filename = filename or file_util.get_filename(file_path)
    return render_response(file_data, filename, content_type)


def render_response(file_data, filename, content_type="application/pdf"):
    response = FileResponse(file_data, content_type=content_type, as_attachment=True, filename=filename)
    set_response_props(response, filename)
    return response

и где-то в моем коде я вызываю функцию render_file:

file_path  = get_file_path() # returns a posix path
file_path = get_sanitized_file_path(file_path)
render_file(file_path) # gets flagged by snyk


Несмотря на то, что я очищаю свой путь к файлу как перед вызовом метода, так и внутри вызываемого метода, код Snyk по-прежнему помечает строку render_file(file_path) как уязвимость для обхода пути.

Вернуться на верх