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++

control: owner-only files on NTFS (a one-entry protected ACL via ctypes) and the owner state-file check uses it on Windows

Niko12215f051b83d04b
diff --git a/strata_control/owner_transport.py b/strata_control/owner_transport.py
index b32ed5c11..aa495d2b6 100644
--- a/strata_control/owner_transport.py
+++ b/strata_control/owner_transport.py
@@ -173,5 +173,10 @@ def check_state_file(path: Path) -> None:
raise TransportError("the runtime state file is implausibly large")
if hasattr(os, "getuid") and st.st_uid != os.getuid():
raise TransportError("the runtime state file is owned by another user")
- if st.st_mode & 0o077:
+ if WINDOWS:
+ # NTFS has no mode bits: the promise is a protected ACL naming this user only.
+ from strata_control.private_files import is_private
+ if not is_private(path):
+ raise TransportError("the runtime state file is readable by other users")
+ elif st.st_mode & 0o077:
raise TransportError("the runtime state file is readable by other users")
diff --git a/strata_control/private_files.py b/strata_control/private_files.py
new file mode 100644
index 000000000..6ec8f5c10
--- /dev/null
+++ b/strata_control/private_files.py
@@ -0,0 +1,156 @@
+"""Owner-only files on every platform.
+
+POSIX keeps what the code always did (``0600`` files, ``0700`` directories). NTFS has no mode bits,
+so on Windows the same promise is an ACL: a protected (non-inherited) DACL with exactly one
+allow entry, for the current user. This uses ``advapi32`` through ``ctypes``; there is no
+``pywin32`` or ``icacls`` dependency and no output parsing that depends on the display language.
+"""
+from __future__ import annotations
+
+import os
+import re
+from pathlib import Path
+
+WINDOWS = os.name == "nt"
+
+if WINDOWS:
+ import ctypes
+ from ctypes import wintypes
+
+ _advapi = ctypes.WinDLL("advapi32", use_last_error=True)
+ _kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+
+ _kernel.GetCurrentProcess.restype = wintypes.HANDLE
+ _kernel.LocalFree.argtypes = [ctypes.c_void_p]
+ _kernel.LocalFree.restype = ctypes.c_void_p
+ _kernel.CloseHandle.argtypes = [wintypes.HANDLE]
+ _advapi.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
+ _advapi.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD)]
+ _advapi.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)]
+ _advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
+ wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p]
+ _advapi.GetSecurityDescriptorDacl.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.BOOL),
+ ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.BOOL)]
+ _advapi.SetNamedSecurityInfoW.argtypes = [wintypes.LPWSTR, ctypes.c_int, wintypes.DWORD, ctypes.c_void_p,
+ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
+ _advapi.SetNamedSecurityInfoW.restype = wintypes.DWORD
+ _advapi.GetNamedSecurityInfoW.argtypes = [wintypes.LPCWSTR, ctypes.c_int, wintypes.DWORD, ctypes.c_void_p,
+ ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p,
+ ctypes.POINTER(ctypes.c_void_p)]
+ _advapi.GetNamedSecurityInfoW.restype = wintypes.DWORD
+ _advapi.ConvertSecurityDescriptorToStringSecurityDescriptorW.argtypes = [
+ ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(wintypes.LPWSTR), ctypes.c_void_p]
+
+_SE_FILE_OBJECT = 1
+_DACL = 0x4
+_PROTECTED_DACL = 0x80000000
+_TOKEN_QUERY = 0x8
+_TOKEN_USER = 1
+_SDDL_REVISION_1 = 1
+_sid_cache: str | None = None
+
+
+def _winerr(what: str, code: int | None = None) -> OSError:
+ return ctypes.WinError(code if code is not None else ctypes.get_last_error(), what) # type: ignore[attr-defined]
+
+
+def current_user_sid() -> str:
+ """The string SID of the user this process runs as (Windows only)."""
+ global _sid_cache
+ if not WINDOWS:
+ raise OSError("SIDs exist on Windows only")
+ if _sid_cache:
+ return _sid_cache
+ token = wintypes.HANDLE()
+ if not _advapi.OpenProcessToken(_kernel.GetCurrentProcess(), _TOKEN_QUERY, ctypes.byref(token)):
+ raise _winerr("OpenProcessToken")
+ try:
+ needed = wintypes.DWORD()
+ _advapi.GetTokenInformation(token, _TOKEN_USER, None, 0, ctypes.byref(needed))
+ buffer = ctypes.create_string_buffer(needed.value)
+ if not _advapi.GetTokenInformation(token, _TOKEN_USER, buffer, needed, ctypes.byref(needed)):
+ raise _winerr("GetTokenInformation")
+ psid = ctypes.c_void_p.from_buffer(buffer).value # TOKEN_USER starts with the SID pointer
+ text = wintypes.LPWSTR()
+ if not _advapi.ConvertSidToStringSidW(psid, ctypes.byref(text)):
+ raise _winerr("ConvertSidToStringSidW")
+ try:
+ _sid_cache = text.value
+ finally:
+ _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p))
+ finally:
+ _kernel.CloseHandle(token)
+ assert _sid_cache
+ return _sid_cache
+
+
+def restrict_to_current_user(path: str | os.PathLike, *, directory: bool | None = None) -> None:
+ """Make ``path`` readable and writable by the current user only.
+
+ POSIX: ``chmod 0600`` (``0700`` for a directory). Windows: replace the DACL with one protected
+ entry granting the current user full control (inherited by children when ``path`` is a
+ directory) and drop every inherited entry.
+ """
+ path = os.fspath(path)
+ if directory is None:
+ directory = os.path.isdir(path)
+ if not WINDOWS:
+ os.chmod(path, 0o700 if directory else 0o600)
+ return
+ flags = "OICI" if directory else ""
+ sddl = f"D:PAI(A;{flags};FA;;;{current_user_sid()})"
+ descriptor = ctypes.c_void_p()
+ if not _advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ sddl, _SDDL_REVISION_1, ctypes.byref(descriptor), None):
+ raise _winerr("ConvertStringSecurityDescriptorToSecurityDescriptorW")
+ try:
+ present, defaulted, dacl = wintypes.BOOL(), wintypes.BOOL(), ctypes.c_void_p()
+ if not _advapi.GetSecurityDescriptorDacl(descriptor, ctypes.byref(present), ctypes.byref(dacl),
+ ctypes.byref(defaulted)) or not present.value:
+ raise _winerr("GetSecurityDescriptorDacl")
+ code = _advapi.SetNamedSecurityInfoW(path, _SE_FILE_OBJECT, _DACL | _PROTECTED_DACL,
+ None, None, dacl, None)
+ if code:
+ raise _winerr(f"SetNamedSecurityInfoW {path}", code)
+ finally:
+ _kernel.LocalFree(descriptor)
+
+
+def dacl_sddl(path: str | os.PathLike) -> str:
+ """The DACL of ``path`` as an SDDL string such as ``D:PAI(A;;FA;;;S-1-5-21-...)`` (Windows only)."""
+ if not WINDOWS:
+ raise OSError("DACLs exist on Windows only")
+ descriptor = ctypes.c_void_p()
+ code = _advapi.GetNamedSecurityInfoW(os.fspath(path), _SE_FILE_OBJECT, _DACL, None, None, None, None,
+ ctypes.byref(descriptor))
+ if code:
+ raise _winerr(f"GetNamedSecurityInfoW {path}", code)
+ try:
+ text = wintypes.LPWSTR()
+ if not _advapi.ConvertSecurityDescriptorToStringSecurityDescriptorW(
+ descriptor, _SDDL_REVISION_1, _DACL, ctypes.byref(text), None):
+ raise _winerr("ConvertSecurityDescriptorToStringSecurityDescriptorW")
+ try:
+ return text.value
+ finally:
+ _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p))
+ finally:
+ _kernel.LocalFree(descriptor)
+
+
+def is_private(path: str | os.PathLike) -> bool:
+ """True when only the current user can reach ``path``.
+
+ POSIX: no group or other permission bits. Windows: the DACL is protected (no inherited entries)
+ and consists of exactly one allow entry for the current user.
+ """
+ if not WINDOWS:
+ return not (os.lstat(path).st_mode & 0o077)
+ sddl = dacl_sddl(path)
+ head = sddl.split("(", 1)[0]
+ entries = re.findall(r"\(([^()]*)\)", sddl)
+ if not head.startswith("D:") or "P" not in head[2:] or len(entries) != 1:
+ return False
+ fields = entries[0].split(";")
+ return len(fields) >= 6 and fields[0] == "A" and fields[5] == current_user_sid()
diff --git a/tests/terminal/test_owner_transport.py b/tests/terminal/test_owner_transport.py
index 17ac08f73..11282dd40 100644
--- a/tests/terminal/test_owner_transport.py
+++ b/tests/terminal/test_owner_transport.py
@@ -27,6 +27,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from strata_control import owner_transport as ot # noqa: E402
+from strata_control.private_files import restrict_to_current_user # noqa: E402
class TestAddressing(unittest.TestCase):
@@ -40,6 +41,7 @@ class TestAddressing(unittest.TestCase):
else:
self.assertTrue(addr.endswith(".sock"))
+ @unittest.skipIf(ot.WINDOWS, "the Windows address is a placeholder; the listener picks the port")
def test_address_is_stable_for_the_same_inputs(self):
d = Path("/tmp/strata-runtime")
self.assertEqual(ot.address_for(d, "default"), ot.address_for(d, "default"))
@@ -194,7 +196,7 @@ class TestStateFileValidation(unittest.TestCase):
self.tmp = Path(tempfile.mkdtemp(prefix="strata-state-"))
self.path = self.tmp / "default.json"
self.path.write_text('{"token": "x"}')
- os.chmod(self.path, 0o600)
+ restrict_to_current_user(self.path)
def tearDown(self):
import shutil
@@ -203,6 +205,13 @@ class TestStateFileValidation(unittest.TestCase):
def test_a_private_regular_file_is_accepted(self):
ot.check_state_file(self.path)
+ @unittest.skipUnless(ot.WINDOWS, "NTFS ACLs")
+ def test_a_state_file_with_an_inherited_acl_is_refused(self):
+ other = self.tmp / "inherited.json"
+ other.write_text("{}") # a fresh file inherits the directory's entries (SYSTEM, Administrators)
+ with self.assertRaises(ot.TransportError):
+ ot.check_state_file(other)
+
@unittest.skipIf(ot.WINDOWS, "POSIX permission bits")
def test_a_world_readable_state_file_is_refused(self):
os.chmod(self.path, 0o644)
diff --git a/tests/terminal/test_private_files.py b/tests/terminal/test_private_files.py
new file mode 100644
index 000000000..3a908858d
--- /dev/null
+++ b/tests/terminal/test_private_files.py
@@ -0,0 +1,81 @@
+"""Owner-only files: 0600/0700 on POSIX, a one-entry protected ACL for the current user on NTFS."""
+
+from __future__ import annotations
+
+import os
+import stat
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+from strata_control import private_files as pf # noqa: E402
+
+
+class PrivateFileTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+
+ def test_a_file_becomes_private_and_stays_readable_by_us(self):
+ path = self.root / "key.json"
+ path.write_text('{"apiKey": "x"}')
+ pf.restrict_to_current_user(path)
+ self.assertTrue(pf.is_private(path))
+ self.assertEqual(path.read_text(), '{"apiKey": "x"}')
+ path.write_text("{}") # the owner can still replace it
+
+ def test_a_directory_becomes_private_and_its_children_inherit(self):
+ folder = self.root / "app-data"
+ folder.mkdir()
+ pf.restrict_to_current_user(folder)
+ self.assertTrue(pf.is_private(folder))
+ child = folder / "child.json"
+ child.write_text("{}")
+ if pf.WINDOWS:
+ # the child inherits the directory's single entry rather than the profile's
+ sddl = pf.dacl_sddl(child)
+ self.assertIn(pf.current_user_sid(), sddl)
+ self.assertNotIn("S-1-1-0", sddl)
+ self.assertNotIn(";;;SY)", sddl)
+ self.assertNotIn(";;;BA)", sddl)
+ else:
+ self.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700)
+
+ @unittest.skipIf(pf.WINDOWS, "POSIX mode bits")
+ def test_posix_modes_are_exact(self):
+ path = self.root / "key.json"
+ path.write_text("{}")
+ os.chmod(path, 0o666)
+ pf.restrict_to_current_user(path)
+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
+ os.chmod(path, 0o644)
+ self.assertFalse(pf.is_private(path))
+
+ @unittest.skipUnless(pf.WINDOWS, "NTFS ACLs")
+ def test_the_effective_acl_is_one_protected_entry_for_the_current_user(self):
+ path = self.root / "key.json"
+ path.write_text("{}")
+ self.assertFalse(pf.is_private(path), "a fresh file inherits SYSTEM/Administrators entries")
+ pf.restrict_to_current_user(path)
+ sddl = pf.dacl_sddl(path)
+ self.assertEqual(sddl, f"D:PAI(A;;FA;;;{pf.current_user_sid()})")
+ # nobody else: no Everyone, Users, Authenticated Users, SYSTEM or Administrators
+ for sid in ("WD", "BU", "AU", "SY", "BA", "S-1-1-0", "S-1-5-32-545"):
+ self.assertNotIn(f";;;{sid})", sddl)
+
+ @unittest.skipUnless(pf.WINDOWS, "NTFS ACLs")
+ def test_widening_the_acl_is_noticed(self):
+ path = self.root / "key.json"
+ path.write_text("{}")
+ pf.restrict_to_current_user(path)
+ import subprocess
+ subprocess.run(["icacls", str(path), "/grant", "*S-1-1-0:R"], check=True, capture_output=True)
+ self.assertFalse(pf.is_private(path))
+
+
+if __name__ == "__main__":
+ unittest.main()