diff options
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 127 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_inflight_reviews.py | 142 |
2 files changed, 238 insertions, 31 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 1544ccfe..9ba40385 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -675,14 +675,19 @@ def _diff_review_done(token): # through a second full review. So a review first takes an exclusive flock on # `sg-inflight-<sha>`, next to the reviewed-shas file, and holds it until its # process ends; other reviews leave a locked commit to it. The kernel drops -# the lock however the holder dies, so a killed review blocks nobody. Without -# flock (native Windows Python, some network filesystems) there are no +# the lock however the holder dies, so a killed review blocks nobody. Native +# Windows Python has no flock; there the same lock is taken with LockFileEx. +# Where files cannot be locked (some network filesystems) there are no # markers and nothing changes. _INFLIGHT_PREFIX = "sg-inflight-" # A marker file nobody holds (a killed review's) is removed once this old. _INFLIGHT_GC_AGE_S = 3600 _inflight_held = {} +# Windows refuses to delete a file that is open, so a marker is closed first +# there. Elsewhere it is deleted while still locked, so nobody can lock a +# file that is about to go. +_UNLINK_BEFORE_CLOSE = os.name != "nt" def _full_shas(repo_root, shas): @@ -701,11 +706,60 @@ def _full_shas(repo_root, shas): return out +_win_lock_file_ex = None + + +def _win_lock_nb(fd, exclusive): + """`_flock_nb` for native Windows Python, with LockFileEx. + + Shared and exclusive as with flock, never waits, and Windows drops the + lock when the handle is closed or the holder's process ends. Windows + locks stop other processes reading the locked bytes, so the byte locked + is one far past the end of the (empty) marker: copying a repository while + a review runs still reads the marker. + """ + global _win_lock_file_ex + import errno + try: + import ctypes + import msvcrt + if _win_lock_file_ex is None: + from ctypes import wintypes + + class _Overlapped(ctypes.Structure): + _fields_ = [("Internal", ctypes.c_void_p), ("InternalHigh", ctypes.c_void_p), + ("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD), + ("hEvent", wintypes.HANDLE)] + + fn = ctypes.WinDLL("kernel32", use_last_error=True).LockFileEx + fn.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, + wintypes.DWORD, ctypes.POINTER(_Overlapped)] + fn.restype = wintypes.BOOL + _win_lock_file_ex = (fn, _Overlapped) + except (ImportError, AttributeError, OSError) as e: + raise OSError(errno.ENOLCK, f"no file locking in this Python ({e})") + fn, _Overlapped = _win_lock_file_ex + fail_immediately, exclusive_lock = 0x1, 0x2 + where = _Overlapped(Offset=0, OffsetHigh=0x7FFFFFFF) + if fn(msvcrt.get_osfhandle(fd), fail_immediately | (exclusive_lock if exclusive else 0), + 0, 1, 0, ctypes.byref(where)): + return True + err = ctypes.get_last_error() + if err == 33: # ERROR_LOCK_VIOLATION: another handle holds it + return False + raise OSError(errno.ENOLCK, f"LockFileEx failed (WinError {err})") + + def _flock_nb(fd, exclusive): """True when the lock was taken, False when another process holds it. Raises OSError when the file cannot be locked at all.""" import errno - import fcntl + if os.name == "nt": + return _win_lock_nb(fd, exclusive) + try: + import fcntl + except ImportError as e: + raise OSError(errno.ENOLCK, f"no file locking in this Python ({e})") try: fcntl.flock(fd, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB) return True @@ -715,16 +769,36 @@ def _flock_nb(fd, exclusive): raise -def _release_inflight(): - for p, fd in list(_inflight_held.items()): +def _again_if_refused(op, *args): + """`op(*args)`, tried a few times where another process having the file + open for a moment refuses it (Windows). Raises the last OSError.""" + import time as _time + tries = 1 if _UNLINK_BEFORE_CLOSE else 3 + for attempt in range(tries): try: - os.unlink(p) - except OSError: - pass + return op(*args) + except PermissionError: + if attempt == tries - 1: + raise + _time.sleep(0.01) + + +def _drop_marker(p, fd, unlink=True): + """Close a marker this process has open and, with `unlink`, delete it, in + the order this platform needs. Never raises. A delete that stays refused + leaves an unlocked file, which is swept once old.""" + steps = [(_again_if_refused, os.unlink, p)] if unlink else [] + steps.insert(len(steps) if _UNLINK_BEFORE_CLOSE else 0, (os.close, fd)) + for step, *args in steps: try: - os.close(fd) + step(*args) except OSError: pass + + +def _release_inflight(): + for p, fd in list(_inflight_held.items()): + _drop_marker(p, fd) _inflight_held.clear() @@ -743,11 +817,10 @@ def _sweep_inflight(gd): except OSError: continue try: - if _flock_nb(fd, exclusive=True): - os.unlink(p) + unheld = _flock_nb(fd, exclusive=True) except OSError: - pass - os.close(fd) + unheld = False + _drop_marker(p, fd, unlink=unheld) def _mark_inflight(repo_root, shas): @@ -755,7 +828,6 @@ def _mark_inflight(repo_root, shas): run, until the process ends. Best-effort; never raises. A commit another live review holds stays with that review.""" try: - import fcntl # noqa: F401 gd = _git_dir(repo_root) if not gd: return @@ -764,17 +836,26 @@ def _mark_inflight(repo_root, shas): p = os.path.join(gd, _INFLIGHT_PREFIX + sha) if not _is_full_sha(sha) or p in _inflight_held: continue - fd = os.open(p, os.O_RDWR | os.O_CREAT, 0o600) try: - # The inode check: a holder unlinks its marker when it ends, - # and a lock on that unlinked file would claim nothing. - held = (_flock_nb(fd, exclusive=True) - and os.fstat(fd).st_ino == os.stat(p).st_ino) + fd = _again_if_refused(os.open, p, os.O_RDWR | os.O_CREAT, 0o600) + except OSError: + # One marker that cannot be opened does not cost the others + # their claim. + continue + try: + held = _flock_nb(fd, exclusive=True) except OSError: # Cannot lock here at all: leave no file that reads as held. - os.close(fd) - os.unlink(p) + _drop_marker(p, fd) return + if held and _UNLINK_BEFORE_CLOSE: + # The inode check: a holder unlinks its marker when it ends, + # and a lock on that unlinked file would claim nothing. Not + # where an open file cannot be unlinked in the first place. + try: + held = os.fstat(fd).st_ino == os.stat(p).st_ino + except OSError: + held = False if not held: os.close(fd) continue @@ -790,10 +871,6 @@ def _mark_inflight(repo_root, shas): def _load_inflight_shas(repo_root, shas, _gd=None): """Which of `shas` another live review in this clone holds right now.""" out = set() - try: - import fcntl # noqa: F401 - except ImportError: - return out gd = _gd or _git_dir(repo_root) if not gd: return out diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py index 4e00c608..4c339a5f 100644 --- a/plugins/security-guidance/tests/test_inflight_reviews.py +++ b/plugins/security-guidance/tests/test_inflight_reviews.py @@ -14,12 +14,15 @@ from conftest import ( import diffstate -pytest.importorskip("fcntl") +_HOOKS_DIR = os.path.dirname(diffstate.__file__) +# Locks the way a review does on this platform: flock, or LockFileEx on Windows. _HOLD = ( - "import fcntl, os, sys, time\n" + "import os, sys, time\n" + "sys.path.insert(0, sys.argv[3])\n" + "import diffstate\n" "fd = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT, 0o600)\n" - "fcntl.flock(fd, fcntl.LOCK_EX)\n" + "assert diffstate._flock_nb(fd, exclusive=True)\n" "print('held', flush=True)\n" "time.sleep(float(sys.argv[2]))\n" ) @@ -29,8 +32,9 @@ _HOLD = ( def _held_by_another_review(repo, sha, seconds=60): """A marker on `sha` that a live process holds, as a running review does.""" marker = repo / ".git" / f"sg-inflight-{sha}" - p = subprocess.Popen([sys.executable, "-c", _HOLD, str(marker), str(seconds)], - stdout=subprocess.PIPE, text=True) + p = subprocess.Popen( + [sys.executable, "-c", _HOLD, str(marker), str(seconds), _HOOKS_DIR], + stdout=subprocess.PIPE, text=True) try: assert p.stdout.readline().strip() == "held" yield marker @@ -238,7 +242,7 @@ def test_own_marker_is_held_until_released(tmp_path): "print(sorted(diffstate._load_inflight_shas(sys.argv[2], [sys.argv[3]])))" ) seen = subprocess.run( - [sys.executable, "-c", probe, os.path.dirname(diffstate.__file__), str(repo), sha], + [sys.executable, "-c", probe, _HOOKS_DIR, str(repo), sha], capture_output=True, text=True).stdout.strip() assert seen == str([sha]) reviewed, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 5) @@ -246,3 +250,129 @@ def test_own_marker_is_held_until_released(tmp_path): finally: diffstate._release_inflight() assert not marker.exists() + + +def test_marker_is_closed_before_it_is_deleted_where_open_files_cannot_be(tmp_path, monkeypatch): + # The order used on Windows, where deleting an open file is refused. + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + marker = repo / ".git" / f"sg-inflight-{sha}" + monkeypatch.setattr(diffstate, "_UNLINK_BEFORE_CLOSE", False) + open_at_delete, refusals = [], [2] + + def delete_like_windows(p, fd): + try: + os.fstat(fd) + open_at_delete.append(True) + except OSError: + open_at_delete.append(False) + if refusals[0]: + # Another review asking about the marker has it open just now. + refusals[0] -= 1 + raise PermissionError(13, "The process cannot access the file") + real_unlink(p) + + real_unlink = os.unlink + try: + diffstate._mark_inflight(str(repo), [sha]) + (fd,) = diffstate._inflight_held.values() + monkeypatch.setattr(diffstate.os, "unlink", lambda p: delete_like_windows(p, fd)) + diffstate._release_inflight() + finally: + monkeypatch.setattr(diffstate.os, "unlink", real_unlink) + diffstate._release_inflight() + assert open_at_delete == [False, False, False] and not marker.exists() + + # An old leftover goes the same way. + marker.write_text("") + old = time.time() - diffstate._INFLIGHT_GC_AGE_S - 5 + os.utime(marker, (old, old)) + diffstate._mark_inflight(str(repo), []) + assert not marker.exists() + + +def test_no_markers_in_a_python_without_file_locks(tmp_path, monkeypatch): + if os.name == "nt": + pytest.skip("Windows locks with LockFileEx") + repo = make_repo(tmp_path / "repo") + sha = git(repo, "rev-parse", "HEAD").strip() + monkeypatch.setitem(sys.modules, "fcntl", None) + diffstate._mark_inflight(str(repo), [sha]) + assert _markers(repo) == [] and diffstate._inflight_held == {} + (repo / ".git" / f"sg-inflight-{sha}").write_text("") + assert diffstate._load_inflight_shas(str(repo), [sha]) == set() + + +def test_one_marker_that_cannot_be_claimed_does_not_stop_the_others(tmp_path, monkeypatch): + repo = make_repo(tmp_path / "repo") + first = git(repo, "rev-parse", "HEAD").strip() + second, _ = commit_file(repo, "b.py", "b = 1\n") + third, _ = commit_file(repo, "c.py", "c = 1\n") + # Cannot be opened at all. + (repo / ".git" / f"sg-inflight-{first}").mkdir() + # Its last holder deletes it between this review's open and its lock. + real_flock_nb = diffstate._flock_nb + + def holder_ends_first(fd, exclusive): + taken = real_flock_nb(fd, exclusive) + gone = repo / ".git" / f"sg-inflight-{second}" + if gone.exists() and os.name != "nt": + gone.unlink() + return taken + monkeypatch.setattr(diffstate, "_flock_nb", holder_ends_first) + try: + diffstate._mark_inflight(str(repo), [first, second, third]) + held = [os.path.basename(p) for p in diffstate._inflight_held] + assert f"sg-inflight-{third}" in held and f"sg-inflight-{first}" not in held + if os.name != "nt": + assert held == [f"sg-inflight-{third}"] + finally: + diffstate._release_inflight() + + +class _FakeKernel32: + """LockFileEx as kernel32 has it, for the code path only Windows runs.""" + + def __init__(self): + self.calls, self.result, self.error = [], 1, 0 + + def LockFileEx(handle, flags, reserved, low, high, overlapped): + ov = overlapped._obj + self.calls.append((handle, flags, low, high, ov.Offset, ov.OffsetHigh)) + return self.result + self.LockFileEx = LockFileEx + + +@pytest.fixture +def kernel32(monkeypatch): + import ctypes + import types + fake = _FakeKernel32() + monkeypatch.setattr(ctypes, "WinDLL", lambda name, use_last_error=False: fake, raising=False) + monkeypatch.setattr(ctypes, "get_last_error", lambda: fake.error, raising=False) + monkeypatch.setitem(sys.modules, "msvcrt", + types.SimpleNamespace(get_osfhandle=lambda fd: 1000 + fd)) + monkeypatch.setattr(diffstate, "_win_lock_file_ex", None) + return fake + + +def test_windows_lock_call(kernel32): + assert diffstate._win_lock_nb(7, exclusive=True) is True + assert diffstate._win_lock_nb(7, exclusive=False) is True + # Fail-immediately, exclusive or shared, one byte far past the end of the + # file so that reading the marker is never refused. + assert kernel32.calls == [(1007, 0x3, 1, 0, 0, 0x7FFFFFFF), (1007, 0x1, 1, 0, 0, 0x7FFFFFFF)] + kernel32.result, kernel32.error = 0, 33 + assert diffstate._win_lock_nb(7, exclusive=True) is False + for other_error in (5, 6, 997): + kernel32.error = other_error + with pytest.raises(OSError): + diffstate._win_lock_nb(7, exclusive=True) + + +def test_windows_lock_is_off_where_the_call_is_missing(monkeypatch): + import ctypes + monkeypatch.delattr(ctypes, "WinDLL", raising=False) + monkeypatch.setattr(diffstate, "_win_lock_file_ex", None) + with pytest.raises(OSError): + diffstate._win_lock_nb(7, exclusive=True) |
