okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
1"""Owner-local monitor connections; store references, never credential values. 2 3This module is standard-library only so the portable monitor bundle and source 4CLI resolve the same saved connection without importing server or installer code. 5""" 6 7from __future__import annotations 8 9import os 10try : 11from strata_control .private_files import private_mkdir as _private_mkdir 12except ImportError :# a thin bundle (monitor only) ships without strata_control 13def _private_mkdir (path ,* ,parents = False ,exist_ok = True ): 14path .mkdir (mode = 0o700 ,parents = parents ,exist_ok = exist_ok ) 15return path 16try : 17from strata_control import posix_owner 18except ImportError :# the same thin bundle: the old plain check 19import stat as _stat 20 21class posix_owner :# noqa: N801 22owner_only_wrong = staticmethod (lambda path ,details :os .name == "posix" and (details .st_uid != os .getuid ()or _stat .S_IMODE (details .st_mode )& 0o077 )) 23owner_only_text = staticmethod (lambda text ,path :text ) 24try : 25from strata_control import atomic as _atomic_mod 26except ImportError :# the same thin bundle: a plain replace 27class _atomic_mod :# noqa: N801 28replace = staticmethod (os .replace ) 29import hashlib 30import json 31import os 32import re 33import stat 34import tempfile 35from contextlib import contextmanager 36from pathlib import Path 37 38from strata_cli .client import server_url ,url_prefix 39 40 41NAME = re .compile (r"[a-z][a-z0-9_-]{0,63}\Z" ) 42ENV_NAME = re .compile (r"[A-Za-z_][A-Za-z0-9_]{0,127}\Z" ) 43MAX_BYTES = 4096 44DEFAULT_URL = "http://127.0.0.1:8095" 45 46 47class ConnectionError (ValueError ): 48def __init__ (self ,message :str ,exit_code :int = 2 ): 49super ().__init__ (message ) 50self .exit_code = exit_code 51 52 53def _name (value :str )-> str : 54if not isinstance (value ,str )or not NAME .fullmatch (value ): 55raise ConnectionError ("connection name must use lowercase a-z, 0-9, _ or - and start with a letter" ) 56return value 57 58 59def prefix_path (value :str )-> str : 60try : 61return url_prefix (value ) 62except ValueError as exc : 63raise ConnectionError (str (exc ))from None 64 65 66def credential_name (value :str )-> str : 67if not isinstance (value ,str )or not ENV_NAME .fullmatch (value ): 68raise ConnectionError ("credential reference must be an ASCII environment variable name" ) 69return value 70 71 72def connection_dir (* ,create :bool = False )-> Path : 73explicit = os .environ .get ("STRATA_CONNECTION_DIR" ) 74if explicit : 75directory = Path (explicit ).expanduser () 76if not directory .is_absolute (): 77raise ConnectionError ("STRATA_CONNECTION_DIR must be absolute" ) 78elif os .name == "nt" : 79base = os .environ .get ("APPDATA" ) 80directory = (Path (base )if base else Path .home ()/ "AppData" / "Roaming" )/ "Strata" / "connections" 81else : 82directory = Path (os .environ .get ("XDG_CONFIG_HOME" )or Path .home ()/ ".config" )/ "strata" / "connections" 83if create : 84_private_mkdir (directory ,parents = True ,exist_ok = True ) 85if directory .exists ()or directory .is_symlink (): 86details = directory .lstat () 87if not stat .S_ISDIR (details .st_mode )or (os .name == "posix" and 88 (posix_owner .owner_only_wrong (directory ,details ))): 89raise ConnectionError (posix_owner .owner_only_text ("connection directory must be owner-only" ,directory ),5 ) 90return directory 91 92 93def _path (name :str ,* ,create_dir :bool = False )-> Path : 94return connection_dir (create = create_dir )/ f" { _name ( name ) } .json" 95 96 97def _validate (value :object ,* ,expected_name :str | None = None )-> dict : 98if not isinstance (value ,dict )or set (value )!= {"schema_version" ,"id" ,"url" ,"prefix" ,"credential_env" }: 99raise ConnectionError ("connection has an unsupported schema" ,5 ) 100if type (value ["schema_version" ])is not int or value ["schema_version" ]!= 1 : 101raise ConnectionError ("connection has an unsupported schema version" ,5 ) 102name = _name (value ["id" ]) 103if expected_name is not None and name != expected_name : 104raise ConnectionError ("connection ID does not match its filename" ,5 ) 105try : 106url = server_url (value ["url" ]) 107except (ValueError ,TypeError ): 108raise ConnectionError ("connection URL must be a safe server root" ,5 )from None 109prefix = prefix_path (value ["prefix" ]) 110credential = credential_name (value ["credential_env" ]) 111if url != value ["url" ]or prefix != value ["prefix" ]: 112raise ConnectionError ("connection URL or prefix is not canonical" ,5 ) 113return {"schema_version" :1 ,"id" :name ,"url" :url ,"prefix" :prefix , 114"credential_env" :credential } 115 116 117def _bytes (value :dict )-> bytes : 118data = (json .dumps (value ,sort_keys = True ,indent = 2 ,ensure_ascii = False )+ "\n" ).encode ("utf-8" ) 119if len (data )> MAX_BYTES : 120raise ConnectionError ("connection record exceeds 4 KiB" ,5 ) 121return data 122 123 124def _revision (data :bytes )-> str : 125return hashlib .sha256 (data ).hexdigest ()[:16 ] 126 127 128def load (name :str )-> tuple [dict ,str ]: 129path = _path (name ) 130try : 131details = path .lstat () 132if not stat .S_ISREG (details .st_mode )or details .st_size > MAX_BYTES or \ 133 (os .name == "posix" and (posix_owner .owner_only_wrong (path ,details ))): 134raise ConnectionError (posix_owner .owner_only_text ("connection file must be a private regular file under 4 KiB" ,path ),5 ) 135data = path .read_bytes () 136value = json .loads (data .decode ("utf-8" )) 137except FileNotFoundError : 138raise ConnectionError (f"connection { name !r } is not saved; use strata connection create" ,5 )from None 139except (OSError ,UnicodeError ,ValueError )as exc : 140if isinstance (exc ,ConnectionError ): 141raise 142raise ConnectionError ("connection file is unreadable" ,5 )from None 143try : 144return _validate (value ,expected_name = name ),_revision (data ) 145except (ConnectionError ,ValueError ,TypeError )as exc : 146raise ConnectionError (f"connection file has invalid values ( { type ( exc ). __name__ } )" ,5 )from None 147 148 149def list_connections ()-> list [dict ]: 150directory = connection_dir () 151if not directory .exists (): 152return [] 153paths = [path for path in sorted (directory .glob ("*.json" ))if NAME .fullmatch (path .stem )] 154if len (paths )> 100 : 155raise ConnectionError ("more than 100 connection records need inspection" ,5 ) 156result = [] 157for path in paths : 158try : 159value ,revision = load (path .stem ) 160result .append ({"id" :value ["id" ],"url" :value ["url" ],"prefix" :value ["prefix" ], 161"credential_env" :value ["credential_env" ],"revision" :revision }) 162except ConnectionError as exc : 163result .append ({"id" :path .stem ,"error" :str (exc )}) 164return result 165 166 167def _replace (path :Path ,data :bytes )-> None : 168descriptor ,name = tempfile .mkstemp (prefix = f". { path . stem } -" ,suffix = ".tmp" ,dir = path .parent ) 169try : 170with os .fdopen (descriptor ,"wb" )as stream : 171stream .write (data ) 172stream .flush () 173os .fsync (stream .fileno ()) 174_atomic_mod .replace (name ,path ) 175if os .name == "posix" : 176try : 177parent = os .open (path .parent ,os .O_RDONLY ) 178try : 179os .fsync (parent ) 180finally : 181os .close (parent ) 182except OSError : 183# The replacement succeeded; do not report a failed save afterward. 184pass 185finally : 186if os .path .exists (name ): 187os .unlink (name ) 188 189 190@contextmanager 191def _lock (name :str ): 192path = connection_dir (create = True )/ f". { _name ( name ) } .lock" 193descriptor = os .open (path ,os .O_RDWR | os .O_CREAT | getattr (os ,"O_NOFOLLOW" ,0 ),0o600 ) 194with os .fdopen (descriptor ,"r+b" )as stream : 195details = os .fstat (stream .fileno ()) 196if not stat .S_ISREG (details .st_mode )or (os .name == "posix" and 197 (posix_owner .owner_only_wrong (path ,details ))): 198raise ConnectionError (posix_owner .owner_only_text ("connection lock must be owner-only" ,path ),5 ) 199if os .name == "nt" : 200import msvcrt 201stream .seek (0 ) 202if not stream .read (1 ): 203stream .write (b"0" ) 204stream .flush () 205stream .seek (0 ) 206msvcrt .locking (stream .fileno (),msvcrt .LK_LOCK ,1 ) 207try : 208yield 209finally : 210stream .seek (0 ) 211msvcrt .locking (stream .fileno (),msvcrt .LK_UNLCK ,1 ) 212else : 213import fcntl 214fcntl .flock (stream .fileno (),fcntl .LOCK_EX ) 215try : 216yield 217finally : 218fcntl .flock (stream .fileno (),fcntl .LOCK_UN ) 219 220 221def create (name :str ,url :str ,* ,prefix :str = "" , 222credential_env :str = "STRATA_TELEMETRY_KEY" )-> tuple [dict ,str ]: 223name = _name (name ) 224value = _validate ({"schema_version" :1 ,"id" :name ,"url" :server_url (url ), 225"prefix" :prefix_path (prefix ),"credential_env" :credential_name (credential_env )}, 226expected_name = name ) 227data = _bytes (value ) 228path = _path (name ,create_dir = True ) 229flags = os .O_WRONLY | os .O_CREAT | os .O_EXCL | getattr (os ,"O_NOFOLLOW" ,0 ) 230try : 231descriptor = os .open (path ,flags ,0o600 ) 232except FileExistsError : 233raise ConnectionError (f"connection { name !r } already exists" )from None 234try : 235with os .fdopen (descriptor ,"wb" )as stream : 236stream .write (data ) 237stream .flush () 238os .fsync (stream .fileno ()) 239except BaseException : 240path .unlink (missing_ok = True ) 241raise 242return value ,_revision (data ) 243 244 245def propose (name :str ,assignment :str )-> tuple [dict ,str ]: 246current ,revision = load (name ) 247key ,sep ,raw = assignment .partition ("=" ) 248if not sep or key not in ("url" ,"prefix" ,"credential_env" ): 249raise ConnectionError ("expected url=ROOT, prefix=/PATH or credential_env=ENV_NAME" ) 250candidate = dict (current ) 251candidate [key ]= (server_url (raw )if key == "url" else 252prefix_path (raw )if key == "prefix" else credential_name (raw )) 253return _validate (candidate ,expected_name = name ),revision 254 255 256def save (name :str ,value :dict ,* ,expected_revision :str )-> tuple [dict ,str ]: 257name = _name (name ) 258value = _validate (value ,expected_name = name ) 259if not isinstance (expected_revision ,str )or not re .fullmatch (r"[0-9a-f]{16}" ,expected_revision ): 260raise ConnectionError ("connection revision must be 16 lowercase hex characters" ) 261path = _path (name ) 262with _lock (name ): 263current ,revision = load (name ) 264if revision != expected_revision : 265raise ConnectionError ("connection changed since preview; inspect it again" ,6 ) 266data = _bytes (value ) 267if value == current : 268return current ,revision 269_replace (path ,data ) 270return value ,_revision (data ) 271 272 273def resolve (* ,url :str | None = None ,connection :str | None = None , 274credential_env :str | None = None ,timeout :float | None = None , 275environment :dict | None = None )-> dict : 276env = os .environ if environment is None else environment 277selected = connection or (None if url is not None else env .get ("STRATA_CONNECTION" )) 278if url is not None and connection is not None : 279raise ConnectionError ("choose --url or --connection, not both" ) 280if selected : 281saved ,revision = load (selected ) 282root ,prefix = saved ["url" ],saved ["prefix" ] 283key_ref = saved ["credential_env" ] 284origins = {"url" :"connection" ,"prefix" :"connection" ,"credential_env" :"connection" } 285else : 286revision = None 287root = url if url is not None else env .get ("STRATA_URL" ,DEFAULT_URL ) 288prefix = "" 289key_ref = "STRATA_API_KEY" 290origins = {"url" :"flag" if url is not None else "environment" if "STRATA_URL" in env else "default" , 291"prefix" :"default" ,"credential_env" :"default" } 292if credential_env is not None : 293key_ref = credential_env 294origins ["credential_env" ]= "flag" 295if timeout is not None and (type (timeout )not in (int ,float )or not 0 < timeout <= 30 ): 296raise ConnectionError ("timeout must be greater than zero and at most 30 seconds" ) 297origins ["timeout_s" ]= "flag" if timeout is not None else "default" 298normalized_url ,normalized_prefix = server_url (root ),prefix_path (prefix ) 299return {"url" :normalized_url ,"prefix" :normalized_prefix , 300"base_url" :normalized_url + normalized_prefix , 301"credential_env" :credential_name (key_ref ),"credential_present" :bool (env .get (key_ref )), 302"timeout_s" :timeout if timeout is not None else 3.0 , 303"connection" :selected ,"connection_revision" :revision ,"origins" :origins }