okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b247f4ecd
main
1"""Round 0213 QATUI: a profile or run config of the launch itself that cannot be read stops the launch BEFORE anything is written. 2 3Found on l620 (job qatui-s03c / s03d): with `chmod 000` on the launch's own profile, `strata launch --access lan` printed "A new API key was made", rewrote the 4launch's run config with that new key, and only then failed with `profile 'launch-x' already exists` (exit 2): the key every app was set up with was gone. 5With `chmod 000` on the run config the launch went on and replaced it silently, again with a new key. Real files, an isolated home; only the Runner's 6step is called (the rest of a launch needs an engine). 7 8python -m pytest tests/terminal/test_launch_unreadable_state_0213_qatui.py 9""" 10from __future__import annotations 11 12import json 13import os 14import sys 15import unittest 16from pathlib import Path 17from unittest import mock 18 19ROOT = Path (__file__ ).resolve ().parents [2 ] 20sys .path .insert (0 ,str (ROOT )) 21 22from tests .terminal .launch_support import Home # noqa: E402 23 24POSIX_NOT_ROOT = os .name != "nt" and hasattr (os ,"geteuid" )and os .geteuid ()!= 0 25 26 27def _runner (): 28from strata_cli .launch import settings as S 29from strata_cli .launch .runner import Runner 30r = Runner (S .LaunchSettings (model = "iq3_s" ,context = 32768 )) 31assert r .name == "iq3_s-32k" and r .profile == "launch-iq3_s-32k" 32return r 33 34 35def _write_state (name :str = "iq3_s-32k" ,key :str = "sk-strata-OLD" ): 36from strata_cli .launch .runner import launch_dir 37cfg = launch_dir ()/ f" { name } .json" 38cfg .write_text (json .dumps ({"exe" :"x" ,"args" : [],"api_key" :key }),encoding = "utf-8" ) 39pdir = Path (os .environ ["STRATA_PROFILE_DIR" ]) 40pdir .mkdir (parents = True ,exist_ok = True ) 41prof = pdir / f"launch- { name } .json" 42prof .write_text (json .dumps ({"schema_version" :1 ,"id" :f"launch- { name } " ,"source_config" :str (cfg ),"overrides" : {}}),encoding = "utf-8" ) 43return cfg ,prof 44 45 46class CheckSavedState (unittest .TestCase ): 47def test_nothing_saved_yet_is_fine (self ): 48with Home (): 49_runner ().check_saved_state_readable () 50 51def test_readable_state_is_fine (self ): 52with Home (): 53_write_state () 54_runner ().check_saved_state_readable () 55 56def test_a_damaged_profile_of_this_launch_stops_it_before_any_write (self ): 57from strata_control import profiles 58with Home (): 59cfg ,prof = _write_state () 60prof .write_text ("{not json" ,encoding = "utf-8" ) 61before = cfg .read_bytes () 62with self .assertRaises (profiles .ProfileError )as ctx : 63_runner ().check_saved_state_readable () 64text = str (ctx .exception ) 65self .assertTrue (text .startswith (f"The profile of this launch ( { prof } ) cannot be read (" ),text ) 66self .assertTrue (text .endswith ("). Fix its permissions or move it away, then run the launch again." ),text ) 67self .assertEqual (ctx .exception .exit_code ,2 ) 68self .assertEqual (cfg .read_bytes (),before ) 69 70@ unittest . skipUnless ( POSIX_NOT_ROOT , "needs permissions that deny the owner" ) 71def test_an_unreadable_profile_stops_the_launch_and_the_key_stays (self ): 72from strata_control import profiles 73with Home (): 74cfg ,prof = _write_state () 75os .chmod (prof ,0 ) 76try : 77with self .assertRaises (profiles .ProfileError )as ctx : 78_runner ().check_saved_state_readable () 79finally : 80os .chmod (prof ,0o600 ) 81self .assertIn ("(Permission denied)" ,str (ctx .exception )) 82self .assertIn ("sk-strata-OLD" ,cfg .read_text (encoding = "utf-8" )) 83 84@ unittest . skipUnless ( POSIX_NOT_ROOT , "needs permissions that deny the owner" ) 85def test_an_unreadable_run_config_stops_the_launch_instead_of_minting_a_key (self ): 86from strata_cli .launch .runner import LaunchError 87with Home (): 88cfg ,prof = _write_state () 89os .chmod (cfg ,0 ) 90try : 91with self .assertRaises (LaunchError )as ctx : 92_runner ().check_saved_state_readable () 93finally : 94os .chmod (cfg ,0o600 ) 95self .assertEqual (str (ctx .exception ),f"The saved settings of this launch ( { cfg } ) cannot be read (Permission denied). Fix its permissions or move it away, " 96"then run the launch again: writing a new one would drop its API key and your changes." ) 97self .assertEqual (ctx .exception .code ,6 ) 98self .assertIn ("sk-strata-OLD" ,cfg .read_text (encoding = "utf-8" )) 99 100def test_an_unreadable_run_config_is_refused_on_every_platform (self ): 101"""The same, with the read failing the way a locked or permission-denied file fails (also testable on Windows).""" 102from strata_cli .launch .runner import LaunchError 103with Home (): 104cfg ,prof = _write_state () 105real = Path .read_bytes 106 107def denied (self_ ): 108if self_ == cfg : 109raise PermissionError (13 ,"Permission denied" ) 110return real (self_ ) 111with mock .patch .object (Path ,"read_bytes" ,denied ): 112with self .assertRaises (LaunchError )as ctx : 113_runner ().check_saved_state_readable () 114self .assertIn ("cannot be read (Permission denied)" ,str (ctx .exception )) 115 116 117NEW_KEY = "A new API key was made, because the server is shared beyond this computer. It is saved with the preset; show it with: strata launch --show-key" 118 119 120class NewKeySentenceIsTrue (unittest .TestCase ): 121"""The sentence "A new API key was made" is said only after the run config that holds the key has been written: not in the plan, not before a refusal.""" 122 123def _run (self ,* ,refuse = None ,fail_after_write = None ): 124from strata_cli .launch import settings as S 125from strata_cli .launch .runner import Runner 126events ,order = [], [] 127r = Runner (S .LaunchSettings (model = "iq3_s" ,context = 32768 ),emit = lambda e :events .append (e )) 128r .key_written_notice = NEW_KEY 129base = Path (os .environ ["STRATA_INSTALL_DIR" ])/ "base.json" 130 131def build (self_ ,base_path ): 132order .append ("written" ) 133return base 134patches = [mock .patch .object (Runner ,"check_own_files" ),mock .patch .object (Runner ,"check_serving" ,return_value = None ), 135mock .patch .object (Runner ,"ensure_engine" ),mock .patch .object (Runner ,"ensure_model" ,return_value = base ), 136mock .patch .object (Runner ,"ensure_drafter" ),mock .patch .object (Runner ,"build_config" ,build ), 137mock .patch .object (Runner ,"ensure_profile" ,side_effect = fail_after_write or (lambda * a ,** k :None )), 138mock .patch .object (Runner ,"tune" ,side_effect = RuntimeError ("stop here" )), 139mock .patch .object (Runner ,"check_saved_state_readable" ,side_effect = refuse or (lambda * a ,** k :None ))] 140for p in patches : 141p .start () 142self .addCleanup (lambda : [p .stop ()for p in patches ]) 143try : 144r .run () 145except Exception as exc :# noqa: BLE001 146return r ,events ,order ,exc 147return r ,events ,order ,None 148 149def test_a_refusal_before_the_write_says_nothing_about_a_new_key (self ): 150from strata_cli .launch .runner import LaunchError 151with Home (): 152r ,events ,order ,exc = self ._run (refuse = LaunchError ("cannot be read" ,"fix it" )) 153self .assertIsInstance (exc ,LaunchError ) 154self .assertEqual (order , [])# nothing was written 155self .assertFalse (r .key_written ) 156self .assertNotIn (NEW_KEY , [e .text for e in events ]) 157 158def test_the_sentence_comes_once_right_after_the_write (self ): 159with Home (): 160r ,events ,order ,exc = self ._run () 161self .assertEqual (order , ["written" ]) 162self .assertTrue (r .key_written ) 163said = [e for e in events if e .text == NEW_KEY ] 164self .assertEqual (len (said ),1 ) 165self .assertEqual (said [0 ].level ,"warn" ) 166texts = [e .text for e in events ] 167self .assertLess (texts .index (NEW_KEY ),texts .index ("Settings are saved." )if "Settings are saved." in texts else len (texts )) 168 169def test_it_stays_true_when_something_fails_after_the_write (self ): 170from strata_control import profiles 171with Home (): 172r ,events ,order ,exc = self ._run (fail_after_write = profiles .ProfileError ("later problem" )) 173self .assertIsInstance (exc ,profiles .ProfileError ) 174self .assertTrue (r .key_written )# the key IS on disk then 175self .assertIn (NEW_KEY , [e .text for e in events ]) 176 177def test_the_plan_never_says_it (self ): 178from tests .terminal .launch_support import run_cli 179with Home (): 180code ,out ,err = run_cli (["launch" ,"--plan" ,"--family" ,"qwen" ,"--model" ,"q2_0" ,"--access" ,"lan" ,"--yes" ]) 181self .assertIn ("Plan for" ,out ,out + err )# the plan really ran 182self .assertIn ("API key on" ,out )# and it knows a key is wanted 183self .assertNotIn ("A new API key was made" ,out + err ) 184 185 186if __name__ == "__main__" : 187unittest .main ()