[Python] Snyk flags code as path traversal vulnerability but the code seems ok

Discussão em 'Python' iniciado por Stack, Agosto 13, 2025.

  1. Stack

    Stack Membro Participativo

    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


    and somewhere in my code I calling the render_file function:

    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




    Even though I'm sanitizing my file path both before calling the method and inside the method called, Snyk code still flags the line render_file(file_path) as a path traversal vulnerability.

    Continue reading...

Compartilhe esta Página