v0.166.0
 1import os
 2import pathlib
 3from typing import TYPE_CHECKING
 4
 5from plain.http import SuspiciousFileOperationError400
 6
 7if TYPE_CHECKING:
 8    from collections.abc import Iterator
 9    from typing import IO, Any
10
11
12def validate_file_name(name: str, allow_relative_path: bool = False) -> str:
13    # Remove potentially dangerous names
14    if os.path.basename(name) in {"", ".", ".."}:
15        raise SuspiciousFileOperationError400(
16            f"Could not derive file name from '{name}'"
17        )
18
19    if allow_relative_path:
20        # Use PurePosixPath() because this branch is checked only in
21        # FileField.generate_filename() where all file paths are expected to be
22        # Unix style (with forward slashes).
23        path = pathlib.PurePosixPath(name)
24        if path.is_absolute() or ".." in path.parts:
25            raise SuspiciousFileOperationError400(
26                f"Detected path traversal attempt in '{name}'"
27            )
28    elif name != os.path.basename(name):
29        raise SuspiciousFileOperationError400(
30            f"File name '{name}' includes path elements"
31        )
32
33    return name
34
35
36class FileProxyMixin:
37    """
38    A mixin class used to forward file methods to an underlying file
39    object.  The internal file object has to be called "file"::
40
41        class FileProxy(FileProxyMixin):
42            def __init__(self, file):
43                self.file = file
44    """
45
46    # Expected to be set by subclasses
47    file: IO[Any]
48
49    encoding = property(lambda self: self.file.encoding)
50    fileno = property(lambda self: self.file.fileno)
51    flush = property(lambda self: self.file.flush)
52    isatty = property(lambda self: self.file.isatty)
53    newlines = property(lambda self: self.file.newlines)
54    read = property(lambda self: self.file.read)
55    readinto = property(lambda self: self.file.readinto)
56    readline = property(lambda self: self.file.readline)
57    readlines = property(lambda self: self.file.readlines)
58    seek = property(lambda self: self.file.seek)
59    tell = property(lambda self: self.file.tell)
60    truncate = property(lambda self: self.file.truncate)
61    write = property(lambda self: self.file.write)
62    writelines = property(lambda self: self.file.writelines)
63
64    @property
65    def closed(self) -> bool:
66        return not self.file or self.file.closed
67
68    def readable(self) -> bool:
69        if self.closed:
70            return False
71        if hasattr(self.file, "readable"):
72            return self.file.readable()
73        return True
74
75    def writable(self) -> bool:
76        if self.closed:
77            return False
78        if hasattr(self.file, "writable"):
79            return self.file.writable()
80        return "w" in getattr(self.file, "mode", "")
81
82    def seekable(self) -> bool:
83        if self.closed:
84            return False
85        if hasattr(self.file, "seekable"):
86            return self.file.seekable()
87        return True
88
89    def __iter__(self) -> Iterator[Any]:
90        return iter(self.file)