Skip to content
Open
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
103 changes: 94 additions & 9 deletions core/private_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,23 @@
import stat
import subprocess
import threading
import time
from functools import lru_cache
from pathlib import Path

PRIVATE_DIRECTORY_MODE = 0o700
PRIVATE_FILE_MODE = 0o600

# ``harden_private_tree`` is a repair sweep, not part of the write path: every
# path DeepCode creates is restricted when it is created. Re-walking a mature
# session tree on each start costs one ``icacls`` process per entry, which took
# the interactive client twenty seconds to draw on a few hundred sessions and
# only gets worse as the tree grows. The sweep therefore runs at most once per
# interval on Windows; the stamp records when it last completed. Callers that
# need an immediate repair pass ``force=True``.
_ACL_SWEEP_STAMP_NAME = ".acl-sweep"
_ACL_SWEEP_INTERVAL_SECONDS = 7 * 24 * 60 * 60


class UnsafePrivateFileError(OSError):
"""A private-state path is not a regular file owned by this path entry."""
Expand Down Expand Up @@ -95,19 +106,39 @@ def _windows_icacls() -> str | None:
# How long the caller waits for the whole spawn before giving up and leaving the
# ACLs as they are. See _run_icacls for why that wait has to exist.
_ICACLS_ABANDON_AFTER_SECONDS = _ICACLS_TIMEOUT_SECONDS + 5.0


def _run_icacls(executable: str, path: Path, *arguments: str) -> bool:
# A restriction is a grant, a strip and a cleanup. Each may be abandoned when
# process creation itself stalls, so the three calls share one budget: three
# 20-second waits in a row would add up to the exact minute a test watchdog
# allows and turn a degraded host into a wedged run.
_ACL_TOTAL_BUDGET_SECONDS = 10.0
# Once a spawn is abandoned, later ones are likely to stall the same way. Stop
# paying the budget for a while (the ACLs stay as they were, which is the
# documented fail-safe) instead of stalling every connect of a busy runtime.
_ICACLS_SPAWN_STALL_COOLDOWN_SECONDS = 120.0
_spawn_stalled_until = 0.0


def _run_icacls(
executable: str,
path: Path,
*arguments: str,
abandon_after: float | None = None,
) -> bool:
"""Run one bounded icacls operation and report whether it succeeded.

Bounded end to end: both the child's run *and* its creation are covered, because
the caller must never be able to hang here. ``subprocess``'s own ``timeout``
only starts once the process exists, and ``CreateProcess`` itself is unbounded,
so the spawn runs on a daemon worker thread that may be abandoned mid-flight.
``abandon_after`` shortens that wait when the caller has a shared deadline.
"""

global _spawn_stalled_until
if time.monotonic() < _spawn_stalled_until:
return False
completed = threading.Event()
succeeded: list[bool] = []
wait = _ICACLS_ABANDON_AFTER_SECONDS if abandon_after is None else abandon_after

def _attempt() -> None:
try:
Expand All @@ -132,7 +163,11 @@ def _attempt() -> None:

worker = threading.Thread(target=_attempt, name="deepcode-icacls", daemon=True)
worker.start()
if not completed.wait(_ICACLS_ABANDON_AFTER_SECONDS):
if not completed.wait(max(0.0, wait)):
# Process creation is stalling; paying the budget again for every
# subsequent path would wedge whatever is waiting on us. Leave the ACLs
# as inherited (fail safe) and let the next repair sweep catch up.
_spawn_stalled_until = time.monotonic() + _ICACLS_SPAWN_STALL_COOLDOWN_SECONDS
return False
return bool(succeeded and succeeded[0])

Expand All @@ -151,17 +186,30 @@ def _restrict_windows_acl(path: Path) -> None:
executable = _windows_icacls()
if identity is None or executable is None:
return
deadline = time.monotonic() + _ACL_TOTAL_BUDGET_SECONDS

def attempt(*arguments: str) -> bool:
remaining = deadline - time.monotonic()
if remaining <= 0:
return False
return _run_icacls(
executable,
path,
*arguments,
abandon_after=min(_ICACLS_ABANDON_AFTER_SECONDS, remaining),
)

grant = f"{identity}:{'(OI)(CI)' if path.is_dir() else ''}F"
if not _run_icacls(executable, path, "/grant:r", grant):
if not attempt("/grant:r", grant):
# Fail safe: keep the inherited ACLs; the path stays accessible.
return
if not _run_icacls(executable, path, "/inheritance:r"):
if not attempt("/inheritance:r"):
# Strip failed: the path is merely less restricted, still usable.
return
# ``/inheritance:r`` removes inherited ACEs but deliberately leaves
# explicit entries alone. Remove the broad built-in principals as a final
# best-effort step so hardening also repairs legacy explicit grants.
_run_icacls(executable, path, "/remove", *_WINDOWS_BROAD_ACCESS_SIDS)
attempt("/remove", *_WINDOWS_BROAD_ACCESS_SIDS)


