okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
8.1 KiB189 linesraw
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
6  local files; no model, library or asset is fetched mid-request. This can be true while the machine
7  has 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,
9  tool subprocesses and the agent runtime. This must hold even though a tool or a model file might
10  want 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
72    allowed: bool
73    reason: str
74
75    def __bool__(self) -> bool:
76        return self.allowed
77
78
79class OfflineViolation(RuntimeError):
80    """A fetch was attempted under a policy that forbids it."""
81
82    def __init__(self, url: str, reason: str) -> None:
83        super().__init__(f"offline policy forbids fetching {url!r}: {reason}")
84        self.url = url
85        self.reason = reason
86
87
88def check_url(url: str, *, offline: bool) -> Decision:
89    """May this URL be fetched?
90
91    A local scheme or a loopback host is allowed even under strict offline: talking to this machine
92    is not a download, and forbidding it would break the local API the product is built on.
93    """
94    if not offline:
95        return Decision(True, "not offline")
96    if not url:
97        return Decision(False, "no URL")
98    parsed = urlparse(str(url))
99    scheme = (parsed.scheme or "").lower()
100    if scheme in LOCAL_SCHEMES:
101        return Decision(True, f"the {scheme} scheme is local")
102    if scheme in ("", "http", "https"):
103        host = (parsed.hostname or "").lower()
104        if scheme == "" and not host:
105            # A bare path is a local file, which is how a profile usually names an image.
106            return Decision(True, "a local path, not a URL")
107        if host in LOCAL_HOSTS:
108            return Decision(True, f"{host} is this machine")
109        return Decision(False, f"{scheme or 'http'} to {host or 'an unnamed host'} would leave this machine")
110    return 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."""
115    decision = check_url(url, offline=offline)
116    if not decision.allowed:
117        raise 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
123    Under strict offline the variables are *set*, not merely left alone: a child that would otherwise
124    read the parent's proxy settings must be told not to use them.
125    """
126    env = dict(base if base is not None else os.environ)
127    if offline:
128        env.update(OFFLINE_ENV)
129    else:
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.
132        for key in OFFLINE_ENV:
133            env.pop(key, None)
134    return 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."""
139    needs: list[str] = []
140    servers = cfg.get("mcp_servers") or cfg.get("mcpServers")
141    if servers:
142        count = len(servers) if hasattr(servers, "__len__") else 1
143        needs.append(f"the profile declares {count} MCP server(s), which are started as subprocesses "
144                     "and may fetch tools")
145    for key in ("before_load", "beforeLoad"):
146        if cfg.get(key):
147            needs.append(f"the profile declares a {key} command, which runs before the model loads")
148    for key in ("images", "vision"):
149        section = cfg.get(key)
150        if isinstance(section, dict):
151            for field in ("remote_sources", "allowed_hosts", "url"):
152                if section.get(field):
153                    needs.append(f"the profile's {key}.{field} permits network sources")
154    return 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
160    Refusing before the server starts is more useful than failing on the first request, and it keeps
161    the promise precise: a profile that permits a network source is not offline, whatever the flag
162    says.
163    """
164    return 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."""
169    return [
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."""
179    requirements = profile_requirements(cfg or {})
180    return {
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    }