Skip to content

Commit 5b606b1

Browse files
Raise error if attachment pathname contains invalid bytes (python-discord#209)
1 parent f45ae67 commit 5b606b1

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

snekbox/nsjail.py

+6
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from snekbox.limits.timed import time_limit
1515
from snekbox.result import EvalError, EvalResult
1616
from snekbox.snekio import FileAttachment, MemFS
17+
from snekbox.snekio.errors import IllegalPathError
1718
from snekbox.snekio.filesystem import Size
1819
from snekbox.utils.iter import iter_lstrip
1920

@@ -244,6 +245,11 @@ def _parse_attachments(
244245
except TimeoutError as e:
245246
log.info(f"Exceeded time limit while parsing attachments: {e}")
246247
raise EvalError("TimeoutError: Exceeded time limit while parsing attachments") from e
248+
except IllegalPathError as e:
249+
log.info(f"Invalid bytes in filename while parsing attachments: {e}")
250+
raise EvalError(
251+
"FileParsingError: invalid bytes in filename while parsing attachments"
252+
) from e
247253
except Exception as e:
248254
log.exception(f"Unexpected {type(e).__name__} while parse attachments", exc_info=e)
249255
raise EvalError("FileParsingError: Unknown error while parsing attachments") from e

snekbox/snekio/attachment.py

+9
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,17 @@ def from_path(cls, file: Path, relative_to: Path | None = None) -> FileAttachmen
6767
Args:
6868
file: The file to attach.
6969
relative_to: The root for the path name.
70+
Raises:
71+
IllegalPathError: If path name contains characters that can't be encoded in UTF-8
7072
"""
7173
path = file.relative_to(relative_to) if relative_to else file
74+
75+
# Disallow filenames with chars that can't be encoded in UTF-8
76+
try:
77+
str(path).encode("utf-8")
78+
except UnicodeEncodeError as e:
79+
raise IllegalPathError("File paths may not contain invalid byte sequences") from e
80+
7281
return cls(str(path), file.read_bytes())
7382

7483
@property

tests/test_nsjail.py

+14
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,20 @@ def test_file_parsing_timeout(self):
250250
)
251251
self.assertEqual(result.stderr, None)
252252

253+
def test_filename_encoding_illegal_chars(self):
254+
code = dedent(
255+
r"""
256+
with open(b"\xC3.txt", "w") as f:
257+
f.write("test")
258+
"""
259+
).strip()
260+
result = self.eval_file(code)
261+
self.assertEqual(result.returncode, None)
262+
self.assertEqual(
263+
result.stdout, "FileParsingError: invalid bytes in filename while parsing attachments"
264+
)
265+
self.assertEqual(result.stderr, None)
266+
253267
def test_file_parsing_depth_limit(self):
254268
code = dedent(
255269
"""

0 commit comments

Comments
 (0)