def _open_private_descriptor(target: Path, flags: int) -> tuple[int, bool]:
Expand Down Expand Up @@ -289,12 +337,48 @@ def ensure_private_file(path: Path | str) -> None:
_chmod(target, PRIVATE_FILE_MODE, force=True)


def harden_private_tree(root: Path | str) -> Path:
"""Repair a DeepCode-owned tree while refusing to traverse symlinks."""
def _acl_sweep_is_fresh(base: Path) -> bool:
"""Report whether the last repair sweep is recent enough to skip."""

if os.name != "nt":
return False
try:
stamp = (base / _ACL_SWEEP_STAMP_NAME).stat().st_mtime
except OSError:
return False
return (time.time() - stamp) < _ACL_SWEEP_INTERVAL_SECONDS


def _mark_acl_sweep(base: Path) -> None:
"""Record a completed sweep so the next start can skip it.

Best-effort: losing the stamp only means the next start sweeps again.
"""

if os.name != "nt":
return
try:
(base / _ACL_SWEEP_STAMP_NAME).write_text(
str(int(time.time())), encoding="utf-8"
)
except OSError:
pass


def harden_private_tree(root: Path | str, *, force: bool = False) -> Path:
"""Repair a DeepCode-owned tree while refusing to traverse symlinks.

The repair runs at most once per :data:`_ACL_SWEEP_INTERVAL_SECONDS` on
Windows because it sits in the client's startup path while every entry it
touches is already restricted at creation. Pass ``force=True`` to repair
a tree immediately.
"""

base = ensure_private_directory(root)
if _is_directory_link(base):
raise UnsafePrivateFileError("private storage root must not be a link")
if not force and _acl_sweep_is_fresh(base):
return base

for current, directories, files in os.walk(base, followlinks=False):
current_path = Path(current)
Expand All @@ -306,6 +390,7 @@ def harden_private_tree(root: Path | str) -> Path:
_chmod(current_path / name, PRIVATE_DIRECTORY_MODE, force=True)
for name in files:
ensure_private_file(current_path / name)
_mark_acl_sweep(base)
return base


Expand Down
43 changes: 40 additions & 3 deletions tests/test_private_storage_acl_once.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def test_acl_restriction_orders_grant_strip_and_broad_principal_removal(
monkeypatch.setattr(ps, "_windows_identity", lambda: "DOMAIN\\user")
monkeypatch.setattr(ps, "_windows_icacls", lambda: "trusted-icacls.exe")

def record(executable, path, *arguments):
def record(executable, path, *arguments, **_kwargs):
calls.append((executable, Path(path), arguments))
return True

Expand All @@ -139,7 +139,7 @@ def test_acl_restriction_stops_before_strip_when_grant_fails(
monkeypatch.setattr(ps, "_windows_identity", lambda: "DOMAIN\\user")
monkeypatch.setattr(ps, "_windows_icacls", lambda: "trusted-icacls.exe")

def fail_grant(executable, path, *arguments):
def fail_grant(executable, path, *arguments, **_kwargs):
calls.append(arguments)
return False

Expand All @@ -159,7 +159,7 @@ def test_acl_restriction_does_not_remove_entries_when_strip_fails(
monkeypatch.setattr(ps, "_windows_identity", lambda: "DOMAIN\\user")
monkeypatch.setattr(ps, "_windows_icacls", lambda: "trusted-icacls.exe")

def fail_strip(executable, path, *arguments):
def fail_strip(executable, path, *arguments, **_kwargs):
calls.append(arguments)
return arguments != ("/inheritance:r",)

Expand Down Expand Up @@ -212,3 +212,40 @@ def blocking_spawn(*_args, **_kwargs):
assert started.wait(5) is True, "the spawn was actually attempted"
finally:
release.set()


def test_windows_tree_sweep_is_throttled_to_one_pass_per_interval(
monkeypatch, tmp_path: Path
) -> None:
"""The startup repair sweep must not re-walk a mature tree on every launch.

Every path DeepCode creates is restricted at creation, so re-running the
sweep on each start only spawned one ``icacls`` per entry: a few hundred
sessions stalled the interactive client for ~24s before it drew. The
sweep is now throttled by a stamp inside the tree; ``force=True`` still
requests an immediate repair.
"""

if os.name != "nt":
import pytest

pytest.skip("the startup throttle only exists on Windows")

import core.private_storage as ps

calls = []
monkeypatch.setattr(ps, "_restrict_windows_acl", lambda p: calls.append(p))

root = tmp_path / "private"
(root / "session-1").mkdir(parents=True)
(root / "session-1" / "session.jsonl").write_text("x", encoding="utf-8")

ps.harden_private_tree(root)
after_first = len(calls)
assert after_first >= 3, "the first sweep repairs the tree"

ps.harden_private_tree(root)
assert len(calls) == after_first, "a fresh stamp must skip the second sweep"

ps.harden_private_tree(root, force=True)
assert len(calls) > after_first, "force must sweep again regardless of the stamp"
Loading