Skip to content

Commit d7324f5

Browse files
authored
🐛 fix(rw): protect private database links (#1096)
1 parent 54fe35c commit d7324f5

11 files changed

Lines changed: 586 additions & 102 deletions
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Bound parent-directory enumeration in the dead-holder link sweep during :class:`~filelock.ReadWriteLock` and
2+
:class:`~filelock.AsyncReadWriteLock` connection setup. A crowded shared directory no longer forces the sweep to inspect
3+
every planted name.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
On POSIX, :class:`~filelock.ReadWriteLock` and :class:`~filelock.AsyncReadWriteLock` no longer create a separate lock
2+
database when a private hard link disappears before SQLite opens it. On Linux, cleanup leaves links from other
3+
processes alone when procfs cannot establish their PID namespace.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Prevent another account from redirecting :class:`ReadWriteLock <filelock.ReadWriteLock>` through a watched directory
2+
swapped into a shared, non-sticky lock parent. The SQLite hard link now uses a fresh private directory below the
3+
replaceable directory, keeping its final name hidden from a watch opened before the swap. Dead-holder cleanup still
4+
recognizes link layouts left by older releases.

‎docs/concepts.rst‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -506,10 +506,12 @@ The defense differs by platform:
506506
was given the inode number of a removed record and renamed over it.
507507

508508
:class:`ReadWriteLock <filelock.ReadWriteLock>` refuses a symlink at its database path. In a directory that processes of
509-
other accounts can write, it opens SQLite through a hard link (a second name for the same file) in a directory only the
510-
locking account can read, so a link or journal file another process puts beside the database cannot point the lock at
509+
other accounts can write, it opens SQLite through a hard link (a second name for the same file) in a freshly created
510+
private directory, so a link or journal file another process puts beside the database cannot point the lock at
511511
another file. It also uses that link when a ``-journal``, ``-wal`` or ``-shm`` file remains beside the database after
512-
the directory is made private. On Windows the directory counts as writable by other accounts unless its owner and every
512+
the directory is made private.
513+
514+
On Windows the directory counts as writable by other accounts unless its owner and every
513515
entry of its access control list (ACL) that allows adding or removing names belong to the locking account, ``SYSTEM`` or
514516
``Administrators``.
515517

‎docs/how-to.rst‎

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -450,26 +450,33 @@ write hold.
450450
SQLite loads the schema before it can honor the acquire timeout. filelock limits each row to 1,024 bytes during this
451451
load and interrupts long-running schema queries. A lock database that exceeds either limit raises :class:`ValueError`.
452452

453-
On POSIX, SQLite opens the database by name. It also uses the names ``<database>-journal``, ``<database>-wal`` and
454-
``<database>-shm`` beside it, so a file placed under one of those names changes what SQLite does. filelock therefore
455-
names the database directly only when no process of another account can create names in its directory and none of those
456-
three side files exists. The directory must belong to the locking account or root and must not be writable by its group
457-
or by others. Otherwise, filelock opens SQLite through a hard link (a second name for the same file) inside a
458-
``.filelock-*`` directory that only the locking account can read. A side file left before the directory was made private
459-
still selects this route. The directory must be writable by the locking account, and the filesystem must support hard
460-
links; when the link cannot be made, the lock raises :class:`OSError`.
453+
On POSIX, filelock opens the database directly when its directory belongs to the locking account or root, its group
454+
and others cannot write there, and none of SQLite's side files (``-journal``, ``-wal`` or ``-shm``) exist.
455+
456+
Otherwise, filelock creates a private directory under ``.filelock-*`` and opens a hard link to the database there.
457+
This keeps SQLite's side files out of the shared directory. The locking account needs write access to the parent and a
458+
filesystem that supports hard links. If inherited permissions expose the private directory, filelock sets mode 0700 and
459+
checks it. If other accounts still have access or the filesystem refuses the mode change, filelock raises :class:`PermissionError`.
460+
461+
Each process checks shared directories for links left by dead holders. It checks a 50 ms deadline between entries.
462+
If time runs out, connections to that database skip cleanup for one minute. The next connection then continues from
463+
the last entry. Each process keeps up to 16 unfinished scans. An evicted scan starts over when its database is next
464+
eligible. After visiting 1,024 databases, filelock can forget an older scan and check that database again. A leftover
465+
link does not keep the lock held.
466+
467+
On POSIX, SQLite refuses to create a database if its private link disappears before the connection opens. On Linux,
468+
when procfs cannot establish the process's PID namespace, filelock leaves private links from other processes in place.
469+
Upgrade all processes that share the database together. Older releases can create a separate database if their private
470+
link disappears. Stop all users of the database before removing any stale ``.filelock-*`` directories by hand.
461471

462472
Both routes assume that no process of another account can replace the database directory or any directory above it.
463473
That holds when every directory above belongs to the locking account or root and is either not writable by others or
464474
has the sticky bit (a directory flag that lets only a file's owner rename or remove it).
465475

466-
A process that can rename an entry in a directory above owns every name below it, and can put a replacement at the
467-
database path between the lock's checks. filelock compares the name with the file it checked before it runs any SQL statement, and raises
468-
:class:`OSError` instead of reporting the lock held, and leaves the replacement's files as they were, except that
469-
SQLite's open creates an empty ``lock.db`` there when the name is missing, following a symlink at that name. A swap that lands after that
470-
comparison and before SQLite's first statement still makes SQLite look up ``-journal`` and ``-wal`` under the
471-
replacement: it deletes both, and beside a non-empty lock database it first replays the journal into that database and
472-
unlinks the file the journal names.
476+
Keep the database under directories trusted by the locking account. If another account can replace a directory above
477+
the database, it can change which files SQLite sees between the identity check and the first SQL statement. SQLite
478+
can then delete a journal or WAL in the replacement directory. With a nonempty database, SQLite can replay the journal
479+
into that database and unlink the file named by the journal.
473480

474481
On Windows the lock makes the same choice from the directory's access control list (ACL). It connects by the database
475482
name only when the directory's owner and every entry that allows adding files, adding subdirectories or deleting entries

‎src/filelock/_identity.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,9 +378,22 @@ def _owner_runs_elsewhere(pid: int, start_token: int | None) -> bool:
378378
return False
379379

380380

381+
def link_host() -> str | None: # pragma: needs posix-hard-link
382+
if sys.platform in {"linux", "android"}: # pragma: darwin no cover
383+
try:
384+
Path("/proc/self/ns/pid").stat()
385+
except OSError:
386+
# An unreadable procfs gives different PID namespaces the same hostname; none can prove a peer dead.
387+
return None
388+
if not _proc_numbers_tasks_as_here():
389+
return None
390+
return host_name()
391+
392+
381393
__all__ = [
382394
"describe_host_name",
383395
"host_name",
396+
"link_host",
384397
"owner_is_current_process",
385398
"owner_is_stale",
386399
"process_alive",

0 commit comments

Comments
 (0)