okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""Owner-only files: 0600/0700 on POSIX, a one-entry protected ACL for the current user on NTFS.""" 2 3from __future__import annotations 4 5import json 6import os 7import re 8import stat 9import sys 10import tempfile 11import unittest 12from pathlib import Path 13from unittest import mock 14 15sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [2 ])) 16 17from strata_control import private_files as pf # noqa: E402 18 19 20def resolved (sddl :str )-> str : 21"""``sddl`` with every trustee alias (``LA`` is the built-in Administrator) written as its string SID.""" 22return re .sub (r";;;([^)]*)\)" ,lambda match :f";;; { pf . _string_sid ( match . group ( 1 )) } )" ,sddl ) 23 24 25class PrivateFileTests (unittest .TestCase ): 26def setUp (self ): 27self .tmp = tempfile .TemporaryDirectory () 28self .addCleanup (self .tmp .cleanup ) 29self .root = Path (self .tmp .name ) 30 31def test_a_file_becomes_private_and_stays_readable_by_us (self ): 32path = self .root / "key.json" 33path .write_text ('{"apiKey": "x"}' ) 34pf .restrict_to_current_user (path ) 35self .assertTrue (pf .is_private (path )) 36self .assertEqual (path .read_text (),'{"apiKey": "x"}' ) 37path .write_text ("{}" )# the owner can still replace it 38 39def test_a_directory_becomes_private_and_its_children_inherit (self ): 40folder = self .root / "app-data" 41folder .mkdir () 42pf .restrict_to_current_user (folder ) 43self .assertTrue (pf .is_private (folder )) 44child = folder / "child.json" 45child .write_text ("{}" ) 46if pf .WINDOWS : 47# the child inherits the directory's single entry rather than the profile's 48sddl = pf .dacl_sddl (child ) 49self .assertIn (pf .current_user_sid (),resolved (sddl )) 50self .assertNotIn ("S-1-1-0" ,sddl ) 51self .assertNotIn (";;;SY)" ,sddl ) 52self .assertNotIn (";;;BA)" ,sddl ) 53else : 54self .assertEqual (stat .S_IMODE (folder .stat ().st_mode ),0o700 ) 55 56@ unittest . skipIf ( pf . WINDOWS , "POSIX mode bits" ) 57def test_posix_modes_are_exact (self ): 58path = self .root / "key.json" 59path .write_text ("{}" ) 60os .chmod (path ,0o666 ) 61pf .restrict_to_current_user (path ) 62self .assertEqual (stat .S_IMODE (path .stat ().st_mode ),0o600 ) 63os .chmod (path ,0o644 ) 64self .assertFalse (pf .is_private (path )) 65 66@ unittest . skipUnless ( pf . WINDOWS , "NTFS ACLs" ) 67def test_the_effective_acl_is_one_protected_entry_for_the_current_user (self ): 68path = self .root / "key.json" 69path .write_text ("{}" ) 70self .assertFalse (pf .is_private (path ),"a fresh file inherits SYSTEM/Administrators entries" ) 71pf .restrict_to_current_user (path ) 72sddl = pf .dacl_sddl (path ) 73self .assertEqual (resolved (sddl ),f"D:PAI(A;;FA;;; { pf . current_user_sid () } )" ) 74# nobody else: no Everyone, Users, Authenticated Users, SYSTEM or Administrators 75for sid in ("WD" ,"BU" ,"AU" ,"SY" ,"BA" ,"S-1-1-0" ,"S-1-5-32-545" ): 76self .assertNotIn (f";;; { sid } )" ,sddl ) 77 78def test_a_file_made_in_the_profile_is_unshared_but_not_strictly_private (self ): 79path = self .root / "inherited.json" 80path .write_text ("{}" ) 81if not pf .WINDOWS : 82# POSIX files have mode bits rather than an inherited profile ACL. 83# Specify the private mode instead of depending on the process umask. 84path .chmod (0o600 ) 85self .assertTrue (pf .is_unshared (path )) 86if pf .WINDOWS : 87self .assertFalse (pf .is_private (path ))# SYSTEM and Administrators still inherit 88else : 89self .assertTrue (pf .is_private (path )) 90path .chmod (0o644 ) 91self .assertFalse (pf .is_unshared (path )) 92self .assertFalse (pf .is_private (path )) 93 94@ unittest . skipUnless ( pf . WINDOWS , "NTFS ACLs" ) 95def test_everyone_is_noticed_by_the_relaxed_check_too (self ): 96import subprocess 97path = self .root / "shared.json" 98path .write_text ("{}" ) 99subprocess .run (["icacls" ,str (path ),"/grant" ,"*S-1-1-0:R" ],check = True ,capture_output = True ) 100self .assertFalse (pf .is_unshared (path )) 101 102@ unittest . skipUnless ( pf . WINDOWS , "NTFS ACLs" ) 103def test_widening_the_acl_is_noticed (self ): 104path = self .root / "key.json" 105path .write_text ("{}" ) 106pf .restrict_to_current_user (path ) 107import subprocess 108subprocess .run (["icacls" ,str (path ),"/grant" ,"*S-1-1-0:R" ],check = True ,capture_output = True ) 109self .assertFalse (pf .is_private (path )) 110 111 112if __name__ == "__main__" : 113unittest .main () 114 115 116@ unittest . skipUnless ( pf . WINDOWS , "NTFS ACLs" ) 117class ElevatedRunLockoutTests (unittest .TestCase ): 118"""A file or folder an elevated run made names only SYSTEM and Administrators: the user's normal session cannot open it.""" 119 120def setUp (self ): 121self .tmp = tempfile .TemporaryDirectory () 122self .addCleanup (self .tmp .cleanup ) 123self .root = Path (self .tmp .name ) 124# repair_access only touches the user's own folders (user_roots): the scratch folder is the "profile" here, wherever TEMP points 125env = mock .patch .dict (os .environ , {"STRATA_HOME" :str (self .root )}) 126env .start () 127self .addCleanup (env .stop ) 128 129@staticmethod 130def lock_out (path ): 131"""Replace the rule with SYSTEM only: this session may be elevated itself, so Administrators is left out to make the lock-out real.""" 132import ctypes 133from ctypes import wintypes 134descriptor = ctypes .c_void_p () 135assert pf ._advapi .ConvertStringSecurityDescriptorToSecurityDescriptorW ( 136"D:P(A;OICI;FA;;;SY)" ,1 ,ctypes .byref (descriptor ),None ) 137present ,defaulted ,dacl = wintypes .BOOL (),wintypes .BOOL (),ctypes .c_void_p () 138pf ._advapi .GetSecurityDescriptorDacl (descriptor ,ctypes .byref (present ),ctypes .byref (dacl ),ctypes .byref (defaulted )) 139code = pf ._advapi .SetNamedSecurityInfoW (str (path ),1 ,0x4 | 0x80000000 ,None ,None ,dacl ,None ) 140assert code == 0 ,code 141 142def test_a_locked_file_is_read_again_after_the_repair (self ): 143path = self .root / "profile.json" 144path .write_text ('{"name": "x"}' ) 145self .lock_out (path ) 146with self .assertRaises (PermissionError ): 147path .read_bytes () 148self .assertEqual (pf .read_bytes_repairing (path ),b'{"name": "x"}' ) 149self .assertIn (pf .current_user_sid (),resolved (pf .dacl_sddl (path ))) 150self .assertEqual (path .read_bytes (),b'{"name": "x"}' ) 151 152def test_a_locked_folder_and_what_is_inside_are_repaired_as_a_tree (self ): 153folder = self .root / "profiles" 154folder .mkdir () 155 (folder / "a.json" ).write_text ("{}" ) 156 (folder / "sub" ).mkdir () 157 (folder / "sub" / "b.json" ).write_text ("{}" ) 158for item in (folder / "sub" / "b.json" ,folder / "sub" ,folder / "a.json" ,folder ): 159self .lock_out (item ) 160with self .assertRaises (PermissionError ): 161 (folder / "a.json" ).read_bytes () 162os .environ ["STRATA_HOME" ]= str (self .root ) 163self .addCleanup (os .environ .pop ,"STRATA_HOME" ,None ) 164report = pf .repair_known_roots () 165self .assertGreaterEqual (report ["repaired" ],1 ) 166self .assertEqual (report ["failed" ],0 ) 167self .assertEqual ((folder / "a.json" ).read_bytes (),b"{}" ) 168self .assertEqual ((folder / "sub" / "b.json" ).read_bytes (),b"{}" ) 169self .assertIn (pf .current_user_sid (),resolved (pf .dacl_sddl (folder / "sub" / "b.json" ))) 170 171def test_a_folder_made_with_private_mkdir_names_the_user_explicitly (self ): 172made = pf .private_mkdir (self .root / "x" / "y" ,parents = True ) 173self .assertIn (pf .current_user_sid (),resolved (pf .dacl_sddl (made ))) 174self .assertIn (pf .current_user_sid (),resolved (pf .dacl_sddl (made .parent ))) 175 (made / "file.json" ).write_text ("{}" ) 176self .assertIn (pf .current_user_sid (),resolved (pf .dacl_sddl (made / "file.json" ))) 177self .assertEqual ((made / "file.json" ).read_text (),"{}" ) 178 179def test_the_process_defaults_can_be_set_for_the_user (self ): 180self .assertTrue (pf .adopt_user_defaults ()) 181self .assertTrue (pf .adopt_user_defaults ())# again: nothing breaks 182path = self .root / "new.json" 183path .write_text ("{}" ) 184self .assertEqual (path .read_text (),"{}" ) 185 186def test_default_dacl_allows_reopening_child_process_for_qos (self ): 187import subprocess 188import sys 189# Isolate token changes and keep this test independent of the test runner's defaults. 190script = ''' 191import ctypes 192from ctypes import wintypes 193import subprocess 194import sys 195from strata_control import private_files as pf 196from serve import winjob 197assert pf.adopt_user_defaults() 198k32 = ctypes.WinDLL("kernel32", use_last_error=True) 199k32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) 200k32.OpenProcess.restype = wintypes.HANDLE 201k32.CloseHandle.argtypes = (wintypes.HANDLE,) 202child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) 203try: 204handle = k32.OpenProcess(0x1000 | 0x0200, False, child.pid) 205assert handle, "OpenProcess failed: %s" % ctypes.get_last_error() 206try: 207assert winjob.no_throttle(handle), "Setting child QoS failed" 208finally: 209k32.CloseHandle(handle) 210finally: 211child.terminate() 212child.wait() 213''' 214result = subprocess .run ([sys .executable ,"-c" ,script ],capture_output = True ,text = True ,timeout = 40 ) 215self .assertEqual (result .returncode ,0 ,result .stdout + result .stderr ) 216 217def test_only_the_users_own_folders_are_ever_repaired (self ): 218self .assertFalse (pf .repair_access (os .environ .get ("SystemRoot" ,"C:\Windows" )+ "\System32\drivers" )) 219 220def test_a_profile_that_was_locked_loads (self ): 221from strata_control import profiles 222os .environ ["STRATA_PROFILE_DIR" ]= str (self .root / "profiles" ) 223self .addCleanup (os .environ .pop ,"STRATA_PROFILE_DIR" ,None ) 224directory = self .root / "profiles" 225directory .mkdir () 226run_config = self .root / "strata-x.json" 227run_config .write_text ("{}" ) 228 (directory / "app-1.json" ).write_text (json .dumps ({"schema" :1 ,"name" :"app-1" ,"source_config" :str (run_config )})) 229self .lock_out (directory / "app-1.json" ) 230try : 231profiles .load ("app-1" ) 232except profiles .ProfileError as exc : 233self .assertNotIn ("PermissionError" ,str (exc ))# any other complaint is the sample's shape, not access