Skip to content

Commit

Permalink
Adding max_length in secure_filename
Browse files Browse the repository at this point in the history
1) adding max_length parameter which truncates the file but includes the ext.
2) This is presently set to None but can be set 255 characters.
  • Loading branch information
Krishn1412 committed Dec 12, 2024
1 parent 11076b8 commit fe1a82a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
9 changes: 9 additions & 0 deletions falcon/media/multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,15 @@ class MultipartParseOptions:
If the body part headers size exceeds this value, an instance of
:class:`.MultipartParseError` will be raised.
"""
max_filename_length: Optional[int]
"""The maximum length of filenames in multipart forms (default ``None``).
If the filename exceeds this value, it will be truncated while preserving
the file extension. Defaults to ``None`` for backward compatibility.
.. note::
Starting from Falcon 5.0, this will default to 255 characters.
"""
media_handlers: Handlers
"""A dict-like object for configuring the media-types to handle.
Expand Down
13 changes: 11 additions & 2 deletions falcon/util/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import re
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union
import unicodedata
import os

from falcon import status_codes
from falcon.constants import PYPY
Expand Down Expand Up @@ -336,7 +337,7 @@ def get_argnames(func: Callable[..., Any]) -> List[str]:
return args


def secure_filename(filename: str) -> str:
def secure_filename(filename: str, max_length: int = None) -> str:
"""Sanitize the provided `filename` to contain only ASCII characters.
Only ASCII alphanumerals, ``'.'``, ``'-'`` and ``'_'`` are allowed for
Expand All @@ -357,6 +358,8 @@ def secure_filename(filename: str) -> str:
Args:
filename (str): Arbitrary filename input from the request, such as a
multipart form filename field.
max_length (int, optional): Maximum length of the sanitized filename,
including the file extension. If None, no truncation is applied.
Returns:
str: The sanitized filename.
Expand All @@ -373,7 +376,13 @@ def secure_filename(filename: str) -> str:
filename = unicodedata.normalize('NFKD', filename)
if filename.startswith('.'):
filename = filename.replace('.', '_', 1)
return _UNSAFE_CHARS.sub('_', filename)
filename = _UNSAFE_CHARS.sub('_', filename)

if max_length is not None and len(filename) > max_length:
name, ext = os.path.splitext(filename)
filename = name[:max_length - len(ext)] + ext

Check warning on line 383 in falcon/util/misc.py

View check run for this annotation

Codecov / codecov/patch

falcon/util/misc.py#L382-L383

Added lines #L382 - L383 were not covered by tests

return filename


@_lru_cache_for_simple_logic(maxsize=64)
Expand Down

0 comments on commit fe1a82a

Please sign in to comment.