okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""Starting and serving never acquire anything. 2 3The owner's rule: a user must never download random packages from the internet while starting or serving. Everything 4that installs, downloads or compiles lives behind an explicit command (SETUP, UPDATE, `strata install`). Three layers 5are checked here: 6 7* the import graph of the start/serve entry points does not reach installer code; 8* no module on the start/serve side runs pip, git, cmake, npm or a package manager, or opens a URL, outside a short 9list of request-time and loopback uses, each with its reason; 10* a real start (setup.main with an installed model) with the network and every subprocess mocked makes no request and 11runs no installer, and a start that WOULD need one stops with a typed error that names the explicit command. 12""" 13 14import ast 15import contextlib 16import io 17import json 18import os 19import subprocess 20import sys 21import tempfile 22import unittest 23import urllib .request 24from pathlib import Path 25from unittest import mock 26 27import setup 28from strata_cli import cli 29from strata_control import acquisition 30 31ROOT = Path (__file__ ).resolve ().parents [2 ] 32 33#: Modules the start/serve entry points must never load. 34INSTALLER_MODULES = {"setup" ,"pip" ,"ensurepip" ,"venv" ,"huggingface_hub" ,"modelscope" ,"metal.setup_mac" , 35"sycl.setup_intel" } 36#: Files that may be loaded on the start/serve side besides the control, cli and serve packages. 37ALLOWED_TOOLS = {"tools.strata_tokenizer" ,"tools.gguf_reader" }# read-only: a tokenizer and a GGUF header reader 38 39#: argv words that mean "acquire": a subprocess whose literal argv contains one of these is an installer. 40INSTALL_WORDS = {"pip" ,"pip3" ,"git" ,"cmake" ,"ninja" ,"npm" ,"npx" ,"pnpm" ,"yarn" ,"winget" ,"apt-get" ,"apt" , 41"dnf" ,"pacman" ,"brew" ,"curl" ,"wget" ,"choco" } 42 43#: (file, call) -> why a network call there is not an acquisition. Request-time and loopback only. 44NETWORK_ALLOWED = { 45 ("serve/server.py" ,"urlopen" ):"an image_url a client sends in a chat request is fetched at request time" , 46 ("serve/mcp.py" ,"urlopen" ):"the MCP servers the user configured, at request time" , 47 ("strata_control/tune_api.py" ,"urlopen" ):"the loopback engine/server of a tuning job the user started" , 48 ("strata_control/tune_session.py" ,"urlopen" ):"the loopback engine (127.0.0.1) the auto-tuner a user started measures" , 49 ("strata_control/loopback.py" ,"urlopen" ):"the one opener for this computer's own servers (no proxy); any other address is passed on unchanged" , 50 ("strata_control/components.py" ,"urlopen" ):"the component fetcher: only `strata install`/UPDATE call it" , 51} 52#: Modules that import the installer on purpose, with the explicit command that reaches them. 53INSTALLER_IMPORT_ALLOWED = { 54"strata_control/calibration.py" :"`strata engine calibrate`: an explicit tuning command, imports setup lazily" , 55} 56 57SERVING_DIRS = ("serve" ,"strata_cli" ,"strata_control" ) 58 59 60def _sources (): 61for d in SERVING_DIRS : 62for p in sorted ((ROOT / d ).glob ("*.py" )): 63if p .name .startswith ("test_" )or p .name == "__init__.py" : 64continue 65yield p 66yield ROOT / "strata.py" 67 68 69class ImportGraphTests (unittest .TestCase ): 70def test_start_and_serve_modules_do_not_load_installer_code (self ): 71script = ( 72"import sys, os, json\n" 73"sys.path.insert(0, os.getcwd())\n" 74"import strata_cli.cli as c\n" 75"import serve.server\n" 76"from strata_control import runtime\n" 77"c.parser()\n" 78"root = os.getcwd()\n" 79"mods = {n: os.path.relpath(m.__file__, root).replace(os.sep, '/') for n, m in list(sys.modules.items())\n" 80" if getattr(m, '__file__', None) and os.path.abspath(m.__file__).startswith(root)}\n" 81"print(json.dumps({'mods': mods, 'names': sorted(sys.modules)}))\n" ) 82r = subprocess .run ([sys .executable ,"-c" ,script ],cwd = ROOT ,capture_output = True ,text = True ,timeout = 120 ) 83self .assertEqual (r .returncode ,0 ,r .stderr [- 1000 :]) 84got = json .loads (r .stdout .strip ().splitlines ()[- 1 ]) 85loaded = set (got ["names" ]) 86self .assertEqual (sorted (loaded & INSTALLER_MODULES ), []) 87for name ,rel in got ["mods" ].items (): 88top = rel .split ("/" )[0 ] 89self .assertIn (top , ("serve" ,"strata_cli" ,"strata_control" ), 90f" { name } ( { rel } ) is loaded by starting/serving but is not part of it" ) 91self .assertNotIn ("strata_control.calibration" ,got ["mods" ]) 92self .assertNotIn ("strata_control.components" ,got ["mods" ]) 93 94def test_static_imports_of_the_installer_are_explicit_commands_only (self ): 95found = {} 96for p in _sources (): 97rel = p .relative_to (ROOT ).as_posix () 98tree = ast .parse (p .read_text (encoding = "utf-8" )) 99for node in ast .walk (tree ): 100names = [] 101if isinstance (node ,ast .Import ): 102names = [a .name for a in node .names ] 103elif isinstance (node ,ast .ImportFrom )and node .module : 104names = [node .module ] 105for n in names : 106top = n .split ("." )[0 ] 107if top == "setup" or n .startswith (("tools." ,"metal." ,"sycl." ))and n not in ALLOWED_TOOLS : 108found .setdefault (rel , []).append (n ) 109for rel in found : 110self .assertIn (rel ,INSTALLER_IMPORT_ALLOWED ,f" { rel } imports installer code: { found [ rel ] } " ) 111 112def test_no_installer_subprocess_or_network_call_on_the_serving_side (self ): 113bad = [] 114for p in _sources (): 115rel = p .relative_to (ROOT ).as_posix () 116tree = ast .parse (p .read_text (encoding = "utf-8" )) 117for node in ast .walk (tree ): 118if not isinstance (node ,ast .Call ): 119continue 120fn = node .func 121name = fn .attr if isinstance (fn ,ast .Attribute )else fn .id if isinstance (fn ,ast .Name )else "" 122if name in ("urlopen" ,"urlretrieve" )and (rel ,name )not in NETWORK_ALLOWED \ 123and (rel ,"urlopen" )not in NETWORK_ALLOWED : 124bad .append (f" { rel } : { node . lineno } { name } " ) 125if name in ("run" ,"call" ,"Popen" ,"check_call" ,"check_output" )and node .args : 126argv = node .args [0 ] 127words = [] 128if isinstance (argv , (ast .List ,ast .Tuple )): 129words = [e .value for e in argv .elts if isinstance (e ,ast .Constant )and isinstance (e .value ,str )] 130elif isinstance (argv ,ast .Constant )and isinstance (argv .value ,str ): 131words = argv .value .split () 132hit = INSTALL_WORDS & {Path (w ).stem if w .endswith (".exe" )else w for w in words } 133if hit : 134bad .append (f" { rel } : { node . lineno } subprocess { sorted ( hit ) } " ) 135self .assertEqual (bad , []) 136for key ,why in NETWORK_ALLOWED .items (): 137self .assertTrue (why ) 138 139 140class _Recorder : 141"""Stands in for the network and for every way of starting a program; records what a start tries.""" 142 143def __init__ (self ): 144self .network = [] 145self .programs = [] 146 147def urlopen (self ,req ,* a ,** k ): 148self .network .append (getattr (req ,"full_url" ,str (req ))) 149raise AssertionError ("a start reached the network: " + self .network [- 1 ]) 150 151def program (self ,argv ,* a ,** k ): 152argv = [str (x )for x in (argv if isinstance (argv , (list ,tuple ))else str (argv ).split ())] 153self .programs .append (argv ) 154return subprocess .CompletedProcess (argv ,0 ,stdout = "" ,stderr = "" ) 155 156def installers (self ): 157return [a for a in self .programs 158if INSTALL_WORDS & {Path (w ).stem .lower ()if w .lower ().endswith (".exe" )else w for w in a } 159or "pip" in a or "-m" in a and "pip" in a ] 160 161 162class StartNeverAcquiresTests (unittest .TestCase ): 163def setUp (self ): 164self .tmp = tempfile .TemporaryDirectory () 165self .addCleanup (self .tmp .cleanup ) 166self .root = Path (self .tmp .name )/ "Strata" 167self .root .mkdir () 168self .data = Path (self .tmp .name )/ "Strata-data" 169 (self .data / "models" ).mkdir (parents = True ) 170self .gguf = self .data / "models" / "m.gguf" 171self .gguf .write_bytes (b"GGUF" ) 172eng = self .root / "engine" 173eng .mkdir () 174 (eng / setup .EXE ).write_bytes (b"engine" ) 175# an engine older than this Strata expects: a start used to download the new one 176 (eng / "BUILD.json" ).write_text (json .dumps ({"version" :"0.1.1" ,"source" :"prebuilt" ,"backend" :"cuda" , 177"archs" : [86 ]})) 178self .cfg = self .root / "strata-q2_0.json" 179self .cfg .write_text (json .dumps ({ 180"exe" :str (eng / setup .EXE ),"args" : ["--native" ,str (self .gguf ),"--max-context" ,"8192" ], 181"tokenizer" :str (self .data / "tok.json" ),"model_name" :"Q2_0" ,"port" :8080 })) 182self .settings_home = Path (self .tmp .name )/ "appdata" 183self .settings_home .mkdir () 184env = {"APPDATA" :str (self .settings_home ),"XDG_CONFIG_HOME" :str (self .settings_home )} 185patcher = mock .patch .dict (os .environ ,env ) 186patcher .start () 187self .addCleanup (patcher .stop ) 188setup .settings_path ().parent .mkdir (parents = True ,exist_ok = True ) 189setup .settings_path ().write_text (json .dumps ({"data_dir" :str (self .data ),"installs" : [str (self .root )]})) 190self .settings_before = setup .settings_path ().read_bytes () 191# pip_install keeps its stamp in sys.prefix: never in the interpreter running the tests 192prefix = mock .patch .object (sys ,"prefix" ,str (self .root )) 193prefix .start () 194self .addCleanup (prefix .stop ) 195 196def run_setup (self ,rec ,* argv ,gpus = None ): 197out = io .StringIO () 198started = [] 199with contextlib .ExitStack ()as st : 200st .enter_context (mock .patch .object (setup ,"ROOT" ,self .root )) 201st .enter_context (mock .patch .object (sys ,"argv" , ["setup.py" ,* argv ])) 202st .enter_context (mock .patch .object (urllib .request ,"urlopen" ,rec .urlopen )) 203st .enter_context (mock .patch .object (setup .netpolicy ,"urlopen" ,rec .urlopen )) 204for n in ("run" ,"call" ,"Popen" ,"check_call" ,"check_output" ): 205st .enter_context (mock .patch .object (subprocess ,n ,rec .program )) 206st .enter_context (mock .patch .object (setup ,"gpus" ,lambda :gpus or [])) 207st .enter_context (mock .patch .object (setup ,"call_server" ,create = True )) 208st .enter_context (mock .patch .object (setup .subprocess ,"call" ,lambda cmd ,* a ,** k : ( 209started .append (cmd ),setattr (self ,"env_of_start" , (k .get ("env" )or {}).get (acquisition .ENV )),0 )[- 1 ])) 210st .enter_context (contextlib .redirect_stdout (out )) 211try : 212code = setup .main () 213except SystemExit as e : 214code = e .code 215except acquisition .AcquisitionRefused as e : 216code = e 217return code ,out .getvalue (),started 218 219def test_a_start_with_an_old_engine_makes_no_request_and_runs_no_installer (self ): 220rec = _Recorder () 221code ,text ,started = self .run_setup (rec ,"--yes" ,"--no-browser" ) 222self .assertEqual (code ,0 ,text ) 223self .assertEqual (rec .network , []) 224self .assertEqual (rec .installers (), []) 225self .assertEqual (len (started ),1 ,text )# the server was started 226self .assertIn ("server.py" ," " .join (started [0 ])) 227self .assertEqual (self .env_of_start ,"1" )# the server is told, too 228self .assertIn ("is older than this Strata expects" ,text ) 229self .assertTrue ("UPDATE" in text or "update.sh" in text ,text )# UPDATE.bat on Windows, ./update.sh elsewhere 230 231def test_a_start_moves_copies_and_creates_nothing (self ): 232before = sorted (p .relative_to (self .tmp .name ).as_posix ()for p in Path (self .tmp .name ).rglob ("*" )) 233stamps = {p :p .stat ().st_mtime_ns for p in Path (self .tmp .name ).rglob ("*" )if p .is_file ()} 234rec = _Recorder () 235code ,text ,_ = self .run_setup (rec ,"--yes" ,"--no-browser" ) 236self .assertEqual (code ,0 ,text ) 237after = sorted (p .relative_to (self .tmp .name ).as_posix ()for p in Path (self .tmp .name ).rglob ("*" )) 238self .assertEqual (before ,after ) 239self .assertEqual (setup .settings_path ().read_bytes (),self .settings_before ) 240for p ,ns in stamps .items (): 241if p != self .cfg :# a start touches the config (most recently used) 242self .assertEqual (p .stat ().st_mtime_ns ,ns ,p ) 243 244def test_a_card_the_engine_has_no_code_for_is_a_typed_error_naming_the_command (self ): 245rec = _Recorder () 246card = {"index" :0 ,"name" :"RTX 5090" ,"arch" :"120" ,"vram_gb" :32.0 ,"driver" :"580.0" } 247with mock .patch .object (setup ,"engine_runs_on" ,lambda g ,tk = 13 :False ), \ 248mock .patch .object (setup ,"old_gpus_opt_in" ,lambda * a ,** k : []): 249code ,text ,started = self .run_setup (rec ,"--yes" ,"--no-browser" ,gpus = [card ]) 250self .assertIsInstance (code ,acquisition .AcquisitionRefused ) 251self .assertIn ("RTX 5090" ,str (code )) 252self .assertIn ("setup" ,str (code ).lower ()) 253self .assertEqual ((rec .network ,rec .installers (),started ), ([], [], [])) 254 255def test_main_script_reports_the_refusal_and_exits_5 (self ): 256e = acquisition .AcquisitionRefused ("an engine for sm_120" ) 257self .assertEqual (e .exit_code ,5 ) 258self .assertEqual (e .code ,"acquisition_refused" ) 259self .assertIn ("never install or download" ,str (e )) 260 261def test_every_acquiring_primitive_refuses_while_a_model_starts (self ): 262rec = _Recorder () 263calls = [ 264lambda :setup .download ("https://example.invalid/x.bin" ,self .root / "x.bin" ), 265lambda :setup .download ("file:///nonexistent" ,self .root / "y.bin" ), 266lambda :setup .pip_install (["definitely-not-installed==1.0" ],"a test package" ), 267lambda :setup .run ([sys .executable ,"-m" ,"pip" ,"install" ,"x" ]), 268lambda :setup ._urlopen (urllib .request .Request ("https://example.invalid/" )), 269lambda :setup .reachable ("https://example.invalid/" ), 270lambda :setup .get_prebuilt ("https://example.invalid/" , {"arch" :"86" },"none" ), 271lambda :setup .cmake_build (self .root ,self .root / "b" ,"strata" , [],None ,"" ), 272lambda :setup .pip_cuda_libs (13 ), 273 ] 274with mock .patch .object (urllib .request ,"urlopen" ,rec .urlopen ),mock .patch .object (setup .netpolicy ,"urlopen" ,rec .urlopen ), \ 275mock .patch .object (subprocess ,"run" ,rec .program ),mock .patch .object (subprocess ,"Popen" ,rec .program ): 276with acquisition .forbidden (): 277for i ,call in enumerate (calls ): 278with self .subTest (i = i ): 279with self .assertRaises (acquisition .AcquisitionRefused )as cm : 280call () 281self .assertIn ("Run:" ,str (cm .exception )) 282self .assertEqual ((rec .network ,rec .programs ), ([], [])) 283 284def test_the_environment_switch_forbids_a_whole_process (self ): 285with mock .patch .dict (os .environ , {acquisition .ENV :"1" }): 286with self .assertRaises (acquisition .AcquisitionRefused ): 287setup .pip_install (["definitely-not-installed==1.0" ],"a test package" ) 288 289def test_update_still_installs (self ): 290"""The explicit commands keep working: outside a start, the install step runs.""" 291installed = [] 292with tempfile .TemporaryDirectory ()as prefix ,mock .patch .object (sys ,"prefix" ,prefix ),mock .patch .object (setup ,"run" ,lambda cmd ,** k :installed .append ([str (c )for c in cmd ])): 293setup .pip_install (["somepkg==1.0" ],"a test package" ) 294self .assertEqual (len (installed ),1 ) 295self .assertIn ("pip" ,installed [0 ]) 296 297 298class CliServeIsOfflineTests (unittest .TestCase ): 299def test_serve_plan_reaches_no_network_and_runs_no_program (self ): 300rec = _Recorder () 301with tempfile .TemporaryDirectory ()as d : 302cfg = Path (d )/ "strata-x.json" 303gguf = Path (d )/ "m.gguf" 304gguf .write_bytes (b"GGUF" ) 305tok = Path (d )/ "t.json" 306tok .write_text ("{}" ) 307exe = Path (d )/ "strata.exe" 308exe .write_bytes (b"x" ) 309cfg .write_text (json .dumps ({"exe" :str (exe ),"args" : ["--native" ,str (gguf )],"tokenizer" :str (tok )})) 310out = io .StringIO () 311with mock .patch .object (urllib .request ,"urlopen" ,rec .urlopen ), \ 312mock .patch .object (subprocess ,"run" ,rec .program ),mock .patch .object (subprocess ,"Popen" ,rec .program ), \ 313mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (Path (d )/ "profiles" )}), \ 314contextlib .redirect_stdout (out ): 315code = cli .main (["serve" ,"--profile" ,str (cfg ),"--plan" ,"--output" ,"json" ]) 316self .assertEqual (code ,0 ,out .getvalue ()) 317# Reading the hardware is not acquiring anything: nvidia-smi / hipInfo / rocminfo and PowerShell's Get-CimInstance (display adapters) only 318# print what is here. Whether a PC runs them depends on the PC (a machine with nvidia-smi on PATH does), so the check is that nothing else runs. 319probes = {"nvidia-smi" ,"hipinfo" ,"rocminfo" ,"rocm-smi" ,"vulkaninfo" } 320 321def read_only (argv ): 322stem = Path (argv [0 ]).stem .lower () 323return stem in probes or (stem in ("powershell" ,"pwsh" )and any ("Get-CimInstance" in a for a in argv )) 324self .assertEqual (rec .network , []) 325self .assertEqual ([a for a in rec .programs if not read_only (a )], []) 326self .assertNotIn ("setup" ,sys .modules .get ("strata_cli.cli" ).__dict__ .get ("__name__" ,"" )) 327 328def test_strata_install_without_the_installer_is_a_typed_error (self ): 329err = io .StringIO () 330with tempfile .TemporaryDirectory ()as d , \ 331mock .patch .dict (os .environ , {"STRATA_INSTALL_DIR" :d }), \ 332mock .patch .object (cli ,"ROOT" ,Path (d )),contextlib .redirect_stderr (err ): 333code = cli .main (["install" ]) 334self .assertEqual (code ,5 ) 335self .assertIn ("installer" ,err .getvalue ()) 336 337 338if __name__ == "__main__" : 339unittest .main ()