okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
1"""Saved read-only connections work in both source and portable terminal clients.""" 2 3import io 4import json 5import os 6import stat 7import subprocess 8import sys 9import tempfile 10import threading 11import unittest 12from contextlib import redirect_stdout 13from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 14from pathlib import Path 15from unittest import mock 16 17from strata_cli .cli import main 18from strata_cli import connections 19from strata_cli .client import ClientError ,Endpoint ,server_url 20from strata_cli .render import render_view 21 22 23ROOT = Path (__file__ ).resolve ().parents [2 ] 24 25 26class ConnectionTests (unittest .TestCase ): 27def setUp (self ): 28self .temp = tempfile .TemporaryDirectory (prefix = "strata-connections-" ) 29self .addCleanup (self .temp .cleanup ) 30self .directory = Path (self .temp .name )/ "connections" 31env = mock .patch .dict (os .environ , {"STRATA_CONNECTION_DIR" :str (self .directory )},clear = False ) 32env .start () 33self .addCleanup (env .stop ) 34 35def _cli (self ,* argv ): 36output = io .StringIO () 37with redirect_stdout (output ): 38code = main (list (argv )) 39return code ,json .loads (output .getvalue ()) 40 41def test_create_edit_precedence_and_private_storage (self ): 42code ,created = self ._cli ("connection" ,"create" ,"edge" ,"--url" ,"https://Example.COM:443" , 43"--prefix" ,"/proxy/strata" ,"--credential-env" ,"STRATA_READ_KEY" , 44"--output" ,"json" ) 45self .assertEqual (code ,0 ) 46self .assertEqual (created ["connection" ]["url" ],"https://example.com:443" ) 47self .assertEqual (created ["connection" ]["prefix" ],"/proxy/strata" ) 48saved = self .directory / "edge.json" 49if os .name == "posix" : 50self .assertEqual (self .directory .stat ().st_mode & 0o077 ,0 ) 51self .assertEqual (saved .stat ().st_mode & 0o077 ,0 ) 52self .assertNotIn ("test-secret" ,saved .read_text ()) 53revision = created ["revision" ] 54code ,plan = self ._cli ("connection" ,"set" ,"edge" ,"prefix=/new" ,"--plan" , 55"--if-revision" ,revision ,"--output" ,"json" ) 56self .assertEqual (code ,0 ) 57self .assertTrue (plan ["would_save" ]) 58self .assertEqual (connections .load ("edge" )[1 ],revision ) 59code ,changed = self ._cli ("connection" ,"set" ,"edge" ,"prefix=/new" , 60"--if-revision" ,revision ,"--output" ,"json" ) 61self .assertEqual (code ,0 ) 62self .assertNotEqual (changed ["revision" ],revision ) 63code ,stale = self ._cli ("connection" ,"set" ,"edge" ,"prefix=/other" , 64"--if-revision" ,revision ,"--output" ,"json" ) 65self .assertEqual ((code ,stale ["error" ]["code" ]), (6 ,6 )) 66self .assertEqual (connections .load ("edge" )[0 ]["prefix" ],"/new" ) 67with mock .patch .dict (os .environ , {"STRATA_CONNECTION" :"edge" ,"STRATA_URL" :"https://ignored.example" , 68"STRATA_READ_KEY" :"test-secret" }): 69code ,effective = self ._cli ("config" ,"show" ,"--effective" ,"--output" ,"json" ) 70self .assertEqual (code ,0 ) 71self .assertEqual (effective ["effective" ]["url" ],"https://example.com:443" ) 72self .assertEqual (effective ["effective" ]["prefix" ],"/new" ) 73self .assertEqual (effective ["effective" ]["base_url" ],"https://example.com:443/new" ) 74self .assertEqual (effective ["effective" ]["origins" ]["url" ],"connection" ) 75self .assertEqual (effective ["effective" ]["timeout_s" ],3.0 ) 76self .assertEqual (effective ["effective" ]["origins" ]["timeout_s" ],"default" ) 77self .assertTrue (effective ["effective" ]["credential_present" ]) 78self .assertNotIn ("test-secret" ,json .dumps (effective )) 79code ,override = self ._cli ("config" ,"show" ,"--url" ,"https://other.example" , 80"--credential-env" ,"OTHER_KEY" ,"--timeout" ,"4.5" , 81"--output" ,"json" ) 82self .assertEqual (code ,0 ) 83self .assertEqual (override ["effective" ]["url" ],"https://other.example" ) 84self .assertEqual (override ["effective" ]["prefix" ],"" ) 85self .assertEqual (override ["effective" ]["credential_env" ],"OTHER_KEY" ) 86self .assertEqual (override ["effective" ]["origins" ]["url" ],"flag" ) 87self .assertEqual (override ["effective" ]["origins" ]["timeout_s" ],"flag" ) 88self .assertEqual (override ["effective" ]["timeout_s" ],4.5 ) 89code ,conflict = self ._cli ("config" ,"show" ,"--url" ,"https://other.example" , 90"--connection" ,"edge" ,"--output" ,"json" ) 91self .assertEqual ((code ,conflict ["error" ]["code" ]), (2 ,2 )) 92 93def test_connection_and_config_json_aliases (self ): 94code ,listed = self ._cli ("connection" ,"list" ,"--json" ) 95self .assertEqual (code ,0 ) 96self .assertEqual (listed ["connections" ], []) 97code ,effective = self ._cli ("config" ,"show" ,"--url" ,"http://127.0.0.1:8095" ,"--json" ) 98self .assertEqual (code ,0 ) 99self .assertTrue (effective ["ok" ]) 100self .assertEqual (effective ["effective" ]["url" ],"http://127.0.0.1:8095" ) 101 102def test_interactive_monitor_rejects_json_output_before_connecting (self ): 103for output_flag in (("--output" ,"json" ), ("--json" ,)): 104with self .subTest (output_flag = output_flag ),mock .patch ( 105"strata_cli.monitor_commands.Endpoint" )as endpoint : 106code ,response = self ._cli ("monitor" ,"--url" ,"http://127.0.0.1:1" , 107* output_flag ) 108self .assertEqual ((code ,response ["error" ]["code" ]), (2 ,2 )) 109self .assertIn ("requires --once" ,response ["error" ]["message" ]) 110endpoint .assert_not_called () 111bundle = Path (self .temp .name )/ "strata-monitor.pyz" 112subprocess .run ([sys .executable ,str (ROOT / "packaging/monitor_bundle.py" ), 113"build" ,str (bundle )],capture_output = True ,text = True ,check = True ) 114portable = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"monitor" ,"--url" , 115"http://127.0.0.1:1" ,"--output" ,"json" ], 116cwd = self .temp .name ,capture_output = True ,text = True ) 117self .assertEqual (portable .returncode ,2 ) 118self .assertIn ("requires --once" ,json .loads (portable .stdout )["error" ]["message" ]) 119self .assertEqual (portable .stderr ,"" ) 120 121def test_quiet_connection_and_status_keep_machine_records (self ): 122output = io .StringIO () 123with redirect_stdout (output ): 124self .assertEqual (main (["connection" ,"list" ,"--quiet" ]),0 ) 125self .assertEqual (output .getvalue (),"" ) 126code ,listed = self ._cli ("connection" ,"list" ,"--quiet" ,"--json" ) 127self .assertEqual (code ,0 ) 128self .assertEqual (listed ["connections" ], []) 129with mock .patch ("strata_cli.monitor_commands.Endpoint" )as endpoint : 130endpoint .return_value .snapshot .return_value = {"schema_version" :1 } 131output = io .StringIO () 132with redirect_stdout (output ): 133self .assertEqual (main (["status" ,"--url" ,"http://127.0.0.1:8095" ,"--quiet" ]),0 ) 134self .assertEqual (output .getvalue (),"" ) 135with redirect_stdout (output ): 136self .assertEqual (main (["status" ,"--url" ,"http://127.0.0.1:8095" , 137"--quiet" ,"--json" ]),0 ) 138self .assertTrue (json .loads (output .getvalue ())["ok" ]) 139 140def test_invalid_prefix_credentials_and_file_permissions_fail_closed (self ): 141for prefix in ("//proxy" ,"/a/../b" ,"/a?key=secret" ,"/a//b" ,"https://host/path" ): 142with self .assertRaises (connections .ConnectionError ): 143connections .prefix_path (prefix ) 144with self .assertRaises (ValueError ): 145server_url ("http://@127.0.0.1:8095" ) 146with self .assertRaises (connections .ConnectionError ): 147connections .credential_name ("BAD-NAME" ) 148connections .create ("local" ,"http://127.0.0.1:8095" ) 149with self .assertRaises (connections .ConnectionError ): 150connections .create ("local" ,"http://127.0.0.1:8095" ) 151if os .name == "posix" : 152record = self .directory / "local.json" 153record .chmod (0o644 )# our own file with drifted modes is put back, not refused 154connections .load ("local" ) 155self .assertEqual (stat .S_IMODE (record .stat ().st_mode ),0o600 ) 156with mock .patch ("os.getuid" ,return_value = os .getuid ()+ 1 ):# a file that belongs to another account is refused 157with self .assertRaisesRegex (connections .ConnectionError ,"belongs to .*sudo chown" ): 158connections .load ("local" ) 159record = self .directory / "local.json" 160corrupted = json .loads (record .read_text ()) 161corrupted ["url" ]= 42 162record .write_text (json .dumps (corrupted )) 163code ,response = self ._cli ("config" ,"show" ,"--connection" ,"local" ,"--output" ,"json" ) 164self .assertEqual ((code ,response ["error" ]["code" ]), (5 ,5 )) 165 166def test_proxy_prefix_and_credential_reference_work_in_portable_bundle (self ): 167seen = [] 168snapshot = {"schema_version" :1 ,"instance" : {"id" :"from-proxy" }, 169"model" : {"id" :"fixture" ,"loaded" :True },"work" : {"active" :3 }} 170 171class Handler (BaseHTTPRequestHandler ): 172def do_GET (self ): 173seen .append ((self .path ,self .headers .get ("Authorization" ))) 174if self .path != "/proxy/v1/telemetry" : 175self .send_error (404 ) 176return 177body = json .dumps (snapshot ).encode () 178self .send_response (200 ) 179self .send_header ("Content-Type" ,"application/json" ) 180self .send_header ("Content-Length" ,str (len (body ))) 181self .end_headers () 182self .wfile .write (body ) 183 184def log_message (self ,* _args ): 185pass 186 187server = ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 188thread = threading .Thread (target = server .serve_forever ,daemon = True ) 189thread .start () 190try : 191root = f"http://127.0.0.1: { server . server_port } " 192connections .create ("proxied" ,root ,prefix = "/proxy" ,credential_env = "STRATA_READ_KEY" ) 193with mock .patch .dict (os .environ , {"STRATA_READ_KEY" :"test-secret" }): 194code ,source = self ._cli ("status" ,"--connection" ,"proxied" ,"--json" ) 195self .assertEqual (code ,0 ) 196self .assertEqual (source ["snapshot" ]["work" ]["active" ],3 ) 197bundle = Path (self .temp .name )/ "strata-monitor.pyz" 198subprocess .run ([sys .executable ,str (ROOT / "packaging/monitor_bundle.py" ), 199"build" ,str (bundle )],capture_output = True ,text = True ,check = True ) 200portable = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"status" ,"--connection" , 201"proxied" ,"--json" ],env = os .environ .copy (),cwd = self .temp .name , 202capture_output = True ,text = True ,check = True ) 203self .assertEqual (json .loads (portable .stdout ),source ) 204portable_config = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"config" ,"show" , 205"--connection" ,"proxied" ,"--output" ,"json" ], 206env = os .environ .copy (),cwd = self .temp .name , 207capture_output = True ,text = True ,check = True ) 208self .assertEqual (json .loads (portable_config .stdout )["effective" ]["prefix" ],"/proxy" ) 209self .assertNotIn ("test-secret" ,portable_config .stdout ) 210subprocess .run ([sys .executable ,"-S" ,str (bundle ),"connection" ,"create" ,"second" , 211"--url" ,root ,"--output" ,"json" ],env = os .environ .copy (), 212cwd = self .temp .name ,capture_output = True ,text = True ,check = True ) 213self .assertEqual (connections .load ("second" )[0 ]["url" ],root ) 214self .assertEqual (seen , [("/proxy/v1/telemetry" ,"Bearer test-secret" )]* 2 ) 215self .assertEqual (Endpoint (root ,prefix = "/proxy" ).base_url ,root + "/proxy" ) 216finally : 217server .shutdown () 218server .server_close () 219thread .join (timeout = 2 ) 220 221def test_deeply_nested_telemetry_returns_one_redacted_error (self ): 222depth = 20000 # Python 3.13 parses 1100 levels; the recursion limit is reached at a few thousand on every version 223body = b"[" * depth + b"0" + b"]" * depth 224 225class Handler (BaseHTTPRequestHandler ): 226def do_GET (self ): 227self .send_response (200 ) 228self .send_header ("Content-Type" ,"application/json" ) 229self .send_header ("Content-Length" ,str (len (body ))) 230self .end_headers () 231self .wfile .write (body ) 232 233def log_message (self ,* _args ): 234pass 235 236server = ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 237thread = threading .Thread (target = server .serve_forever ,daemon = True ) 238thread .start () 239try : 240root = f"http://127.0.0.1: { server . server_port } " 241with self .assertRaisesRegex (ClientError ,"malformed JSON telemetry" ): 242Endpoint (root ).snapshot () 243code ,response = self ._cli ("status" ,"--url" ,root ,"--json" ) 244self .assertEqual (code ,3 ) 245self .assertEqual (response ["error" ]["message" ],"server returned malformed JSON telemetry" ) 246bundle = Path (self .temp .name )/ "deep-json-monitor.pyz" 247subprocess .run ([sys .executable ,str (ROOT / "packaging/monitor_bundle.py" ), 248"build" ,str (bundle )],capture_output = True ,text = True ,check = True ) 249portable = subprocess .run ([sys .executable ,"-I" ,"-S" ,str (bundle ),"status" , 250"--url" ,root ,"--json" ],cwd = self .temp .name , 251capture_output = True ,text = True ,check = False ) 252self .assertEqual (portable .returncode ,3 ) 253self .assertFalse (portable .stderr ) 254self .assertEqual (json .loads (portable .stdout )["error" ]["message" ], 255"server returned malformed JSON telemetry" ) 256finally : 257server .shutdown () 258server .server_close () 259thread .join (timeout = 2 ) 260 261def test_status_only_fallback_labels_missing_telemetry_without_inventing_work (self ): 262paths = [] 263metrics_status = [404 ] 264status = {"service" :"strata" ,"model" :"loaded-model" ,"loaded" :True , 265"started" :1_790_000_000 ,"concurrency" : {"serving" :8 }} 266 267class Handler (BaseHTTPRequestHandler ): 268def do_GET (self ): 269paths .append (self .path ) 270if self .path == "/metrics" and metrics_status [0 ]== 401 : 271self .send_error (401 ) 272return 273if self .path != "/v1/status" : 274self .send_error (404 ) 275return 276body = json .dumps (status ).encode () 277self .send_response (200 ) 278self .send_header ("Content-Type" ,"application/json" ) 279self .send_header ("Content-Length" ,str (len (body ))) 280self .end_headers () 281self .wfile .write (body ) 282 283def log_message (self ,* _args ): 284pass 285 286server = ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 287thread = threading .Thread (target = server .serve_forever ,daemon = True ) 288thread .start () 289try : 290root = f"http://127.0.0.1: { server . server_port } " 291snapshot = Endpoint (root ).snapshot () 292self .assertEqual (paths , ["/v1/telemetry" ,"/metrics" ,"/v1/status" ]) 293self .assertEqual (snapshot ["source" ],"status-only" ) 294self .assertEqual (snapshot ["quality" ]["telemetry" ],"unavailable" ) 295self .assertEqual (snapshot ["model" ], {"id" :"loaded-model" ,"loaded" :True ,"context" :None }) 296self .assertEqual (snapshot ["work" ]["slots_effective" ],8 ) 297self .assertIsNone (snapshot ["work" ]["active" ]) 298self .assertIsNone (snapshot ["rates" ]["answer_tok_s" ]) 299display = render_view (snapshot ,"overview" ,80 ,24 ) 300self .assertIn ("[NO TELEMETRY]" ,display ) 301self .assertIn ("Telemetry unavailable; status only" ,display ) 302self .assertIn ("Sample age" ,render_view (snapshot ,"overview" ,40 ,12 )) 303self .assertIn ("In flight --" ,display ) 304code ,source = self ._cli ("status" ,"--url" ,root ,"--json" ) 305self .assertEqual (code ,0 ) 306self .assertEqual (source ["snapshot" ]["quality" ]["telemetry" ],"unavailable" ) 307bundle = Path (self .temp .name )/ "status-only.pyz" 308subprocess .run ([sys .executable ,str (ROOT / "packaging/monitor_bundle.py" ), 309"build" ,str (bundle )],capture_output = True ,text = True ,check = True ) 310portable = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"status" ,"--url" ,root , 311"--json" ],capture_output = True ,text = True ,check = True ) 312portable_snapshot = json .loads (portable .stdout )["snapshot" ] 313self .assertEqual (portable_snapshot ["source" ],"status-only" ) 314self .assertIsNone (portable_snapshot ["work" ]["active" ]) 315metrics_status [0 ]= 401 316paths .clear () 317with self .assertRaises (ClientError )as denied : 318Endpoint (root ).snapshot () 319self .assertEqual (denied .exception .exit_code ,4 ) 320self .assertEqual (paths , ["/v1/telemetry" ,"/metrics" ]) 321finally : 322server .shutdown () 323server .server_close () 324thread .join (timeout = 2 ) 325 326 327if __name__ == "__main__" : 328unittest .main ()