1
0
forked from clan/clan-core

clan-cli: Better env jailing in temporary_home

This commit is contained in:
Luis Hebendanz 2024-06-25 12:03:40 +02:00
parent 5ae8ccbbdd
commit 62839b6fa0

View File

@ -11,26 +11,28 @@ log = logging.getLogger(__name__)
@pytest.fixture @pytest.fixture
def temporary_home(monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]: def temporary_home(monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
env_dir = os.getenv("TEST_TEMPORARY_DIR") with tempfile.TemporaryDirectory(prefix="pytest-") as dirpath:
if env_dir is not None: xdg_runtime_dir = os.getenv("XDG_RUNTIME_DIR")
path = Path(env_dir).resolve() monkeypatch.setenv("HOME", str(dirpath))
log.debug("Temp HOME directory: %s", str(path)) monkeypatch.setenv("XDG_CONFIG_HOME", str(Path(dirpath) / ".config"))
monkeypatch.setenv("HOME", str(path))
monkeypatch.setenv("XDG_CONFIG_HOME", str(path / ".config")) runtime_dir = Path(dirpath) / "xdg-runtime-dir"
runtime_dir = path / "xdg-runtime-dir"
runtime_dir.mkdir() runtime_dir.mkdir()
runtime_dir.chmod(0o700) runtime_dir.chmod(0o700)
gpgdir = runtime_dir / "gpgagent"
gpgdir.mkdir()
gpgdir.chmod(0o700)
monkeypatch.setenv("GPG_AGENT_INFO", str(gpgdir))
# Iterate over all environment variables
for key, value in os.environ.items():
if xdg_runtime_dir and value.startswith(xdg_runtime_dir):
monkeypatch.setenv(
key, value.replace(xdg_runtime_dir, str(runtime_dir))
)
monkeypatch.setenv("XDG_RUNTIME_DIR", str(runtime_dir)) monkeypatch.setenv("XDG_RUNTIME_DIR", str(runtime_dir))
monkeypatch.chdir(str(path)) monkeypatch.chdir(str(dirpath))
yield path log.debug("Temp HOME directory: %s", str(dirpath))
else: yield Path(dirpath)
with tempfile.TemporaryDirectory(prefix="pytest-") as dirpath:
monkeypatch.setenv("HOME", str(dirpath))
monkeypatch.setenv("XDG_CONFIG_HOME", str(Path(dirpath) / ".config"))
runtime_dir = Path(dirpath) / "xdg-runtime-dir"
runtime_dir.mkdir()
runtime_dir.chmod(0o700)
monkeypatch.setenv("XDG_RUNTIME_DIR", str(runtime_dir))
monkeypatch.chdir(str(dirpath))
log.debug("Temp HOME directory: %s", str(dirpath))
yield Path(dirpath)