Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Fix: Windows runtime folder refused as not owner-only

Niko1221c316a7c2155b
diff --git a/strata_control/private_files.py b/strata_control/private_files.py
index e163c6028..318fee9ab 100644
--- a/strata_control/private_files.py
+++ b/strata_control/private_files.py
@@ -100,21 +100,9 @@ def _same_sid(sddl_trustee: str, sid: str) -> bool:
Administrator, RID 500, is ``LA``), so an alias is turned into its string SID before the compare (#3302)."""
if sddl_trustee == sid:
return True
- if sddl_trustee.upper().startswith("S-1-") or not WINDOWS:
- return False
- pointer = ctypes.c_void_p()
- if not _advapi.ConvertStringSidToSidW(sddl_trustee, ctypes.byref(pointer)):
+ if not WINDOWS:
return False
- try:
- text = wintypes.LPWSTR()
- if not _advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)):
- return False
- try:
- return text.value == sid
- finally:
- _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p))
- finally:
- _kernel.LocalFree(pointer)
+ return _string_sid(sddl_trustee) == sid.upper()
def restrict_to_current_user(path: str | os.PathLike, *, directory: bool | None = None) -> None:
@@ -187,6 +175,8 @@ def is_private(path: str | os.PathLike) -> bool:
"""
if not WINDOWS:
return not (os.lstat(path).st_mode & 0o077)
+ if not volume_has_acls(path):
+ return True # FAT / exFAT: there are no permissions to check
sddl = dacl_sddl(path)
head = sddl.split("(", 1)[0]
entries = re.findall(r"\(([^()]*)\)", sddl)
@@ -196,9 +186,6 @@ def is_private(path: str | os.PathLike) -> bool:
return len(fields) >= 6 and fields[0] == "A" and _same_sid(fields[5], current_user_sid())
-_PRIVILEGED = {"SY", "BA", "OW", "CO", "CG", "S-1-5-18", "S-1-5-32-544", "S-1-3-4"}
-
-
def is_unshared(path: str | os.PathLike) -> bool:
"""True when nobody but this user, SYSTEM and the administrators can reach ``path``.
@@ -209,15 +196,105 @@ def is_unshared(path: str | os.PathLike) -> bool:
"""
if not WINDOWS:
return is_private(path)
- sddl = dacl_sddl(path)
- me = current_user_sid()
- allowed = _PRIVILEGED | {me}
+ if not volume_has_acls(path):
+ return True # FAT / exFAT: there are no permissions to check
+ return not unshared_offenders(dacl_sddl(path))
+
+
+def volume_has_acls(path: str | os.PathLike) -> bool:
+ """False for a drive without file permissions (FAT, exFAT); True for NTFS/ReFS, and when it cannot be told (Windows only)."""
+ if not WINDOWS:
+ return True
+ try:
+ drive = os.path.splitdrive(os.path.abspath(os.fspath(path)))[0]
+ if not drive:
+ return True
+ flags = wintypes.DWORD()
+ fn = _kernel.GetVolumeInformationW
+ fn.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p,
+ ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR, wintypes.DWORD]
+ if not fn(drive.rstrip("\\") + "\\", None, 0, None, None, ctypes.byref(flags), None, 0):
+ return True
+ return bool(flags.value & 0x00000008) # FILE_PERSISTENT_ACLS
+ except (OSError, ValueError):
+ return True
+
+
+_ACCOUNT_NAMES = {"WD": "Everyone", "BU": "Users", "AU": "Authenticated Users", "IU": "Interactive users",
+ "NU": "Network users", "AN": "Anonymous", "DU": "Domain Users", "S-1-1-0": "Everyone",
+ "S-1-5-32-545": "Users", "S-1-5-11": "Authenticated Users", "S-1-5-4": "Interactive users"}
+
+
+def _string_sid(trustee: str) -> str:
+ """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
+ when Windows does not know it."""
+ if trustee.upper().startswith("S-1-"):
+ return trustee.upper()
+ pointer = ctypes.c_void_p()
+ if not _advapi.ConvertStringSidToSidW(trustee, ctypes.byref(pointer)):
+ return trustee.upper()
+ try:
+ text = wintypes.LPWSTR()
+ if not _advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)):
+ return trustee.upper()
+ try:
+ return text.value.upper()
+ finally:
+ _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p))
+ finally:
+ _kernel.LocalFree(pointer)
+
+
+def _is_privileged_sid(sid: str) -> bool:
+ """SYSTEM, the Administrators group, the built-in Administrator account (RID 500, SDDL "LA"), OWNER RIGHTS / CREATOR OWNER / GROUP."""
+ 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 \
+ re.fullmatch(r"S-1-5-21-[0-9-]+-500", sid) is not None
+
+
+def unshared_offenders(sddl: str) -> list[str]:
+ """The trustees of an SDDL DACL that make the object reachable by someone besides this user, SYSTEM and the administrators:
+ every allow entry that applies to the object itself, whatever form its account is written in (a string SID or an alias such
+ as LA). An inherit-only entry (flag IO) is for the children of a folder, not for the folder, and is left out."""
+ me = current_user_sid().upper()
+ out: list[str] = []
for entry in re.findall(r"\(([^()]*)\)", sddl):
fields = entry.split(";")
- if (len(fields) >= 6 and fields[0] in ("A", "OA") and fields[5] not in allowed
- and not _same_sid(fields[5], me)):
- return False
- return True
+ if len(fields) < 6 or fields[0] not in ("A", "OA") or "IO" in re.findall("..", fields[1].upper()):
+ continue
+ sid = _string_sid(fields[5])
+ if sid == me or _is_privileged_sid(sid) or fields[5].upper() in ("SY", "BA", "OW", "CO", "CG", "LA"):
+ continue
+ if fields[5] not in out:
+ out.append(fields[5])
+ return out
+
+
+def account_name(trustee: str) -> str:
+ """A plain name for an SDDL trustee (Everyone, Users, DOMAIN\\name), or the SID text when it cannot be looked up."""
+ plain = _ACCOUNT_NAMES.get(trustee.upper()) or _ACCOUNT_NAMES.get(_string_sid(trustee))
+ if plain or not WINDOWS:
+ return plain or trustee
+ pointer = ctypes.c_void_p()
+ if not _advapi.ConvertStringSidToSidW(trustee, ctypes.byref(pointer)):
+ return trustee
+ try:
+ name, domain = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(256)
+ n, d, use = wintypes.DWORD(256), wintypes.DWORD(256), wintypes.DWORD()
+ lookup = _advapi.LookupAccountSidW
+ lookup.argtypes = [wintypes.LPCWSTR, ctypes.c_void_p, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD),
+ wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD)]
+ if lookup(None, pointer, name, ctypes.byref(n), domain, ctypes.byref(d), ctypes.byref(use)):
+ return f"{domain.value}\\{name.value}" if domain.value else name.value
+ return trustee
+ finally:
+ _kernel.LocalFree(pointer)
+
+
+def who_can_reach(path: str | os.PathLike) -> list[str]:
+ """Plain names of the accounts besides this user, SYSTEM and the administrators that can reach ``path`` (Windows; [] elsewhere)."""
+ if not WINDOWS:
+ return []
+ return [account_name(t) for t in unshared_offenders(dacl_sddl(path))]
# ---------------------------------------------------------------------------------------------- access repair
diff --git a/strata_control/runtime.py b/strata_control/runtime.py
index c88a94551..da16698f8 100644
--- a/strata_control/runtime.py
+++ b/strata_control/runtime.py
@@ -109,14 +109,67 @@ def runtime_dir() -> Path:
raise ProfileError("STRATA_RUNTIME_DIR must be absolute")
existed = base.exists()
_private_mkdir(base, parents=True, exist_ok=True)
- if WINDOWS and not existed:
- private_files.restrict_to_current_user(base, directory=True) # no mode bits on NTFS: a protected ACL
details = base.lstat()
+ if WINDOWS and stat.S_ISDIR(details.st_mode):
+ if not private_files.volume_has_acls(base): # exFAT / FAT: no permissions exist, so there is nothing to check
+ _warn_no_acls(base)
+ return base
+ if not existed:
+ _make_private(base) # no mode bits on NTFS: a protected ACL
+ if not _is_private(details, base):
+ # A folder that was there before (made by an elevated install, an older version, or with the parent's ACL inherited) can
+ # name other accounts. It is the user's own state folder: take that away instead of stopping the launch, then check again.
+ _make_private(base)
+ try:
+ details = base.lstat()
+ except OSError:
+ pass
if not stat.S_ISDIR(details.st_mode) or not _is_private(details, base):
- raise ProfileError("runtime directory must be owner-only (mode 0700)", 5)
+ raise ProfileError(_not_private_message(base), 5)
return base
+def _make_private(base: Path) -> None:
+ """Windows: a protected ACL naming this user; where that is refused (a folder made by an elevated run), take ownership first."""
+ try:
+ private_files.restrict_to_current_user(base, directory=True)
+ except OSError:
+ pass
+ if _is_private(None, base): # type: ignore[arg-type] - details are not used on Windows
+ return
+ try:
+ private_files.repair_access(base, tree=False)
+ except OSError:
+ pass
+
+
+_NO_ACL_WARNED: set[str] = set()
+
+
+def _warn_no_acls(base: Path) -> None:
+ if str(base) not in _NO_ACL_WARNED:
+ _NO_ACL_WARNED.add(str(base))
+ print(f"[strata] {base} is on a drive that has no file permissions (FAT or exFAT), so other accounts on this PC could "
+ f"read what Strata keeps there. Use a drive formatted as NTFS if that matters.", file=sys.stderr, flush=True)
+
+
+def _not_private_message(base: Path) -> str:
+ if WINDOWS:
+ try:
+ names = private_files.who_can_reach(base) if base.is_dir() else []
+ readable = True
+ except OSError:
+ names, readable = [], False
+ if not readable:
+ return (f"Strata cannot read the permissions of {base}, the folder where it keeps its running state. Run Strata once as "
+ f"yourself (not as administrator), or delete that folder: Strata makes a private one again.")
+ who = ", ".join(names) if names else "other accounts"
+ return (f"Strata keeps its running state in {base}, and {who} can open that folder. Strata could not change that. "
+ f"Right-click the folder, choose Properties > Security, and remove those accounts (or delete the folder: Strata "
+ f"makes a private one again).")
+ return "runtime directory must be owner-only (mode 0700)"
+
+
def acquire_activity_lease(*, shared: bool) -> int:
"""Let managed hosts coexist while excluding a local calibration run."""
directory = runtime_dir()
diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py
index de5a92088..3385aca8e 100644
--- a/tests/terminal/test_issues_022.py
+++ b/tests/terminal/test_issues_022.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import os
import sys
import tempfile
import unittest
@@ -97,6 +98,174 @@ class Issue3403MacBuildTools(unittest.TestCase):
self.assertIn("S.ensure_build_tools()", inspect.getsource(fn), fn.__name__)
[email protected](sys.platform == "win32", "ACLs are Windows only")
+class WindowsRuntimeFolderRefused(unittest.TestCase):
+ """The owner's fresh Windows PC: `strata launch` stopped with "runtime directory must be owner-only" on a folder that was already
+ there with another account in its ACL. Fake SDDL strings for each way an ACL can look."""
+
+ def setUp(self):
+ from unittest import mock
+ from strata_control import private_files as pf
+ self.pf, self.mock = pf, mock
+ self.me = "S-1-5-21-1-2-3-1001"
+ patch = mock.patch.object(pf, "current_user_sid", return_value=self.me)
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def offenders(self, sddl):
+ return self.pf.unshared_offenders(sddl)
+
+ def test_the_usual_acls_are_fine(self):
+ for sddl in ("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)",
+ "D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;S-1-5-21-1-2-3-1001)",
+ "D:PAI(A;OICI;FA;;;LA)(A;OICI;FA;;;SY)", # the built-in Administrator's alias
+ "D:P(A;OICI;FA;;;S-1-5-18)(A;OICI;FA;;;S-1-5-32-544)(A;OICIIO;GA;;;CO)(A;OICI;FA;;;OW)"):
+ self.assertEqual(self.offenders(sddl), [], sddl)
+
+ def test_another_account_is_named(self):
+ self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;FR;;;BU)"), ["BU"])
+ self.assertEqual(self.offenders("D:PAI(A;;FA;;;WD)(A;;FA;;;AU)"), ["WD", "AU"])
+ self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1002)"), ["S-1-5-21-1-2-3-1002"])
+
+ def test_an_inherit_only_entry_is_not_for_the_folder_itself(self):
+ self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICIIO;FR;;;BU)(A;CIIO;GR;;;WD)"), [])
+ # the same entry without the IO flag does apply
+ self.assertEqual(self.offenders("D:PAI(A;OICI;FR;;;BU)"), ["BU"])
+
+ def test_deny_entries_do_not_make_it_reachable(self):
+ self.assertEqual(self.offenders("D:PAI(D;;FA;;;BU)(A;OICI;FA;;;S-1-5-21-1-2-3-1001)"), [])
+
+ def test_plain_names(self):
+ self.assertEqual(self.pf.account_name("BU"), "Users")
+ self.assertEqual(self.pf.account_name("WD"), "Everyone")
+ self.assertEqual(self.pf.account_name("S-1-5-32-545"), "Users")
+
+ def test_runtime_dir_repairs_a_folder_that_names_other_accounts(self):
+ from strata_control import runtime
+ pf = self.pf
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp) / "runtime"
+ base.mkdir()
+ state = {"fixed": False}
+
+ def sddl(_path):
+ return "D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)" if state["fixed"] else \
+ "D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;0x1200a9;;;BU)"
+
+ def restrict(path, directory=None):
+ state["fixed"] = True
+
+ env = {"STRATA_RUNTIME_DIR": str(base)}
+ with self.mock.patch.dict(os.environ, env), self.mock.patch.object(pf, "dacl_sddl", side_effect=sddl), \
+ self.mock.patch.object(pf, "restrict_to_current_user", side_effect=restrict) as r, \
+ self.mock.patch.object(pf, "private_mkdir"), self.mock.patch.object(runtime, "_private_mkdir"):
+ self.assertEqual(runtime.runtime_dir(), base)
+ self.assertEqual(r.call_count, 1)
+
+ def test_runtime_dir_still_refuses_and_says_who_when_the_repair_fails(self):
+ from strata_control import profiles, runtime
+ pf = self.pf
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp) / "runtime"
+ base.mkdir()
+ with self.mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(base)}), \
+ self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;FR;;;BU)"), \
+ self.mock.patch.object(pf, "restrict_to_current_user", side_effect=OSError("denied")), \
+ self.mock.patch.object(runtime, "_private_mkdir"):
+ with self.assertRaises(profiles.ProfileError) as cm:
+ runtime.runtime_dir()
+ self.assertIn("Users", str(cm.exception))
+ self.assertIn(str(base), str(cm.exception))
+ self.assertIn("Properties", str(cm.exception))
+
+
[email protected](sys.platform == "win32", "ACLs are Windows only")
+class WindowsRuntimeFolderMoreCases(unittest.TestCase):
+ """The cases beyond the first repair (audit-refusals-022.md item 5): a data drive's inherited Users entries, an ACL that cannot be
+ read, a folder made by an elevated run, a drive without permissions, and a message in plain words."""
+
+ ME = "S-1-5-21-1-2-3-1001"
+
+ def run_dir(self, *, sddl, restrict=None, repair=None, acls=True):
+ from unittest import mock
+ from strata_control import private_files as pf, runtime
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp) / "runtime"
+ base.mkdir()
+ calls = {"restrict": 0, "repair": 0}
+
+ def r(path, directory=None):
+ calls["restrict"] += 1
+ if restrict:
+ return restrict(calls)
+ def rp(path, tree=True):
+ calls["repair"] += 1
+ return repair(calls) if repair else False
+ with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(base)}), \
+ mock.patch.object(pf, "current_user_sid", return_value=self.ME), \
+ mock.patch.object(pf, "dacl_sddl", side_effect=sddl), \
+ mock.patch.object(pf, "restrict_to_current_user", side_effect=r), \
+ mock.patch.object(pf, "repair_access", side_effect=rp), \
+ mock.patch.object(pf, "volume_has_acls", return_value=acls), \
+ mock.patch.object(runtime, "_private_mkdir"), mock.patch.object(runtime, "_NO_ACL_WARNED", set()), \
+ mock.patch("sys.stderr", new_callable=lambda: __import__("io").StringIO()) as err:
+ try:
+ return runtime.runtime_dir(), calls, None, err.getvalue()
+ except Exception as exc: # noqa: BLE001 - the test looks at the ProfileError text
+ return None, calls, exc, err.getvalue()
+
+ def test_a_data_drive_folder_with_users_and_authenticated_users_is_repaired_once(self):
+ state = {"fixed": False}
+ def sddl(_):
+ return f"D:PAI(A;OICI;FA;;;{self.ME})" if state["fixed"] else \
+ f"D:PAI(A;OICI;FA;;;{self.ME})(A;OICI;0x1301bf;;;AU)(A;OICI;0x1200a9;;;BU)"
+ base, calls, exc, _ = self.run_dir(sddl=sddl, restrict=lambda c: state.update(fixed=True))
+ self.assertIsNone(exc)
+ self.assertEqual(calls["restrict"], 1)
+
+ def test_an_acl_that_cannot_be_read_is_repaired_then_refused_in_plain_words(self):
+ def sddl(_):
+ raise OSError("access denied")
+ base, calls, exc, _ = self.run_dir(sddl=sddl)
+ self.assertIsNotNone(exc)
+ self.assertEqual((calls["restrict"], calls["repair"]), (1, 1)) # tried both, once each
+ self.assertIn("cannot read the permissions", str(exc))
+ self.assertNotIn("0700", str(exc))
+
+ def test_a_folder_made_by_an_elevated_run_gets_ownership_taken_back(self):
+ state = {"fixed": False}
+ def sddl(_):
+ if not state["fixed"]:
+ raise OSError("access denied")
+ return f"D:PAI(A;OICI;FA;;;{self.ME})"
+ def restrict(calls):
+ raise PermissionError("denied")
+ base, calls, exc, _ = self.run_dir(sddl=sddl, restrict=restrict, repair=lambda c: state.update(fixed=True) or True)
+ self.assertIsNone(exc)
+ self.assertEqual((calls["restrict"], calls["repair"]), (1, 1))
+
+ def test_a_drive_without_permissions_is_used_with_one_warning(self):
+ def sddl(_):
+ raise AssertionError("FAT has no ACL to read")
+ base, calls, exc, err = self.run_dir(sddl=sddl, acls=False)
+ self.assertIsNone(exc)
+ self.assertEqual((calls["restrict"], calls["repair"]), (0, 0))
+ self.assertIn("no file permissions", err)
+
+ def test_the_refusal_names_the_accounts_and_never_says_mode_0700(self):
+ sddl = lambda _: f"D:PAI(A;OICI;FA;;;{self.ME})(A;OICI;FR;;;AU)(A;OICI;FR;;;WD)" # noqa: E731
+ base, calls, exc, _ = self.run_dir(sddl=sddl)
+ text = str(exc)
+ self.assertIn("Authenticated Users", text)
+ self.assertIn("Everyone", text)
+ self.assertNotIn("0700", text)
+ self.assertEqual(calls["restrict"], 1)
+
+ def test_the_real_system_drive_has_permissions(self):
+ from strata_control import private_files as pf
+ self.assertTrue(pf.volume_has_acls(os.environ.get("SystemRoot", "C:\\Windows")))
+
+
class Issue3410TrashIsNotAnInstall(unittest.TestCase):
def test_trash_folders_are_recognised(self):
from strata_control.discovery import in_trash
diff --git a/tests/terminal/test_runtime.py b/tests/terminal/test_runtime.py
index 9351195da..1b7a2a275 100644
--- a/tests/terminal/test_runtime.py
+++ b/tests/terminal/test_runtime.py
@@ -1167,7 +1167,17 @@ class RuntimeTests(unittest.TestCase):
if done.returncode != 0:
self.skipTest("icacls could not widen the test directory")
with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(shared)}):
- with self.assertRaisesRegex(profiles.ProfileError, "owner-only"):
+ # a folder that names Everyone is the user's own state folder: it is locked down once and used (never a stop)
+ self.assertEqual(runtime.runtime_dir(), shared)
+ self.assertTrue(private_files.is_unshared(shared))
+ again = Path(self.temp.name) / "shared-runtime-2"
+ again.mkdir()
+ subprocess.run(["icacls", str(again), "/grant", "*S-1-1-0:(OI)(CI)R"], capture_output=True)
+ with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(again)}), \
+ mock.patch.object(private_files, "restrict_to_current_user"), \
+ mock.patch.object(private_files, "repair_access", return_value=False):
+ # when the lock-down does not happen it still refuses, in plain words and naming who can open it
+ with self.assertRaisesRegex(profiles.ProfileError, "Everyone"):
runtime.runtime_dir()
def test_exclusive_lease_waits_for_shared_holders_and_shared_holders_coexist(self):