Skip to content

Commit

Permalink
fix: secure filename + keep filename if uploading file bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
davidlougheed committed Oct 23, 2023
1 parent cf601d6 commit 26e612e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
13 changes: 9 additions & 4 deletions chord_drs/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pathlib import Path
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from werkzeug.utils import secure_filename
from urllib.parse import urlparse
from uuid import uuid4

Expand Down Expand Up @@ -71,6 +72,9 @@ def __init__(self, *args, **kwargs):
# If set, we are deduplicating with an existing file object
object_to_copy: DrsBlob | None = kwargs.get("object_to_copy")

# If set, we are overriding the filename to save the file to
filename: str | None = kwargs.get("filename")

self.id = str(uuid4())

if object_to_copy:
Expand All @@ -88,8 +92,8 @@ def __init__(self, *args, **kwargs):
# TODO: we will need to account for URLs at some point
raise FileNotFoundError("Provided file path does not exists")

self.name = p.name
new_filename = f"{self.id[:12]}-{p.name}" # TODO: use checksum for filename instead
self.name = secure_filename(filename or p.name)
new_filename = f"{self.id[:12]}-{self.name}" # TODO: use checksum for filename instead

backend = get_backend()

Expand All @@ -104,8 +108,9 @@ def __init__(self, *args, **kwargs):
# TODO: implement more specific exception handling
raise Exception("Well if the file is not saved... we can't do squat")

if "location" in kwargs:
del kwargs["location"]
for key_to_remove in ("location", "filename"):
if key_to_remove in kwargs:
del kwargs[key_to_remove]

super().__init__(*args, **kwargs)

Expand Down
5 changes: 4 additions & 1 deletion chord_drs/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,9 +473,11 @@ def object_ingest():

tfh, t_obj_path = tempfile.mkstemp()
try:
if file:
filename: str | None = None # no override, use path filename if path is specified instead of a file upload
if file is not None:
file.save(t_obj_path)
obj_path = t_obj_path
filename = file.filename # still may be none, in which case the temporary filename will be used

if deduplicate:
# Get checksum of original file, and query database for objects that match
Expand Down Expand Up @@ -507,6 +509,7 @@ def object_ingest():
try:
drs_object = DrsBlob(
**(dict(object_to_copy=object_to_copy) if object_to_copy else dict(location=obj_path)),
filename=filename,
project_id=project_id,
dataset_id=dataset_id,
data_type=data_type,
Expand Down

0 comments on commit 26e612e

Please sign in to comment.