fix(profiles): classify the home once at the mkdir boundary; keep file-at-home and .. semantics
Review follow-ups on the home-directory boundary: - assert_named_profile_home_live now returns the named home it checked, and mkdir_under_hermes_home uses that instead of classifying the path again. A custom root identified only by its config.yaml could lose that marker between the two lookups; the second lookup then took the non-profile parents=True branch and re-created the home (same on main; found by the second-model review). It also drops two stats per call on the write path. - The path is normalized lexically before classification, so home/missing/../dest creates home/dest. Previously the leaf-first walk reached home/missing/.. as an "existing leaf" and, elevated, granted the whole home tree with repair_children. - A regular file at the named-home path raises FileExistsError again, as base's mkdir did, instead of returning (unsupportedpastels, m1). - repair_user_dir drops its test-only `elevated` override; its test now uses inputs absent from the grant memo, so removing either guard fails it (m2). - Docstrings and the rename comment in profiles.py describe the current contract.
This commit is contained in:
@@ -2241,8 +2241,8 @@ def rename_profile(old_name: str, new_name: str) -> Path:
|
||||
# 1b. Unroute the old name from a live multiplexer BEFORE the rename (same protocol as
|
||||
# delete_profile). A multiplexed secondary has no gateway.pid of its own, so the check above
|
||||
# reports it stopped while the default gateway still holds its adapters, cron ticker, logging
|
||||
# and SQLite handles; those re-``mkdir`` the old home the moment it moves (no tombstone →
|
||||
# ``mkdir_under_hermes_home`` does not refuse it) and the periodic reconcile re-adopts the
|
||||
# and SQLite handles; any of those that create directories outside ``mkdir_under_hermes_home``
|
||||
# re-create the old home the moment it moves, and the periodic reconcile re-adopts the
|
||||
# resurrected dir as a ghost served profile (#109267).
|
||||
live_mux = _live_default_multiplexer()
|
||||
if live_mux:
|
||||
|
||||
@@ -4,6 +4,7 @@ Import-safe, stdlib-only — importable from anywhere without circular-import ri
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
@@ -460,46 +461,50 @@ def clear_named_profile_deleted(profile_home: str | Path) -> None:
|
||||
profile_tombstone_path(Path(profile_home)).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def assert_named_profile_home_live(path: str | Path) -> None:
|
||||
"""Refuse missing or tombstoned named profile homes."""
|
||||
def assert_named_profile_home_live(path: str | Path) -> Path | None:
|
||||
"""Refuse missing or tombstoned named profile homes; return the named home owning *path*
|
||||
(``None`` for a default or custom home), so a caller acting on it never classifies twice."""
|
||||
home = named_profile_home(path)
|
||||
if home is not None and (named_profile_is_deleted(home) or not home.exists()):
|
||||
raise FileNotFoundError(
|
||||
f"Named profile home does not exist: {home}. "
|
||||
"Create the profile explicitly before using it."
|
||||
)
|
||||
return home
|
||||
|
||||
|
||||
def mkdir_under_hermes_home(path: str | Path) -> Path:
|
||||
"""Create *path*, but never materialize a deleted/missing named profile.
|
||||
|
||||
A named home itself is never created. If it disappears after the liveness check, creating a
|
||||
descendant raises ``FileNotFoundError`` rather than re-creating the home. When *path* is the home,
|
||||
only its ACL is repaired: a missing home is left missing without raising here, so a subsequent
|
||||
caller write fails. This prevents a late config save from creating a live duplicate under a
|
||||
renamed profile's old name. Below the home, see :func:`_mkdir_below_home`; default and custom
|
||||
homes keep ``parents=True``.
|
||||
A named home is never created, even when a delete or rename lands after the liveness check:
|
||||
a descendant then raises ``FileNotFoundError``, and the home as *path* is left missing for the
|
||||
caller's write to fail. Default and custom homes keep ``parents=True``.
|
||||
"""
|
||||
target = Path(path)
|
||||
assert_named_profile_home_live(target)
|
||||
# Lexical, so ``home/missing/../x`` is classified and created as ``home/x``.
|
||||
lexical = Path(os.path.normpath(target))
|
||||
home = assert_named_profile_home_live(lexical)
|
||||
# Lazy so this module still imports alone; hermes_dir_acl (stdlib only) ships beside it in every
|
||||
# closure that creates home dirs, and a missing copy fails loudly instead of silently skipping the
|
||||
# elevated grant (tests/pm/test_bootstrap_import_closure.py).
|
||||
from hermes_dir_acl import make_user_dir, repair_user_dir
|
||||
home = named_profile_home(target)
|
||||
if home is None:
|
||||
make_user_dir(target, parents=True, exist_ok=True)
|
||||
elif target == home:
|
||||
repair_user_dir(home)
|
||||
elif lexical != home:
|
||||
_mkdir_below_home(home, lexical)
|
||||
else:
|
||||
_mkdir_below_home(home, target)
|
||||
try:
|
||||
is_dir = stat.S_ISDIR(home.stat().st_mode)
|
||||
except FileNotFoundError:
|
||||
return target
|
||||
if not is_dir:
|
||||
raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), str(home))
|
||||
repair_user_dir(home)
|
||||
return target
|
||||
|
||||
|
||||
def _mkdir_below_home(home: Path, path: Path) -> None:
|
||||
"""``make_user_dir(path, exist_ok=True)`` leaf first, for *path* strictly below *home*: an
|
||||
existing leaf gets only its usual repair and existing ancestors are never touched. A missing
|
||||
parent is created the same way first, but never *home*: its absence is the caller's error."""
|
||||
"""Create *path* leaf first, its missing parents likewise, never *home* itself."""
|
||||
from hermes_dir_acl import make_user_dir
|
||||
try:
|
||||
make_user_dir(path, exist_ok=True)
|
||||
|
||||
@@ -452,13 +452,11 @@ def make_user_dir(path: str | Path, mode: int = 0o777, *, parents: bool = False,
|
||||
return target
|
||||
|
||||
|
||||
def repair_user_dir(path: str | Path, *, elevated: bool | None = None) -> None:
|
||||
"""The existing-leaf repair of :func:`make_user_dir` without its ``mkdir``: elevated, an existing
|
||||
directory is granted once per directory object (and what is already inside it, when the write was
|
||||
needed); a missing *path* stays missing. For a caller that must never create *path* (a named
|
||||
profile home that a delete or rename may have just removed)."""
|
||||
def repair_user_dir(path: str | Path) -> None:
|
||||
""":func:`make_user_dir`'s existing-leaf repair without its ``mkdir``: elevated, an existing
|
||||
directory gets the same once-per-object grant attempt; a missing *path* stays missing."""
|
||||
target = Path(path)
|
||||
if _elevated(elevated) and target.is_dir():
|
||||
if process_is_elevated() and target.is_dir():
|
||||
_grant_dirs(target, [target])
|
||||
|
||||
|
||||
|
||||
@@ -321,24 +321,19 @@ class TestNamedProfileHome:
|
||||
|
||||
|
||||
class TestMkdirBoundaryNeverRecreatesNamedHome:
|
||||
"""``mkdir_under_hermes_home`` checks the home is live, then creates. A delete or rename landing in
|
||||
between must make the write fail, never let the boundary re-create the home itself: a config save
|
||||
then left a live duplicate of a renamed profile under its old name (no tombstone on a plain
|
||||
rename). Only the directories strictly below a named home are ever created."""
|
||||
|
||||
@staticmethod
|
||||
def _after_liveness_check(monkeypatch, action):
|
||||
"""Run *action* (a real delete/rename) right after the boundary's real liveness check passes."""
|
||||
import hermes_constants
|
||||
|
||||
real = hermes_constants.assert_named_profile_home_live
|
||||
fired = []
|
||||
|
||||
def check_then_act(path):
|
||||
real(path)
|
||||
home = real(path)
|
||||
if not fired:
|
||||
fired.append(path)
|
||||
action()
|
||||
return home
|
||||
|
||||
monkeypatch.setattr(hermes_constants, "assert_named_profile_home_live", check_then_act)
|
||||
return fired
|
||||
@@ -373,6 +368,33 @@ class TestMkdirBoundaryNeverRecreatesNamedHome:
|
||||
assert fired and not profile_dir.exists()
|
||||
assert "worker" not in _named_homes(profile_env)
|
||||
|
||||
def test_custom_root_losing_its_marker_mid_call_does_not_recreate_the_home(self, tmp_path, monkeypatch):
|
||||
from hermes_constants import mkdir_under_hermes_home
|
||||
|
||||
root = tmp_path / "custom"
|
||||
home = root / "profiles" / "worker"
|
||||
home.mkdir(parents=True)
|
||||
(root / "config.yaml").write_text("x", encoding="utf-8")
|
||||
|
||||
def delete_marker_and_home():
|
||||
(root / "config.yaml").unlink()
|
||||
home.rmdir()
|
||||
|
||||
fired = self._after_liveness_check(monkeypatch, delete_marker_and_home)
|
||||
with pytest.raises(FileNotFoundError):
|
||||
mkdir_under_hermes_home(home / "logs")
|
||||
assert fired and not home.exists()
|
||||
|
||||
def test_regular_file_at_named_home_is_not_a_successful_mkdir(self, profile_env):
|
||||
from hermes_constants import mkdir_under_hermes_home
|
||||
|
||||
home = create_profile("worker", no_alias=True, no_skills=True)
|
||||
home.rename(home.with_name("moved"))
|
||||
home.write_text("not a directory", encoding="utf-8")
|
||||
with pytest.raises(FileExistsError):
|
||||
mkdir_under_hermes_home(home)
|
||||
assert home.read_text(encoding="utf-8") == "not a directory"
|
||||
|
||||
def test_live_named_home_creates_only_below_it(self, profile_env, monkeypatch):
|
||||
from hermes_constants import mkdir_under_hermes_home
|
||||
|
||||
@@ -396,10 +418,7 @@ class TestMkdirBoundaryNeverRecreatesNamedHome:
|
||||
|
||||
|
||||
class TestMkdirBoundaryElevatedGrantSelection:
|
||||
"""Which dirs an elevated Windows process would grant through ``mkdir_under_hermes_home``: the same
|
||||
as the ``parents=True`` call it replaced (fresh dirs, an existing leaf once per object, the home
|
||||
when it is the target) and never an existing ancestor merely on the way to the leaf. Elevation is
|
||||
the host fact and the grant a recorder, as in tests/test_hermes_dir_acl.py; no ACL is written."""
|
||||
"""Grant recorder under forced elevation (as in tests/test_hermes_dir_acl.py); no ACL is written."""
|
||||
|
||||
@pytest.fixture()
|
||||
def granted(self, monkeypatch):
|
||||
@@ -413,7 +432,6 @@ class TestMkdirBoundaryElevatedGrantSelection:
|
||||
|
||||
@staticmethod
|
||||
def _forget_creation(granted):
|
||||
"""Drop what creating the fixture profile granted (and memoized), as a later process sees it."""
|
||||
import hermes_dir_acl
|
||||
|
||||
granted.clear()
|
||||
@@ -428,7 +446,7 @@ class TestMkdirBoundaryElevatedGrantSelection:
|
||||
assert granted == [home]
|
||||
|
||||
fired = TestMkdirBoundaryNeverRecreatesNamedHome._after_liveness_check(monkeypatch, lambda: _delete("worker"))
|
||||
mkdir_under_hermes_home(home) # removed after the check: the repair sees nothing to grant
|
||||
mkdir_under_hermes_home(home)
|
||||
assert fired and not home.exists() and granted == [home]
|
||||
|
||||
def test_existing_ancestors_are_not_granted_on_the_way_to_the_leaf(self, profile_env, granted):
|
||||
@@ -442,7 +460,16 @@ class TestMkdirBoundaryElevatedGrantSelection:
|
||||
assert granted == [home / "cache" / "media" / "new", home / "cache" / "media" / "new" / "leaf"]
|
||||
mkdir_under_hermes_home(home / "cache" / "media")
|
||||
mkdir_under_hermes_home(home / "cache" / "media")
|
||||
assert granted[2:] == [home / "cache" / "media"] # an existing leaf: repaired once per object
|
||||
assert granted[2:] == [home / "cache" / "media"]
|
||||
|
||||
def test_dotdot_through_a_missing_dir_never_repairs_the_home_tree(self, profile_env, granted):
|
||||
from hermes_constants import mkdir_under_hermes_home
|
||||
|
||||
home = create_profile("worker", no_alias=True, no_skills=True)
|
||||
self._forget_creation(granted)
|
||||
|
||||
mkdir_under_hermes_home(home / "missing" / ".." / "dest")
|
||||
assert granted == [home / "dest"] and (home / "dest").is_dir() and not (home / "missing").exists()
|
||||
|
||||
def test_default_home_grant_selection_is_unchanged(self, profile_env, granted):
|
||||
from hermes_constants import mkdir_under_hermes_home
|
||||
|
||||
@@ -348,21 +348,27 @@ def _no_pywin32(*_a, **_k):
|
||||
|
||||
|
||||
def test_repair_user_dir_grants_an_existing_dir_once_and_never_creates(tmp_path, monkeypatch):
|
||||
"""make_user_dir's existing-leaf repair without the mkdir (a named profile home a delete may
|
||||
have just removed): granted once per directory object, a missing path stays missing."""
|
||||
granted = []
|
||||
monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: True)
|
||||
elevated = [True]
|
||||
monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: elevated[0])
|
||||
monkeypatch.setattr(hermes_dir_acl, "grant_user_access", lambda p, **k: granted.append((p, k)) or True)
|
||||
monkeypatch.setattr(hermes_dir_acl, "_granted", set())
|
||||
left = tmp_path / "home"
|
||||
left.mkdir()
|
||||
hermes_dir_acl.repair_user_dir(left)
|
||||
hermes_dir_acl.repair_user_dir(left)
|
||||
assert granted == [(left, {"elevated": True, "repair_children": True})] # as make_user_dir's repair
|
||||
assert granted == [(left, {"elevated": True, "repair_children": True})]
|
||||
|
||||
left.rmdir()
|
||||
hermes_dir_acl.repair_user_dir(left)
|
||||
assert not left.exists() and len(granted) == 1
|
||||
left.mkdir()
|
||||
hermes_dir_acl.repair_user_dir(left, elevated=False)
|
||||
assert not left.exists()
|
||||
regular_file = tmp_path / "file"
|
||||
regular_file.touch()
|
||||
hermes_dir_acl.repair_user_dir(regular_file)
|
||||
assert len(granted) == 1
|
||||
|
||||
elevated[0] = False
|
||||
ungranted = tmp_path / "ungranted"
|
||||
ungranted.mkdir()
|
||||
hermes_dir_acl.repair_user_dir(ungranted)
|
||||
assert len(granted) == 1
|
||||
|
||||
Reference in New Issue
Block a user