diff --git a/Lib/tempfile.py b/Lib/tempfile.py index e6fb3c8e9a..2c7d546693 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -81,6 +81,12 @@ else: fd = _os.open(fn, _os.O_RDONLY) _os.close(fd) +if _os.altsep is None: + _path_separators = (_os.sep,) +else: + _path_separators = (_os.sep, _os.altsep) + + def _exists(fn): try: _stat(fn) @@ -121,6 +127,12 @@ def _sanitize_params(prefix, suffix, dir): prefix = template else: prefix = _os.fsencode(template) + if output_type is str: + if any(sep in prefix for sep in _path_separators): + raise ValueError("Prefix contains system separator character") + else: + if any(_os.fsencode(sep) in prefix for sep in _path_separators): + raise ValueError("Prefix contains system separator character") if dir is None: if output_type is str: dir = gettempdir() diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index e5098d2eea..6d2ab60692 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -561,6 +561,23 @@ class TestGetTempPrefix(BaseTestCase): os.rmdir(d) +class TestSanitizeParamsInner(BaseTestCase): + """Test the internal function _sanitize_params.""" + + def test_throw_exception_on_path_separator_detection(self): + with self.assertRaises(ValueError): + tempfile.mkstemp(prefix=f"{os.sep}home") + + def test_throw_exception_on_encoded_path_separator_detection(self): + with self.assertRaises(ValueError): + tempfile.mkstemp(prefix=f"{os.fsencode(os.sep)}home") + + @unittest.skipIf(os.altsep is None, "os.altsep is not present on this platform") + def test_throw_exception_on_alternative_path_separator_detection(self): + with self.assertRaises(ValueError): + tempfile.mkstemp(prefix=f"{os.altsep}home") + + class TestGetTempDir(BaseTestCase): """Test gettempdir()."""