Skip to content

Commit bbd3e29

Browse files
committed
Used Path object to resolve file path in 'validate_and_sanitise'; added additional 'raise Exception' to catch unexpected ones when loading rsync_basepath
1 parent 6dac704 commit bbd3e29

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

src/murfey/server/api/clem.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import sys
55
import traceback
66
from logging import getLogger
7-
from os import path
87
from pathlib import Path
98
from 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

114119
def get_db_entry(

0 commit comments

Comments
 (0)