44import sys
55import traceback
66from logging import getLogger
7- from os import path
87from pathlib import Path
98from typing import Optional , Type , Union
109
@@ -71,14 +70,14 @@ def validate_and_sanitise(
7170 """
7271
7372 # Resolve symlinks and directory changes to get full file path
74- full_path = path . normpath ( path . realpath ( file ))
73+ full_path = Path ( file ). resolve ( )
7574
75+ # Use machine configuration to validate which file base paths are accepted from
7676 instrument_name = (
7777 db .exec (select (MurfeySession ).where (MurfeySession .id == session_id ))
7878 .one ()
7979 .instrument_name
8080 )
81- # Use machine configuration to validate file paths used here
8281 machine_config = get_machine_config (instrument_name = instrument_name )[
8382 instrument_name
8483 ]
@@ -89,6 +88,8 @@ def validate_and_sanitise(
8988 # Print to troubleshoot
9089 logger .warning (f"Base path { rsync_basepath !r} is too short" )
9190 base_path = rsync_basepath .as_posix ()
91+ except Exception :
92+ raise Exception ("Unexpected exception occurred when loading the file base path" )
9293
9394 # Check that full file path doesn't contain unallowed characters
9495 # Currently allows only:
@@ -97,18 +98,22 @@ def validate_and_sanitise(
9798 # - periods,
9899 # - dashes,
99100 # - forward slashes ("/")
100- if bool (re .fullmatch (r"^[\w\s\.\-/]+$" , full_path )) is False :
101- raise ValueError (f"Unallowed characters present in { file !r } " )
101+ if bool (re .fullmatch (r"^[\w\s\.\-/]+$" , str ( full_path ) )) is False :
102+ raise ValueError (f"Unallowed characters present in { file } " )
102103
103104 # Check that it's not accessing somehwere it's not allowed
104105 if not str (full_path ).startswith (str (base_path )):
105- raise ValueError (f"{ file !r} points to a directory that is not permitted" )
106+ raise ValueError (f"{ file } points to a directory that is not permitted" )
107+
108+ # Check that it's a file, not a directory
109+ if full_path .is_file () is False :
110+ raise ValueError (f"{ file } is not a file" )
106111
107112 # Check that it is of a permitted file type
108- if f". { full_path .rsplit ( '.' , 1 )[ - 1 ] } " not in valid_file_types :
109- raise ValueError ("File is not a permitted file format" )
113+ if f"{ full_path .suffix } " not in valid_file_types :
114+ raise ValueError (f" { full_path . suffix } is not a permitted file format" )
110115
111- return Path ( full_path )
116+ return full_path
112117
113118
114119def get_db_entry (
0 commit comments