Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions multiuserfilelock/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,20 @@ def __init__(self, *args, user=None, group=None, chmod=0o666, **kwargs):
parent = self._lock_file_path.parent
self._make_directories(parent)

if self._group is not None and parent.group() != self._group:
shutil.chown(parent, group=self._group)
if self._owns(parent):
if self._group is not None and parent.group() != self._group:
shutil.chown(parent, group=self._group)

# Changing the owner in the tmp directory is hard..
if self._user is not None and parent.owner() != self._user:
shutil.chown(parent, user=self._user)
# Changing the owner in the tmp directory is hard..
if self._user is not None and parent.owner() != self._user:
shutil.chown(parent, user=self._user)

@staticmethod
def _owns(path):
if os.name == 'nt':
return True
euid = os.geteuid()
return euid == 0 or path.stat().st_uid == euid

def _make_directories(self, directory):
if directory.is_dir():
Expand All @@ -76,6 +84,8 @@ def acquire(self, *args, **kwargs):
self._filelock.acquire(*args, **kwargs)
# once the lock has been acquired, we are more guaranteed that the
# _lock_file exists
if not self._owns(self._lock_file_path):
return
if self._chmod:
desired_permissions = self._chmod
current_permissions = self._lock_file_path.stat().st_mode
Expand Down
21 changes: 21 additions & 0 deletions multiuserfilelock/tests/test_acquire.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import shutil
import os
import grp
from multiuserfilelock import MultiUserFileLock, Timeout
Expand Down Expand Up @@ -84,3 +85,23 @@ def test_nested_directories_get_group_and_mode(tmp_path):
for directory in [tmp_path / 'a', tmp_path / 'a' / 'b']:
assert directory.group() == group
assert directory.stat().st_mode & 0o777 == 0o777


@pytest.mark.skipif(os.name == 'nt', reason='no unix ownership')
def test_files_of_another_user_are_left_alone(tmp_path, monkeypatch):
lock_filename = tmp_path / 'a' / 'test.lock'
lock = MultiUserFileLock(lock_filename)
lock.acquire()
lock.release()

def refuse(*args, **kwargs):
raise PermissionError(1, 'Operation not permitted')

monkeypatch.setattr(os, 'geteuid', lambda: os.getuid() + 1)
monkeypatch.setattr(shutil, 'chown', refuse)
lock = MultiUserFileLock(lock_filename, group='other', timeout=0.001)
lock.acquire()
other = MultiUserFileLock(lock_filename, group='other', timeout=0.001)
with pytest.raises(Timeout):
other.acquire()
lock.release()
Loading