okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""Offline policy: what "no download" means, and for whom (checklist U08). 2 3The checklist asks for two claims that are easy to conflate, so this module keeps them apart: 4 5* **runtime-only no-download** — the server, while serving, fetches nothing. The engine runs from 6local files; no model, library or asset is fetched mid-request. This can be true while the machine 7has a network and while other parts of the product do download. 8* **strict offline** — nothing in the process tree reaches the network at all, including children, 9tool subprocesses and the agent runtime. This must hold even though a tool or a model file might 10want to fetch something. 11 12They are tested separately because a passing runtime-only test says nothing about the second: the 13first is about the server's own code paths, and the second is about every process it can start. 14 15How each is enforced: 16 17**Environment, for children.** Every child the server starts is given variables that the common 18runtimes honour — Hugging Face, Transformers, pip, and the proxy variables that make an accidental 19HTTP call fail fast rather than hang. This is the mechanism that reaches code we do not control. 20 21**A guard, for our own fetches.** `check_url` is the single place the product decides whether a URL 22may be fetched, so "offline" is one predicate rather than a scattered set of `if offline` checks. A 23test asserts the server's image path calls it, because a guard that is not wired in is decoration. 24 25**A preflight, for the profile.** A profile that names MCP servers, a `before_load` command or remote 26image sources cannot be strict-offline, and saying so before the server starts is more useful than 27failing on the first request. 28 29**What this cannot do.** It cannot stop a child that ignores the environment and opens a socket 30directly, because that would need a sandbox this product does not have on all three platforms. 31`limits()` states that plainly, and the qualification kit asks for the network-isolated run that 32would settle it. Recording the limit is the honest option; claiming enforcement would not be. 33""" 34 35from __future__import annotations 36 37import os 38from dataclasses import dataclass 39from typing import Any ,Mapping 40from urllib .parse import urlparse 41 42#: Environment for children. The first group is what the Python ML stack reads; the second makes an 43#: accidental HTTP call fail immediately instead of hanging on a timeout; the third tells tools that 44#: ask that they are offline. 45OFFLINE_ENV :dict [str ,str ]= { 46"HF_HUB_OFFLINE" :"1" , 47"TRANSFORMERS_OFFLINE" :"1" , 48"HF_HUB_DISABLE_TELEMETRY" :"1" , 49"DO_NOT_TRACK" :"1" , 50"PIP_NO_INDEX" :"1" , 51"PIP_DISABLE_PIP_VERSION_CHECK" :"1" , 52"NO_PROXY" :"*" , 53"no_proxy" :"*" , 54"HTTP_PROXY" :"" , 55"HTTPS_PROXY" :"" , 56"http_proxy" :"" , 57"https_proxy" :"" , 58"STRATA_OFFLINE" :"1" , 59} 60 61#: Schemes that are local by construction and therefore always allowed. 62LOCAL_SCHEMES = ("file" ,"data" ,"blob" ) 63 64#: Hosts that mean "this machine" and never leave it. 65LOCAL_HOSTS = ("localhost" ,"127.0.0.1" ,"::1" ,"[::1]" ,"0.0.0.0" ) 66 67 68@dataclass( frozen = True ) 69class Decision : 70"""Whether a URL may be fetched, and the reason either way.""" 71 72allowed :bool 73reason :str 74 75def __bool__ (self )-> bool : 76return self .allowed 77 78 79class OfflineViolation (RuntimeError ): 80"""A fetch was attempted under a policy that forbids it.""" 81 82def __init__ (self ,url :str ,reason :str )-> None : 83super ().__init__ (f"offline policy forbids fetching { url !r } : { reason } " ) 84self .url = url 85self .reason = reason 86 87 88def check_url (url :str ,* ,offline :bool )-> Decision : 89"""May this URL be fetched? 90 91A local scheme or a loopback host is allowed even under strict offline: talking to this machine 92is not a download, and forbidding it would break the local API the product is built on. 93""" 94if not offline : 95return Decision (True ,"not offline" ) 96if not url : 97return Decision (False ,"no URL" ) 98parsed = urlparse (str (url )) 99scheme = (parsed .scheme or "" ).lower () 100if scheme in LOCAL_SCHEMES : 101return Decision (True ,f"the { scheme } scheme is local" ) 102if scheme in ("" ,"http" ,"https" ): 103host = (parsed .hostname or "" ).lower () 104if scheme == "" and not host : 105# A bare path is a local file, which is how a profile usually names an image. 106return Decision (True ,"a local path, not a URL" ) 107if host in LOCAL_HOSTS : 108return Decision (True ,f" { host } is this machine" ) 109return Decision (False ,f" { scheme or 'http' } to { host or 'an unnamed host' } would leave this machine" ) 110return Decision (False ,f"the { scheme } scheme is not local" ) 111 112 113def require_url (url :str ,* ,offline :bool )-> None : 114"""`check_url`, as an exception. Used where a refusal must stop the operation.""" 115decision = check_url (url ,offline = offline ) 116if not decision .allowed : 117raise OfflineViolation (url ,decision .reason ) 118 119 120def child_environment (* ,offline :bool ,base :Mapping [str ,str ]| None = None )-> dict [str ,str ]: 121"""The environment a child process gets. 122 123Under strict offline the variables are *set*, not merely left alone: a child that would otherwise 124read the parent's proxy settings must be told not to use them. 125""" 126env = dict (base if base is not None else os .environ ) 127if offline : 128env .update (OFFLINE_ENV ) 129else : 130# Not offline: remove the markers so a previous run's policy cannot leak into this one, which 131# would make a later server mysteriously refuse to fetch. 132for key in OFFLINE_ENV : 133env .pop (key ,None ) 134return env 135 136 137def profile_requirements (cfg :Mapping [str ,Any ])-> list [str ]: 138"""The parts of a profile that need the network, named so a refusal can explain itself.""" 139needs :list [str ]= [] 140servers = cfg .get ("mcp_servers" )or cfg .get ("mcpServers" ) 141if servers : 142count = len (servers )if hasattr (servers ,"__len__" )else 1 143needs .append (f"the profile declares { count } MCP server(s), which are started as subprocesses " 144"and may fetch tools" ) 145for key in ("before_load" ,"beforeLoad" ): 146if cfg .get (key ): 147needs .append (f"the profile declares a { key } command, which runs before the model loads" ) 148for key in ("images" ,"vision" ): 149section = cfg .get (key ) 150if isinstance (section ,dict ): 151for field in ("remote_sources" ,"allowed_hosts" ,"url" ): 152if section .get (field ): 153needs .append (f"the profile's { key } . { field } permits network sources" ) 154return needs 155 156 157def ensure_strictly_offline (cfg :Mapping [str ,Any ])-> list [str ]: 158"""Why this profile cannot be strict-offline. Empty means it can. 159 160Refusing before the server starts is more useful than failing on the first request, and it keeps 161the promise precise: a profile that permits a network source is not offline, whatever the flag 162says. 163""" 164return profile_requirements (cfg ) 165 166 167def limits ()-> list [str ]: 168"""What this policy does not enforce. Stated so it is not over-read as a sandbox.""" 169return [ 170"a child that ignores the environment and opens a socket directly is not stopped; that needs " 171"an OS sandbox, which this product does not have on all three platforms" , 172"a library already loaded with its own network stack is not intercepted" , 173"DNS resolution is not blocked, so a lookup may still occur before a connection fails" , 174 ] 175 176 177def report (* ,offline :bool ,cfg :Mapping [str ,Any ]| None = None )-> dict [str ,Any ]: 178"""What the policy is doing, for the logs and the evidence record.""" 179requirements = profile_requirements (cfg or {}) 180return { 181"strict_offline" :bool (offline ), 182"runtime_only_no_download" :True , 183"child_environment" :sorted (OFFLINE_ENV )if offline else [], 184"profile_needs_network" :requirements , 185"enforced" : (["our own fetches go through check_url" , 186"every child is given the offline environment" ]if offline else 187 ["serving itself fetches nothing; downloads elsewhere are permitted" ]), 188"not_enforced" :limits ()if offline else [], 189 }