tmpdir: fix temporary directories created with world-readable permissions

(Written for a Unix system, but might be applicable to Windows as well).

pytest creates a root temporary directory under /tmp, named
`pytest-of-<username>`, and creates tmp_path's and other under it.
/tmp is shared between all users of the system.

This root temporary directory was created with 0o777&~umask permissions,
which usually becomes 0o755, meaning any user in the system could list
and read the files, which is undesirable.

Use 0o700 permissions instead. Also for subdirectories, because the root
dir is adjustable.
This commit is contained in:
Ran Benita
2021-03-06 17:01:29 +02:00
parent 0dd1e5b4f4
commit 1278f8b97e
5 changed files with 42 additions and 13 deletions

View File

@@ -454,3 +454,19 @@ def test_tmp_path_factory_handles_invalid_dir_characters(
monkeypatch.setattr(tmp_path_factory, "_given_basetemp", None)
p = tmp_path_factory.getbasetemp()
assert "pytest-of-unknown" in str(p)
@pytest.mark.skipif(not hasattr(os, "getuid"), reason="checks unix permissions")
def test_tmp_path_factory_create_directory_with_safe_permissions(
tmp_path: Path, monkeypatch: MonkeyPatch
) -> None:
"""Verify that pytest creates directories under /tmp with private permissions."""
# Use the test's tmp_path as the system temproot (/tmp).
monkeypatch.setenv("PYTEST_DEBUG_TEMPROOT", str(tmp_path))
tmp_factory = TempPathFactory(None, lambda *args: None, _ispytest=True)
basetemp = tmp_factory.getbasetemp()
# No world-readable permissions.
assert (basetemp.stat().st_mode & 0o077) == 0
# Parent too (pytest-of-foo).
assert (basetemp.parent.stat().st_mode & 0o077) == 0