okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-ctl: GitHub setup, Docker, docs and bench items for 0.2.7538acd098

main
26.2 KiB579 linesraw
1"""Owner-only files on every platform.
2
3POSIX keeps what the code always did (``0600`` files, ``0700`` directories). NTFS has no mode bits,
4so on Windows the same promise is an ACL: a protected (non-inherited) DACL with exactly one
5allow entry, for the current user. This uses ``advapi32`` through ``ctypes``; there is no
6``pywin32`` or ``icacls`` dependency and no output parsing that depends on the display language.
7"""
8from __future__ import annotations
9
10import os
11import re
12from pathlib import Path
13
14WINDOWS = os.name == "nt"
15
16if WINDOWS:
17    import ctypes
18    from ctypes import wintypes
19
20    _advapi = ctypes.WinDLL("advapi32", use_last_error=True)
21    _kernel = ctypes.WinDLL("kernel32", use_last_error=True)
22
23    _kernel.GetCurrentProcess.restype = wintypes.HANDLE
24    _kernel.LocalFree.argtypes = [ctypes.c_void_p]
25    _kernel.LocalFree.restype = ctypes.c_void_p
26    _kernel.CloseHandle.argtypes = [wintypes.HANDLE]
27    _advapi.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
28    _advapi.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD,
29                                            ctypes.POINTER(wintypes.DWORD)]
30    _advapi.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)]
31    _advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
32        wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p]
33    _advapi.GetSecurityDescriptorDacl.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.BOOL),
34                                                  ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.BOOL)]
35    _advapi.SetNamedSecurityInfoW.argtypes = [wintypes.LPWSTR, ctypes.c_int, wintypes.DWORD, ctypes.c_void_p,
36                                              ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
37    _advapi.SetNamedSecurityInfoW.restype = wintypes.DWORD
38    _advapi.GetNamedSecurityInfoW.argtypes = [wintypes.LPCWSTR, ctypes.c_int, wintypes.DWORD, ctypes.c_void_p,
39                                              ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p,
40                                              ctypes.POINTER(ctypes.c_void_p)]
41    _advapi.GetNamedSecurityInfoW.restype = wintypes.DWORD
42    _advapi.ConvertSecurityDescriptorToStringSecurityDescriptorW.argtypes = [
43        ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(wintypes.LPWSTR), ctypes.c_void_p]
44    _advapi.ConvertStringSidToSidW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p)]
45    _advapi.SetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
46    _advapi.LookupPrivilegeValueW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.c_void_p]
47    _advapi.AdjustTokenPrivileges.argtypes = [wintypes.HANDLE, wintypes.BOOL, ctypes.c_void_p, wintypes.DWORD,
48                                              ctypes.c_void_p, ctypes.c_void_p]
49
50_SE_FILE_OBJECT = 1
51_DACL = 0x4
52_PROTECTED_DACL = 0x80000000
53_TOKEN_QUERY = 0x8
54_TOKEN_ADJUST_PRIVILEGES = 0x20
55_TOKEN_ADJUST_DEFAULT = 0x80
56_TOKEN_OWNER = 4
57_TOKEN_DEFAULT_DACL = 6
58_OWNER = 0x1
59_TOKEN_USER = 1
60_SDDL_REVISION_1 = 1
61_sid_cache: str | None = None
62
63
64def _winerr(what: str, code: int | None = None) -> OSError:
65    return ctypes.WinError(code if code is not None else ctypes.get_last_error(), what)  # type: ignore[attr-defined]
66
67
68def current_user_sid() -> str:
69    """The string SID of the user this process runs as (Windows only)."""
70    global _sid_cache
71    if not WINDOWS:
72        raise OSError("SIDs exist on Windows only")
73    if _sid_cache:
74        return _sid_cache
75    token = wintypes.HANDLE()
76    if not _advapi.OpenProcessToken(_kernel.GetCurrentProcess(), _TOKEN_QUERY, ctypes.byref(token)):
77        raise _winerr("OpenProcessToken")
78    try:
79        needed = wintypes.DWORD()
80        _advapi.GetTokenInformation(token, _TOKEN_USER, None, 0, ctypes.byref(needed))
81        buffer = ctypes.create_string_buffer(needed.value)
82        if not _advapi.GetTokenInformation(token, _TOKEN_USER, buffer, needed, ctypes.byref(needed)):
83            raise _winerr("GetTokenInformation")
84        psid = ctypes.c_void_p.from_buffer(buffer).value  # TOKEN_USER starts with the SID pointer
85        text = wintypes.LPWSTR()
86        if not _advapi.ConvertSidToStringSidW(psid, ctypes.byref(text)):
87            raise _winerr("ConvertSidToStringSidW")
88        try:
89            _sid_cache = text.value
90        finally:
91            _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p))
92    finally:
93        _kernel.CloseHandle(token)
94    assert _sid_cache
95    return _sid_cache
96
97
98def _same_sid(sddl_trustee: str, sid: str) -> bool:
99    """True when an SDDL trustee names ``sid``. SDDL prints well-known accounts as two-letter aliases (the built-in
100    Administrator, RID 500, is ``LA``), so an alias is turned into its string SID before the compare (#3302)."""
101    if sddl_trustee == sid:
102        return True
103    if not WINDOWS:
104        return False
105    return _string_sid(sddl_trustee) == sid.upper()
106
107
108def restrict_to_current_user(path: str | os.PathLike, *, directory: bool | None = None) -> None:
109    """Make ``path`` readable and writable by the current user only.
110
111    POSIX: ``chmod 0600`` (``0700`` for a directory). Windows: replace the DACL with one protected
112    entry granting the current user full control (inherited by children when ``path`` is a
113    directory) and drop every inherited entry.
114    """
115    path = os.fspath(path)
116    if directory is None:
117        directory = os.path.isdir(path)
118    if not WINDOWS:
119        os.chmod(path, 0o700 if directory else 0o600)
120        return
121    flags = "OICI" if directory else ""
122    sddl = f"D:PAI(A;{flags};FA;;;{current_user_sid()})"
123    descriptor = ctypes.c_void_p()
124    if not _advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW(
125            sddl, _SDDL_REVISION_1, ctypes.byref(descriptor), None):
126        raise _winerr("ConvertStringSecurityDescriptorToSecurityDescriptorW")
127    try:
128        present, defaulted, dacl = wintypes.BOOL(), wintypes.BOOL(), ctypes.c_void_p()
129        if not _advapi.GetSecurityDescriptorDacl(descriptor, ctypes.byref(present), ctypes.byref(dacl),
130                                                 ctypes.byref(defaulted)) or not present.value:
131            raise _winerr("GetSecurityDescriptorDacl")
132        # The explicit entry for the user's own SID is what makes the file reachable from a normal (non-elevated) session:
133        # a file made by an elevated process is owned by BUILTIN\Administrators, and a rule naming only SYSTEM,
134        # Administrators and OWNER RIGHTS shuts the same person out when UAC filters Administrators from their token.
135        # So the owner becomes the user too, where Windows allows it; when it does not, the explicit entry still stands.
136        owner = _user_psid()
137        code = _advapi.SetNamedSecurityInfoW(path, _SE_FILE_OBJECT, _OWNER | _DACL | _PROTECTED_DACL,
138                                             owner, None, dacl, None) if owner else 1
139        if code:
140            code = _advapi.SetNamedSecurityInfoW(path, _SE_FILE_OBJECT, _DACL | _PROTECTED_DACL,
141                                                 None, None, dacl, None)
142        if code:
143            raise _winerr(f"SetNamedSecurityInfoW {path}", code)
144    finally:
145        _kernel.LocalFree(descriptor)
146
147
148def dacl_sddl(path: str | os.PathLike) -> str:
149    """The DACL of ``path`` as an SDDL string such as ``D:PAI(A;;FA;;;S-1-5-21-...)`` (Windows only)."""
150    if not WINDOWS:
151        raise OSError("DACLs exist on Windows only")
152    descriptor = ctypes.c_void_p()
153    code = _advapi.GetNamedSecurityInfoW(os.fspath(path), _SE_FILE_OBJECT, _DACL, None, None, None, None,
154                                         ctypes.byref(descriptor))
155    if code:
156        raise _winerr(f"GetNamedSecurityInfoW {path}", code)
157    try:
158        text = wintypes.LPWSTR()
159        if not _advapi.ConvertSecurityDescriptorToStringSecurityDescriptorW(
160                descriptor, _SDDL_REVISION_1, _DACL, ctypes.byref(text), None):
161            raise _winerr("ConvertSecurityDescriptorToStringSecurityDescriptorW")
162        try:
163            return text.value
164        finally:
165            _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p))
166    finally:
167        _kernel.LocalFree(descriptor)
168
169
170def is_private(path: str | os.PathLike) -> bool:
171    """True when only the current user can reach ``path``.
172
173    POSIX: no group or other permission bits. Windows: the DACL is protected (no inherited entries)
174    and consists of exactly one allow entry for the current user.
175    """
176    if not WINDOWS:
177        return not (os.lstat(path).st_mode & 0o077)
178    if not volume_has_acls(path):
179        return True                                   # FAT / exFAT: there are no permissions to check
180    sddl = dacl_sddl(path)
181    head = sddl.split("(", 1)[0]
182    entries = re.findall(r"\(([^()]*)\)", sddl)
183    if not head.startswith("D:") or "P" not in head[2:] or len(entries) != 1:
184        return False
185    fields = entries[0].split(";")
186    return len(fields) >= 6 and fields[0] == "A" and _same_sid(fields[5], current_user_sid())
187
188
189def is_unshared(path: str | os.PathLike) -> bool:
190    """True when nobody but this user, SYSTEM and the administrators can reach ``path``.
191
192    The relaxed form of :func:`is_private`, for files created under the user's profile where the
193    inherited ACL already shuts out other accounts: any allow entry for Everyone, Users,
194    Authenticated Users or another account makes it False. POSIX is the same check as
195    :func:`is_private`.
196    """
197    if not WINDOWS:
198        return is_private(path)
199    if not volume_has_acls(path):
200        return True                                   # FAT / exFAT: there are no permissions to check
201    return not unshared_offenders(dacl_sddl(path))
202
203
204def volume_has_acls(path: str | os.PathLike) -> bool:
205    """False for a drive without file permissions (FAT, exFAT); True for NTFS/ReFS, and when it cannot be told (Windows only)."""
206    if not WINDOWS:
207        return True
208    try:
209        drive = os.path.splitdrive(os.path.abspath(os.fspath(path)))[0]
210        if not drive:
211            return True
212        flags = wintypes.DWORD()
213        fn = _kernel.GetVolumeInformationW
214        fn.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p,
215                       ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR, wintypes.DWORD]
216        if not fn(drive.rstrip("\\") + "\\", None, 0, None, None, ctypes.byref(flags), None, 0):
217            return True
218        return bool(flags.value & 0x00000008)         # FILE_PERSISTENT_ACLS
219    except (OSError, ValueError):
220        return True
221
222
223_ACCOUNT_NAMES = {"WD": "Everyone", "BU": "Users", "AU": "Authenticated Users", "IU": "Interactive users",
224                  "NU": "Network users", "AN": "Anonymous", "DU": "Domain Users", "S-1-1-0": "Everyone",
225                  "S-1-5-32-545": "Users", "S-1-5-11": "Authenticated Users", "S-1-5-4": "Interactive users"}
226
227
228def _string_sid(trustee: str) -> str:
229    """An SDDL trustee (a string SID or a two-letter alias such as LA, BA, SY, WD) as an upper-case string SID; the text itself
230    when Windows does not know it."""
231    if trustee.upper().startswith("S-1-"):
232        return trustee.upper()
233    pointer = ctypes.c_void_p()
234    if not _advapi.ConvertStringSidToSidW(trustee, ctypes.byref(pointer)):
235        return trustee.upper()
236    try:
237        text = wintypes.LPWSTR()
238        if not _advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)):
239            return trustee.upper()
240        try:
241            return text.value.upper()
242        finally:
243            _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p))
244    finally:
245        _kernel.LocalFree(pointer)
246
247
248def _is_privileged_sid(sid: str) -> bool:
249    """SYSTEM, the Administrators group, the built-in Administrator account (RID 500, SDDL "LA"), OWNER RIGHTS / CREATOR OWNER / GROUP."""
250    return sid in ("S-1-5-18", "S-1-5-32-544", "S-1-3-4", "S-1-3-0", "S-1-3-1") or \
251        re.fullmatch(r"S-1-5-21-[0-9-]+-500", sid) is not None
252
253
254def unshared_offenders(sddl: str) -> list[str]:
255    """The trustees of an SDDL DACL that make the object reachable by someone besides this user, SYSTEM and the administrators:
256    every allow entry that applies to the object itself, whatever form its account is written in (a string SID or an alias such
257    as LA).  An inherit-only entry (flag IO) is for the children of a folder, not for the folder, and is left out."""
258    me = current_user_sid().upper()
259    out: list[str] = []
260    for entry in re.findall(r"\(([^()]*)\)", sddl):
261        fields = entry.split(";")
262        if len(fields) < 6 or fields[0] not in ("A", "OA") or "IO" in re.findall("..", fields[1].upper()):
263            continue
264        sid = _string_sid(fields[5])
265        if sid == me or _is_privileged_sid(sid) or fields[5].upper() in ("SY", "BA", "OW", "CO", "CG", "LA"):
266            continue
267        if fields[5] not in out:
268            out.append(fields[5])
269    return out
270
271
272def account_name(trustee: str) -> str:
273    """A plain name for an SDDL trustee (Everyone, Users, DOMAIN\\name), or the SID text when it cannot be looked up."""
274    plain = _ACCOUNT_NAMES.get(trustee.upper()) or _ACCOUNT_NAMES.get(_string_sid(trustee))
275    if plain or not WINDOWS:
276        return plain or trustee
277    pointer = ctypes.c_void_p()
278    if not _advapi.ConvertStringSidToSidW(trustee, ctypes.byref(pointer)):
279        return trustee
280    try:
281        name, domain = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(256)
282        n, d, use = wintypes.DWORD(256), wintypes.DWORD(256), wintypes.DWORD()
283        lookup = _advapi.LookupAccountSidW
284        lookup.argtypes = [wintypes.LPCWSTR, ctypes.c_void_p, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD),
285                           wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD)]
286        if lookup(None, pointer, name, ctypes.byref(n), domain, ctypes.byref(d), ctypes.byref(use)):
287            return f"{domain.value}\\{name.value}" if domain.value else name.value
288        return trustee
289    finally:
290        _kernel.LocalFree(pointer)
291
292
293def who_can_reach(path: str | os.PathLike) -> list[str]:
294    """Plain names of the accounts besides this user, SYSTEM and the administrators that can reach ``path`` (Windows; [] elsewhere)."""
295    if not WINDOWS:
296        return []
297    return [account_name(t) for t in unshared_offenders(dacl_sddl(path))]
298
299
300# ---------------------------------------------------------------------------------------------- access repair
301
302def _user_psid():
303    """The current user's SID as a native pointer (kept for the life of the process), or None."""
304    global _psid_cache
305    if not WINDOWS:
306        return None
307    if _psid_cache is not None:
308        return _psid_cache
309    pointer = ctypes.c_void_p()
310    if not _advapi.ConvertStringSidToSidW(current_user_sid(), ctypes.byref(pointer)):
311        return None
312    _psid_cache = pointer.value
313    return _psid_cache
314
315
316_psid_cache = None
317_keep: list = []
318
319
320def private_mkdir(path: str | os.PathLike, *, parents: bool = False, exist_ok: bool = True) -> Path:
321    """Create a folder only the user can reach, on every platform.
322
323    POSIX: ``mkdir(mode=0o700)``. Windows: Python 3.13 turns ``mode=0o700`` into an ACL of SYSTEM, Administrators and OWNER
324    RIGHTS (inherited by everything inside), which locks the user out when an elevated process created the folder. This
325    creates the missing folders plainly and gives each one the explicit entry for the user's own SID (and the user as owner).
326    """
327    target = Path(path)
328    if not WINDOWS:
329        target.mkdir(mode=0o700, parents=parents, exist_ok=exist_ok)
330        return target
331    missing = []
332    probe = target
333    while not probe.exists() and probe != probe.parent:
334        missing.append(probe)
335        if not parents:
336            break
337        probe = probe.parent
338    if not missing and not exist_ok:
339        raise FileExistsError(str(target))
340    for folder in reversed(missing):
341        folder.mkdir(exist_ok=exist_ok)
342        try:
343            restrict_to_current_user(folder, directory=True)
344        except OSError:
345            pass            # the folder exists with its inherited rule; a later read repairs it if that is not enough
346    return target
347
348
349def adopt_user_defaults() -> bool:
350    """Make files this process creates belong to, and be open to, the user (Windows; no effect elsewhere).
351
352    An elevated process otherwise creates files owned by BUILTIN\\Administrators with a default rule of SYSTEM and
353    Administrators only. Setting the token's default owner and default rule to the user's own SID fixes that for every file
354    the process (and what it starts) creates afterwards. Returns True when both were set; never raises.
355    """
356    if not WINDOWS:
357        return False
358    try:
359        sid = current_user_sid()
360        psid = _user_psid()
361        token = wintypes.HANDLE()
362        if not psid or not _advapi.OpenProcessToken(_kernel.GetCurrentProcess(), _TOKEN_QUERY | _TOKEN_ADJUST_DEFAULT,
363                                                    ctypes.byref(token)):
364            return False
365        try:
366            class _Owner(ctypes.Structure):
367                _fields_ = [("owner", ctypes.c_void_p)]
368
369            class _DefaultDacl(ctypes.Structure):
370                _fields_ = [("dacl", ctypes.c_void_p)]
371
372            ok_owner = bool(_advapi.SetTokenInformation(token, _TOKEN_OWNER, ctypes.byref(_Owner(psid)),
373                                                        ctypes.sizeof(_Owner)))
374            descriptor = ctypes.c_void_p()
375            # A token default DACL also applies to processes, not just files. FA is
376            # FILE_ALL_ACCESS (0x1f01ff), which omits process query/set-information.
377            # GA is mapped to the full rights of the object being created.
378            if not _advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW(
379                    f"D:(A;;GA;;;{sid})(A;;GA;;;SY)(A;;GA;;;BA)", _SDDL_REVISION_1, ctypes.byref(descriptor), None):
380                return False
381            present, defaulted, dacl = wintypes.BOOL(), wintypes.BOOL(), ctypes.c_void_p()
382            if not _advapi.GetSecurityDescriptorDacl(descriptor, ctypes.byref(present), ctypes.byref(dacl),
383                                                     ctypes.byref(defaulted)) or not present.value:
384                return False
385            _keep.append(descriptor)           # the token keeps pointing into it
386            ok_dacl = bool(_advapi.SetTokenInformation(token, _TOKEN_DEFAULT_DACL, ctypes.byref(_DefaultDacl(dacl.value)),
387                                                       ctypes.sizeof(_DefaultDacl)))
388            return ok_owner and ok_dacl
389        finally:
390            _kernel.CloseHandle(token)
391    except OSError:
392        return False
393
394
395def _enable_privilege(name: str) -> bool:
396    token = wintypes.HANDLE()
397    if not _advapi.OpenProcessToken(_kernel.GetCurrentProcess(), _TOKEN_QUERY | _TOKEN_ADJUST_PRIVILEGES,
398                                    ctypes.byref(token)):
399        return False
400    try:
401        class _Luid(ctypes.Structure):
402            _fields_ = [("low", wintypes.DWORD), ("high", ctypes.c_long)]
403
404        class _Privileges(ctypes.Structure):
405            _fields_ = [("count", wintypes.DWORD), ("luid", _Luid), ("attributes", wintypes.DWORD)]
406
407        luid = _Luid()
408        if not _advapi.LookupPrivilegeValueW(None, name, ctypes.byref(luid)):
409            return False
410        privileges = _Privileges(1, luid, 2)  # SE_PRIVILEGE_ENABLED
411        ctypes.set_last_error(0)
412        _advapi.AdjustTokenPrivileges(token, False, ctypes.byref(privileges), ctypes.sizeof(privileges), None, None)
413        return ctypes.get_last_error() == 0
414    finally:
415        _kernel.CloseHandle(token)
416
417
418def user_roots() -> list[Path]:
419    """The folders that are the user's own per-user data: a file inside one may be repaired by that user."""
420    roots: list[Path] = []
421    for key in ("APPDATA", "LOCALAPPDATA", "STRATA_HOME", "STRATA_PROFILE_DIR", "STRATA_INSTALL_DIR", "STRATA_RUNTIME_DIR",
422                "STRATA_STATE_DIR"):
423        value = os.environ.get(key)
424        if value:
425            roots.append(Path(value))
426    roots.append(Path.home())
427    result = []
428    for root in roots:
429        try:
430            result.append(root.resolve())
431        except OSError:
432            continue
433    return result
434
435
436def is_users_own(path: str | os.PathLike) -> bool:
437    """True when ``path`` is inside the user's own profile or data folders (never the system folders)."""
438    try:
439        target = Path(path).resolve()
440    except OSError:
441        return False
442    return any(target == root or root in target.parents for root in user_roots())
443
444
445def repair_access(path: str | os.PathLike, *, tree: bool = True) -> bool:
446    """Give the current user back a file or folder in their own data folders that an elevated process locked them out of.
447
448    Takes ownership and writes the explicit protected entry for the user's SID (a folder's children are repaired too).
449    Needs the right to do that: an elevated session, or a user holding the take-ownership right; a normal session locked
450    out by someone else's elevated process cannot do it, and this returns False (the caller shows the plain message).
451    Windows only; elsewhere there is nothing to repair. Refuses anything outside the user's own folders.
452    """
453    if not WINDOWS or not is_users_own(path):
454        return False
455    _enable_privilege("SeTakeOwnershipPrivilege")
456    _enable_privilege("SeRestorePrivilege")
457    fixed = True
458    target = Path(path)
459    try:
460        restrict_to_current_user(target, directory=target.is_dir())
461    except OSError:
462        fixed = False
463    if tree and fixed and target.is_dir():
464        try:
465            for dirpath, dirnames, filenames in os.walk(target):
466                for name in dirnames + filenames:
467                    child = os.path.join(dirpath, name)
468                    if os.path.islink(child):
469                        continue
470                    try:
471                        restrict_to_current_user(child, directory=os.path.isdir(child))
472                    except OSError:
473                        fixed = False
474        except OSError:
475            fixed = False
476    return fixed
477
478
479def read_bytes_repairing(path: str | os.PathLike) -> bytes:
480    """``Path.read_bytes`` that, on an access error in the user's own folders, repairs the access once and tries again."""
481    target = Path(path)
482    try:
483        return target.read_bytes()
484    except PermissionError:
485        if not repair_access(target, tree=False):
486            raise
487        return target.read_bytes()
488
489
490ACCESS_MESSAGE = ("Strata is not allowed to open one of its own files. Run `strata repair-access` (or press Repair in the app); "
491                "these files were probably made while Strata ran as administrator, so run it as your normal user from now on.")
492IN_USE_MESSAGE = ("A file Strata needs is in use by another program (usually antivirus, a backup or a sync tool). "
493                  "Wait a moment and run the same command again.")
494
495
496def is_sharing_violation(error: BaseException) -> bool:
497    """Windows "file in use" (WinError 32 or 33), as opposed to a real refusal (WinError 5): waiting helps, repairing does not."""
498    code = getattr(error, "winerror", None)
499    if code in (32, 33):
500        return True
501    text = str(error)
502    return "WinError 32" in text or "WinError 33" in text or "being used by another process" in text
503
504
505_SKIP_DIRS = {"models", "node_modules", "harness", "python", "host", "node", "control", "__pycache__", ".git"}
506_SKIP_SUFFIXES = (".gguf", ".part", ".bin", ".safetensors", ".zip", ".exe", ".dll")
507
508
509def known_roots() -> list[Path]:
510    """Strata's per-user data folders: APPDATA/Strata, LOCALAPPDATA/Strata and ~/.strata (plus the STRATA_* overrides)."""
511    roots: list[Path] = []
512    for key, sub in (("APPDATA", "Strata"), ("LOCALAPPDATA", "Strata")):
513        value = os.environ.get(key)
514        if value:
515            roots.append(Path(value) / sub)
516    roots.append(Path.home() / ".strata")
517    for key in ("STRATA_HOME", "STRATA_PROFILE_DIR", "STRATA_RUNTIME_DIR", "STRATA_STATE_DIR", "STRATA_INSTALL_DIR"):
518        value = os.environ.get(key)
519        if value:
520            roots.append(Path(value))
521    seen, result = set(), []
522    for root in roots:
523        key = str(root).lower()
524        if key not in seen and root.exists():
525            seen.add(key)
526            result.append(root)
527    return result
528
529
530def repair_known_roots(*, limit: int = 20000) -> dict:
531    """Walk Strata's own per-user folders and repair every entry the user cannot open (Windows).
532
533    Meant to run when Strata starts: files and folders an elevated run created (owner Administrators, a rule that names
534    only SYSTEM, Administrators and OWNER RIGHTS) are given back to the user. A normal session can only repair what its
535    own token may change; an elevated start repairs everything. Never raises; returns what it did.
536    """
537    report = {"checked": 0, "repaired": 0, "failed": 0}
538    if not WINDOWS:
539        return report
540    for root in known_roots():
541        stack = [root]
542        while stack and report["checked"] < limit:
543            folder = stack.pop()
544            try:
545                entries = list(os.scandir(folder))
546            except PermissionError:
547                report["checked"] += 1
548                if repair_access(folder, tree=False):
549                    report["repaired"] += 1
550                    try:
551                        entries = list(os.scandir(folder))
552                    except OSError:
553                        continue
554                else:
555                    report["failed"] += 1
556                    continue
557            except OSError:
558                continue
559            for entry in entries:
560                report["checked"] += 1
561                try:
562                    if entry.is_symlink():
563                        continue
564                    if entry.is_dir(follow_symlinks=False):
565                        if entry.name.lower() not in _SKIP_DIRS:
566                            stack.append(Path(entry.path))
567                        continue
568                    if entry.name.lower().endswith(_SKIP_SUFFIXES):
569                        continue
570                    with open(entry.path, "rb"):
571                        pass
572                except PermissionError:
573                    if repair_access(entry.path, tree=False):
574                        report["repaired"] += 1
575                    else:
576                        report["failed"] += 1
577                except OSError:
578                    continue
579    return report