@simplexai/localmodels-linux-arm64 0.1.0-dev.61 → 0.1.0-dev.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +21 -20
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/custom_hub_http.py +27 -104
- package/modules/localmodels/library_jobs.py +4 -0
- package/modules/localmodels/memcalc_load.py +9 -4
- package/modules/localmodels/remote_ops_common.py +31 -90
- package/modules/localmodels/remote_ops_download.py +2 -0
- package/modules/localmodels/remote_ops_mirrors.py +1 -1
- package/modules/localmodels/remote_ops_ranges.py +4 -1
- package/modules/localmodels/remote_ops_redirect.py +393 -0
- package/modules/localmodels/source_cli.py +136 -23
- package/modules/localmodels/speech_jobs.py +4 -0
- package/modules/localmodels/transport.py +1 -0
- package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/RECORD +18 -17
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Unified Layer-0 HTTP redirect validation, SSRF defense, and credential stripping.
|
|
3
|
+
|
|
4
|
+
Part of the remote_ops bundle (transport.BUNDLES): standard library only, Python 3.8+, and a
|
|
5
|
+
pure leaf module (zero imports from sibling localmodels modules) so controller modules such as
|
|
6
|
+
``custom_hub_http`` and ``memcalc_load`` share the exact same policy as ``remote_ops_download``
|
|
7
|
+
without creating import cycles.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ipaddress
|
|
13
|
+
import socket
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
from typing import Any, Union
|
|
18
|
+
|
|
19
|
+
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
|
|
20
|
+
|
|
21
|
+
MAX_REDIRECTS = 5
|
|
22
|
+
SENSITIVE_REDIRECT_HEADERS = frozenset({"authorization", "cookie", "proxy-authorization"})
|
|
23
|
+
|
|
24
|
+
_NAT64_WELL_KNOWN = ipaddress.IPv6Network("64:ff9b::/96")
|
|
25
|
+
_LOOPBACK_V4 = ipaddress.IPv4Network("127.0.0.0/8")
|
|
26
|
+
_LOOPBACK_V6 = ipaddress.IPv6Network("::1/128")
|
|
27
|
+
|
|
28
|
+
# Explicit network sets (never rely on ipaddress.is_global / is_reserved, which reject Fake-IP
|
|
29
|
+
# TUN pools like 198.18.0.0/15 & fc00::/18 as well as RFC 6052 NAT64 64:ff9b::/96).
|
|
30
|
+
_ALWAYS_BLOCKED_V4: tuple[ipaddress.IPv4Network, ...] = (
|
|
31
|
+
_LOOPBACK_V4, # loopback
|
|
32
|
+
ipaddress.IPv4Network("0.0.0.0/8"), # unspecified
|
|
33
|
+
ipaddress.IPv4Network("169.254.0.0/16"), # link-local / cloud IMDS
|
|
34
|
+
ipaddress.IPv4Network("224.0.0.0/4"), # multicast
|
|
35
|
+
)
|
|
36
|
+
_ALWAYS_BLOCKED_V6: tuple[ipaddress.IPv6Network, ...] = (
|
|
37
|
+
_LOOPBACK_V6, # loopback
|
|
38
|
+
ipaddress.IPv6Network("::/128"), # unspecified
|
|
39
|
+
ipaddress.IPv6Network("fe80::/10"), # link-local
|
|
40
|
+
ipaddress.IPv6Network("ff00::/8"), # multicast
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# Fake-IP TUN pools (always blocked as literal redirect targets, allowed when returned by local
|
|
44
|
+
# DNS for a non-local FQDN).
|
|
45
|
+
_FAKEIP_LITERAL_V4: tuple[ipaddress.IPv4Network, ...] = (
|
|
46
|
+
ipaddress.IPv4Network("198.18.0.0/15"), # RFC 2544: FlClash/Mihomo/Clash/sing-box/Surge/V2RayN
|
|
47
|
+
)
|
|
48
|
+
_FAKEIP_LITERAL_V6: tuple[ipaddress.IPv6Network, ...] = (
|
|
49
|
+
ipaddress.IPv6Network("fc00::/18"), # Mihomo / Clash / sing-box IPv6 fake-IP
|
|
50
|
+
ipaddress.IPv6Network("fdfe:dcba:9876::/48"), # Surge IPv6 fake-IP
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# CGNAT / Tailscale / custom TUN range (allowed on DNS for public FQDNs; allowed as literal only
|
|
54
|
+
# from private origins).
|
|
55
|
+
_CGNAT_V4 = ipaddress.IPv4Network("100.64.0.0/10")
|
|
56
|
+
|
|
57
|
+
_DNS_ALLOWED_TUN_V4: tuple[ipaddress.IPv4Network, ...] = (*_FAKEIP_LITERAL_V4, _CGNAT_V4)
|
|
58
|
+
_DNS_ALLOWED_TUN_V6: tuple[ipaddress.IPv6Network, ...] = _FAKEIP_LITERAL_V6
|
|
59
|
+
|
|
60
|
+
_LAN_PRIVATE_V4: tuple[ipaddress.IPv4Network, ...] = (
|
|
61
|
+
ipaddress.IPv4Network("10.0.0.0/8"),
|
|
62
|
+
ipaddress.IPv4Network("172.16.0.0/12"),
|
|
63
|
+
ipaddress.IPv4Network("192.168.0.0/16"),
|
|
64
|
+
)
|
|
65
|
+
_LAN_PRIVATE_V6: tuple[ipaddress.IPv6Network, ...] = (
|
|
66
|
+
ipaddress.IPv6Network("fc00::/7"), # RFC 4193 ULA (checked after Fake-IP IPv6 sets on DNS)
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
_ALWAYS_BLOCKED_HOSTNAMES = frozenset({"localhost", "metadata.google.internal", "metadata.goog"})
|
|
70
|
+
_PRIVATE_LOCAL_SUFFIXES = (".local", ".internal", ".home.arpa", ".localdomain")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class UnsafeRedirectError(urllib.error.URLError):
|
|
74
|
+
"""Deterministic redirect security/policy refusal (never used for transient DNS failures)."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def normalize_host(host: str | None) -> str:
|
|
78
|
+
"""Lowercase a hostname or IP literal, stripping whitespace, IPv6 brackets, and trailing dots."""
|
|
79
|
+
clean = (host or "").strip().lower()
|
|
80
|
+
if clean.startswith("[") and clean.endswith("]"):
|
|
81
|
+
clean = clean[1:-1]
|
|
82
|
+
return clean.rstrip(".")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_hf_mirror_host(host: str | None) -> bool:
|
|
86
|
+
"""True for ``hf-mirror.com`` and any subdomain or trailing-dot spelling."""
|
|
87
|
+
norm = normalize_host(host)
|
|
88
|
+
return norm == "hf-mirror.com" or norm.endswith(".hf-mirror.com")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _parse_port(parsed: urllib.parse.SplitResult) -> int | None:
|
|
92
|
+
try:
|
|
93
|
+
port = parsed.port
|
|
94
|
+
except ValueError as exc:
|
|
95
|
+
raise UnsafeRedirectError(f"redirect refused: invalid port: {exc}") from None
|
|
96
|
+
if port is not None and not 1 <= port <= 65535:
|
|
97
|
+
raise UnsafeRedirectError(f"redirect refused: invalid port {port}")
|
|
98
|
+
return port
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def url_origin(url: str) -> tuple[str, str, int]:
|
|
102
|
+
"""Return ``(scheme, normalized_host, effective_port)``, rejecting malformed ports."""
|
|
103
|
+
parsed = urllib.parse.urlsplit(url)
|
|
104
|
+
scheme = parsed.scheme.lower()
|
|
105
|
+
host = normalize_host(parsed.hostname)
|
|
106
|
+
port = _parse_port(parsed)
|
|
107
|
+
if port is None:
|
|
108
|
+
port = 443 if scheme == "https" else (80 if scheme == "http" else 0)
|
|
109
|
+
return (scheme, host, port)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _parse_ip(raw: str) -> IPAddr | None:
|
|
113
|
+
candidate = normalize_host(raw).split("%", 1)[0]
|
|
114
|
+
if not candidate:
|
|
115
|
+
return None
|
|
116
|
+
try:
|
|
117
|
+
return ipaddress.ip_address(candidate)
|
|
118
|
+
except ValueError:
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _unwrap_ip(addr: IPAddr) -> IPAddr:
|
|
123
|
+
if isinstance(addr, ipaddress.IPv6Address):
|
|
124
|
+
if addr.ipv4_mapped is not None:
|
|
125
|
+
return addr.ipv4_mapped
|
|
126
|
+
if addr in _NAT64_WELL_KNOWN:
|
|
127
|
+
return ipaddress.IPv4Address(int(addr) & 0xFFFFFFFF)
|
|
128
|
+
return addr
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _in_v4_or_v6(
|
|
132
|
+
addr: IPAddr,
|
|
133
|
+
v4_nets: tuple[ipaddress.IPv4Network, ...],
|
|
134
|
+
v6_nets: tuple[ipaddress.IPv6Network, ...],
|
|
135
|
+
) -> bool:
|
|
136
|
+
if isinstance(addr, ipaddress.IPv4Address):
|
|
137
|
+
return any(addr in net for net in v4_nets)
|
|
138
|
+
return any(addr in net for net in v6_nets)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _is_loopback_ip(addr: IPAddr) -> bool:
|
|
142
|
+
return (
|
|
143
|
+
(addr in _LOOPBACK_V4)
|
|
144
|
+
if isinstance(addr, ipaddress.IPv4Address)
|
|
145
|
+
else (addr in _LOOPBACK_V6)
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _is_always_blocked_ip(addr: IPAddr) -> bool:
|
|
150
|
+
return _in_v4_or_v6(addr, _ALWAYS_BLOCKED_V4, _ALWAYS_BLOCKED_V6)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _is_fakeip_literal(addr: IPAddr) -> bool:
|
|
154
|
+
return _in_v4_or_v6(addr, _FAKEIP_LITERAL_V4, _FAKEIP_LITERAL_V6)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _is_dns_allowed_tun(addr: IPAddr) -> bool:
|
|
158
|
+
return _in_v4_or_v6(addr, _DNS_ALLOWED_TUN_V4, _DNS_ALLOWED_TUN_V6)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _is_lan_private_ip(addr: IPAddr) -> bool:
|
|
162
|
+
return _in_v4_or_v6(addr, _LAN_PRIVATE_V4, _LAN_PRIVATE_V6)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _is_lan_private_or_cgnat(addr: IPAddr) -> bool:
|
|
166
|
+
if isinstance(addr, ipaddress.IPv4Address) and addr in _CGNAT_V4:
|
|
167
|
+
return True
|
|
168
|
+
return _is_lan_private_ip(addr)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _is_always_blocked_hostname(host: str) -> bool:
|
|
172
|
+
return host in _ALWAYS_BLOCKED_HOSTNAMES or host.endswith(".localhost")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _is_literal_loopback(host: str) -> bool:
|
|
176
|
+
if host == "localhost":
|
|
177
|
+
return True
|
|
178
|
+
parsed = _parse_ip(host)
|
|
179
|
+
return parsed is not None and _is_loopback_ip(_unwrap_ip(parsed))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _is_private_origin_syntactic(source_url: str | None) -> bool:
|
|
183
|
+
"""True when ``source_url`` explicitly names a LAN/corporate mirror host or private IP."""
|
|
184
|
+
if not source_url:
|
|
185
|
+
return False
|
|
186
|
+
host = normalize_host(urllib.parse.urlsplit(source_url).hostname)
|
|
187
|
+
if not host or _is_always_blocked_hostname(host):
|
|
188
|
+
return False
|
|
189
|
+
literal = _parse_ip(host)
|
|
190
|
+
if literal is not None:
|
|
191
|
+
unwrapped = _unwrap_ip(literal)
|
|
192
|
+
if _is_always_blocked_ip(unwrapped) or _is_fakeip_literal(unwrapped):
|
|
193
|
+
return False
|
|
194
|
+
return _is_lan_private_or_cgnat(unwrapped)
|
|
195
|
+
return host.endswith(_PRIVATE_LOCAL_SUFFIXES) or "." not in host
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _source_resolves_lan_private(source_url: str | None) -> bool:
|
|
199
|
+
"""Lazy check for custom RFC 1918 / ULA Fake-IP TUN pools or transparent corporate proxies."""
|
|
200
|
+
if not source_url or is_proxy_routed(source_url):
|
|
201
|
+
return False
|
|
202
|
+
try:
|
|
203
|
+
_, src_host, src_port = url_origin(source_url)
|
|
204
|
+
except UnsafeRedirectError:
|
|
205
|
+
return False
|
|
206
|
+
if not src_host or _is_always_blocked_hostname(src_host) or _parse_ip(src_host) is not None:
|
|
207
|
+
return False
|
|
208
|
+
try:
|
|
209
|
+
records = socket.getaddrinfo(src_host, src_port or 443, type=socket.SOCK_STREAM)
|
|
210
|
+
except OSError:
|
|
211
|
+
return False
|
|
212
|
+
resolved: list[IPAddr] = []
|
|
213
|
+
for entry in records:
|
|
214
|
+
ip = _parse_ip(str(entry[4][0]))
|
|
215
|
+
if ip is not None:
|
|
216
|
+
resolved.append(_unwrap_ip(ip))
|
|
217
|
+
return (
|
|
218
|
+
bool(resolved)
|
|
219
|
+
and not any(_is_always_blocked_ip(ip) for ip in resolved)
|
|
220
|
+
and any(_is_lan_private_ip(ip) for ip in resolved)
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def is_proxy_routed(url: str) -> bool:
|
|
225
|
+
"""True when urllib routes ``url`` via an explicit HTTP/HTTPS/SOCKS proxy (not bypassed)."""
|
|
226
|
+
parsed = urllib.parse.urlsplit(url)
|
|
227
|
+
scheme = parsed.scheme.lower()
|
|
228
|
+
host = normalize_host(parsed.hostname)
|
|
229
|
+
if not scheme or not host:
|
|
230
|
+
return False
|
|
231
|
+
proxies = {k.lower(): v for k, v in urllib.request.getproxies().items() if v}
|
|
232
|
+
if not proxies.get(scheme):
|
|
233
|
+
return False
|
|
234
|
+
try:
|
|
235
|
+
port = parsed.port
|
|
236
|
+
except ValueError:
|
|
237
|
+
return False
|
|
238
|
+
if port is not None:
|
|
239
|
+
host_with_port = f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
|
|
240
|
+
else:
|
|
241
|
+
host_with_port = host
|
|
242
|
+
try:
|
|
243
|
+
if urllib.request.proxy_bypass(host_with_port):
|
|
244
|
+
return False
|
|
245
|
+
if host_with_port != host and urllib.request.proxy_bypass(host):
|
|
246
|
+
return False
|
|
247
|
+
except Exception: # noqa: BLE001 - platform proxy_bypass quirks must not crash
|
|
248
|
+
return False
|
|
249
|
+
return True
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _validate_literal_ip(
|
|
253
|
+
host: str,
|
|
254
|
+
literal: IPAddr,
|
|
255
|
+
*,
|
|
256
|
+
source_is_private: bool,
|
|
257
|
+
allow_insecure_loopback: bool,
|
|
258
|
+
) -> None:
|
|
259
|
+
unwrapped = _unwrap_ip(literal)
|
|
260
|
+
if _is_always_blocked_ip(unwrapped):
|
|
261
|
+
if allow_insecure_loopback and _is_loopback_ip(unwrapped):
|
|
262
|
+
return
|
|
263
|
+
raise UnsafeRedirectError(f"redirect refused: disallowed IP {host!r}")
|
|
264
|
+
if _is_fakeip_literal(unwrapped):
|
|
265
|
+
raise UnsafeRedirectError(f"redirect refused: non-public IP {host!r}")
|
|
266
|
+
if _is_lan_private_or_cgnat(unwrapped) and not source_is_private:
|
|
267
|
+
raise UnsafeRedirectError(f"redirect refused: non-public IP {host!r}")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _validate_resolved_ips(
|
|
271
|
+
host: str,
|
|
272
|
+
records: list[Any],
|
|
273
|
+
*,
|
|
274
|
+
source_url: str | None,
|
|
275
|
+
source_is_private: bool,
|
|
276
|
+
) -> None:
|
|
277
|
+
if not records:
|
|
278
|
+
raise urllib.error.URLError(f"DNS lookup returned no addresses for {host!r}")
|
|
279
|
+
source_lan_private: bool | None = None
|
|
280
|
+
for entry in records:
|
|
281
|
+
raw_ip = str(entry[4][0])
|
|
282
|
+
parsed_ip = _parse_ip(raw_ip)
|
|
283
|
+
if parsed_ip is None:
|
|
284
|
+
raise UnsafeRedirectError(f"redirect refused: invalid IP for {host!r}")
|
|
285
|
+
unwrapped = _unwrap_ip(parsed_ip)
|
|
286
|
+
if _is_always_blocked_ip(unwrapped):
|
|
287
|
+
raise UnsafeRedirectError(f"redirect refused: disallowed IP for {host!r}")
|
|
288
|
+
if _is_dns_allowed_tun(unwrapped):
|
|
289
|
+
continue
|
|
290
|
+
if _is_lan_private_ip(unwrapped):
|
|
291
|
+
if source_is_private:
|
|
292
|
+
continue
|
|
293
|
+
if source_lan_private is None:
|
|
294
|
+
source_lan_private = _source_resolves_lan_private(source_url)
|
|
295
|
+
if source_lan_private:
|
|
296
|
+
continue
|
|
297
|
+
raise UnsafeRedirectError(f"redirect refused: non-public IP for {host!r}")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def validate_redirect_url(
|
|
301
|
+
target_url: str,
|
|
302
|
+
*,
|
|
303
|
+
source_url: str | None = None,
|
|
304
|
+
allow_insecure_loopback: bool = False,
|
|
305
|
+
) -> None:
|
|
306
|
+
"""Enforce HTTPS, URL hygiene, and proxy/Fake-IP-aware SSRF defense on redirect targets."""
|
|
307
|
+
parsed = urllib.parse.urlsplit(target_url)
|
|
308
|
+
scheme = parsed.scheme.lower()
|
|
309
|
+
host = normalize_host(parsed.hostname)
|
|
310
|
+
port = _parse_port(parsed)
|
|
311
|
+
if parsed.username is not None or parsed.password is not None:
|
|
312
|
+
raise UnsafeRedirectError("redirect refused: credentials in redirect URL")
|
|
313
|
+
if not host:
|
|
314
|
+
raise UnsafeRedirectError("redirect refused: missing target host")
|
|
315
|
+
loopback_test_ok = allow_insecure_loopback and scheme == "http" and _is_literal_loopback(host)
|
|
316
|
+
if scheme != "https" and not loopback_test_ok:
|
|
317
|
+
raise UnsafeRedirectError(f"redirect refused: non-HTTPS scheme {scheme!r}")
|
|
318
|
+
if loopback_test_ok:
|
|
319
|
+
return
|
|
320
|
+
if _is_always_blocked_hostname(host):
|
|
321
|
+
if allow_insecure_loopback and host == "localhost":
|
|
322
|
+
return
|
|
323
|
+
raise UnsafeRedirectError(f"redirect refused: local hostname {host!r}")
|
|
324
|
+
source_is_private = _is_private_origin_syntactic(source_url)
|
|
325
|
+
literal = _parse_ip(host)
|
|
326
|
+
if literal is not None:
|
|
327
|
+
_validate_literal_ip(
|
|
328
|
+
host,
|
|
329
|
+
literal,
|
|
330
|
+
source_is_private=source_is_private,
|
|
331
|
+
allow_insecure_loopback=allow_insecure_loopback,
|
|
332
|
+
)
|
|
333
|
+
return
|
|
334
|
+
if host.endswith(_PRIVATE_LOCAL_SUFFIXES) and not source_is_private:
|
|
335
|
+
raise UnsafeRedirectError(f"redirect refused: local hostname {host!r}")
|
|
336
|
+
if is_proxy_routed(target_url):
|
|
337
|
+
return
|
|
338
|
+
try:
|
|
339
|
+
records = socket.getaddrinfo(host, port or 443, type=socket.SOCK_STREAM)
|
|
340
|
+
except OSError as exc:
|
|
341
|
+
# Preserve transient DNS failures as standard URLError (NOT UnsafeRedirectError) so
|
|
342
|
+
# callers keep retryability and classify genuine offline outages as NETWORK_UNAVAILABLE.
|
|
343
|
+
raise urllib.error.URLError(exc) from None
|
|
344
|
+
_validate_resolved_ips(
|
|
345
|
+
host, records, source_url=source_url, source_is_private=source_is_private
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
class SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
350
|
+
"""Enforce HTTPS + proxy/Fake-IP-aware anti-SSRF and strip credentials on origin change."""
|
|
351
|
+
|
|
352
|
+
max_redirections = MAX_REDIRECTS
|
|
353
|
+
|
|
354
|
+
def __init__(self, *, allow_insecure_loopback: bool = False) -> None:
|
|
355
|
+
self._allow_insecure_loopback = allow_insecure_loopback
|
|
356
|
+
|
|
357
|
+
def allow_loopback(self) -> bool:
|
|
358
|
+
"""Whether loopback HTTP redirects are permitted (internal unit-test hook only)."""
|
|
359
|
+
return self._allow_insecure_loopback
|
|
360
|
+
|
|
361
|
+
def redirect_request(
|
|
362
|
+
self,
|
|
363
|
+
req: urllib.request.Request,
|
|
364
|
+
fp: Any,
|
|
365
|
+
code: int,
|
|
366
|
+
msg: str,
|
|
367
|
+
headers: Any,
|
|
368
|
+
newurl: str,
|
|
369
|
+
) -> urllib.request.Request | None:
|
|
370
|
+
hops = int(getattr(req, "_safe_redirect_hops", 0))
|
|
371
|
+
if hops >= self.max_redirections:
|
|
372
|
+
raise UnsafeRedirectError("redirect refused: redirect limit exceeded")
|
|
373
|
+
if not newurl or not newurl.strip():
|
|
374
|
+
raise UnsafeRedirectError("redirect refused: missing redirect target")
|
|
375
|
+
raw_split = urllib.parse.urlsplit(newurl.strip())
|
|
376
|
+
if raw_split.scheme.lower() in ("http", "https") and not raw_split.hostname:
|
|
377
|
+
raise UnsafeRedirectError("redirect refused: missing target host")
|
|
378
|
+
resolved = urllib.parse.urljoin(req.full_url, newurl)
|
|
379
|
+
validate_redirect_url(
|
|
380
|
+
resolved,
|
|
381
|
+
source_url=req.full_url,
|
|
382
|
+
allow_insecure_loopback=self.allow_loopback(),
|
|
383
|
+
)
|
|
384
|
+
redirected = super().redirect_request(req, fp, code, msg, headers, resolved)
|
|
385
|
+
if redirected is None:
|
|
386
|
+
return None
|
|
387
|
+
redirected.__dict__["_safe_redirect_hops"] = hops + 1
|
|
388
|
+
if url_origin(req.full_url) != url_origin(resolved):
|
|
389
|
+
for bag in (redirected.headers, redirected.unredirected_hdrs):
|
|
390
|
+
for key in list(bag.keys()):
|
|
391
|
+
if key.lower() in SENSITIVE_REDIRECT_HEADERS:
|
|
392
|
+
del bag[key]
|
|
393
|
+
return redirected
|
|
@@ -16,6 +16,7 @@ from localmodels import (
|
|
|
16
16
|
library_convert,
|
|
17
17
|
library_gateway,
|
|
18
18
|
library_jobs,
|
|
19
|
+
library_pricing,
|
|
19
20
|
library_serve,
|
|
20
21
|
library_state,
|
|
21
22
|
library_status,
|
|
@@ -148,14 +149,89 @@ def _read_stdin_json() -> dict[str, Any]:
|
|
|
148
149
|
return parsed
|
|
149
150
|
|
|
150
151
|
|
|
151
|
-
def
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
152
|
+
def _record_base_url(record: dict[str, Any] | None) -> str | None:
|
|
153
|
+
if not isinstance(record, dict):
|
|
154
|
+
return None
|
|
155
|
+
plan = record.get("plan")
|
|
156
|
+
endpoint = plan.get("endpoint") if isinstance(plan, dict) else None
|
|
157
|
+
base_url = endpoint.get("base_url") if isinstance(endpoint, dict) else None
|
|
158
|
+
return str(base_url) if isinstance(base_url, str) and base_url else None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _valid_pi_model(registration: object) -> str | None:
|
|
162
|
+
if not isinstance(registration, dict):
|
|
163
|
+
return None
|
|
164
|
+
pi_model = registration.get("pi_model")
|
|
165
|
+
if isinstance(pi_model, str) and pi_model.strip():
|
|
166
|
+
return pi_model
|
|
167
|
+
return None
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _find_record(
|
|
171
|
+
model_id: str, records: list[library_state.Record] | None = None
|
|
172
|
+
) -> dict[str, Any] | None:
|
|
173
|
+
existing = library_state.records() if records is None else records
|
|
174
|
+
for record in existing:
|
|
175
|
+
if str(record["id"]) == model_id:
|
|
155
176
|
return cast(dict[str, Any], record)
|
|
156
177
|
return None
|
|
157
178
|
|
|
158
179
|
|
|
180
|
+
def _resolve_local_model_id(
|
|
181
|
+
model_id: str, records: list[library_state.Record] | None = None
|
|
182
|
+
) -> str:
|
|
183
|
+
"""Resolve ``model_id`` consistently with ``library_serve.load`` (exact record IDs including
|
|
184
|
+
custom Hub and kept/adopted models, catalog ``id:QUANT``, bare catalog aliases, and PolyStrata
|
|
185
|
+
recipes)."""
|
|
186
|
+
existing = library_state.records() if records is None else records
|
|
187
|
+
if any(str(record["id"]) == model_id for record in existing):
|
|
188
|
+
return model_id
|
|
189
|
+
return library_pricing.find(model_id, library_pricing.entries()).id
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _preferred_pi_model() -> str | None:
|
|
193
|
+
"""Return the saved local ``runtime_model`` if present, else Pi's configured default."""
|
|
194
|
+
try:
|
|
195
|
+
saved = source_byok.load_source_state()
|
|
196
|
+
except (OSError, ValueError, ByokError):
|
|
197
|
+
saved = None
|
|
198
|
+
if saved is not None and saved["mode"] == "local" and saved["runtime_model"]:
|
|
199
|
+
return saved["runtime_model"]
|
|
200
|
+
try:
|
|
201
|
+
raw = json.loads(
|
|
202
|
+
(library_gateway.pi_profile() / "settings.json").read_text(encoding="utf-8")
|
|
203
|
+
)
|
|
204
|
+
except (OSError, ValueError):
|
|
205
|
+
return None
|
|
206
|
+
if not isinstance(raw, dict):
|
|
207
|
+
return None
|
|
208
|
+
provider = raw.get("defaultProvider")
|
|
209
|
+
model = raw.get("defaultModel")
|
|
210
|
+
if isinstance(provider, str) and provider and isinstance(model, str) and model:
|
|
211
|
+
return f"{provider}/{model}"
|
|
212
|
+
return None
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _loaded_local_record() -> dict[str, Any] | None:
|
|
216
|
+
library_convert.convert_once()
|
|
217
|
+
loaded = [
|
|
218
|
+
cast(dict[str, Any], record)
|
|
219
|
+
for record in library_state.records()
|
|
220
|
+
if record.get("state") == "loaded"
|
|
221
|
+
]
|
|
222
|
+
if not loaded:
|
|
223
|
+
return None
|
|
224
|
+
preferred = _preferred_pi_model()
|
|
225
|
+
if preferred is not None:
|
|
226
|
+
for record in loaded:
|
|
227
|
+
if _valid_pi_model(record.get("registration")) == preferred:
|
|
228
|
+
return record
|
|
229
|
+
for record in loaded:
|
|
230
|
+
if _valid_pi_model(record.get("registration")) is not None:
|
|
231
|
+
return record
|
|
232
|
+
return loaded[0]
|
|
233
|
+
|
|
234
|
+
|
|
159
235
|
def _unload_loaded_local_models(base_dir: str) -> list[str]:
|
|
160
236
|
library_convert.convert_once()
|
|
161
237
|
unloaded: list[str] = []
|
|
@@ -175,12 +251,11 @@ def _gateway_url() -> str | None:
|
|
|
175
251
|
def _infer_default_state(harness_root: Path | None) -> SourceState:
|
|
176
252
|
loaded = _loaded_local_record()
|
|
177
253
|
if loaded is not None:
|
|
178
|
-
reg = loaded.get("registration") or {}
|
|
179
254
|
return {
|
|
180
255
|
"schema": source_byok.SOURCE_SCHEMA,
|
|
181
256
|
"mode": "local",
|
|
182
257
|
"runtime": "pi",
|
|
183
|
-
"runtime_model":
|
|
258
|
+
"runtime_model": _valid_pi_model(loaded.get("registration")) or "",
|
|
184
259
|
"model_label": None,
|
|
185
260
|
"gateway_url": _gateway_url(),
|
|
186
261
|
"environment": {"PI_CODING_AGENT_DIR": str(library_gateway.pi_profile())},
|
|
@@ -310,32 +385,70 @@ def _apply_subscription(args: argparse.Namespace, runtime: Runtime) -> SourceSta
|
|
|
310
385
|
)
|
|
311
386
|
|
|
312
387
|
|
|
388
|
+
def _load_target_local_record(
|
|
389
|
+
model_id: str, base_dir: str
|
|
390
|
+
) -> tuple[library_state.Registration, str]:
|
|
391
|
+
"""Ensure ``model_id`` is loaded and return its registration and valid ``pi_model``.
|
|
392
|
+
|
|
393
|
+
Never falls back to another loaded model: if the requested model is missing, not in
|
|
394
|
+
``loaded`` state, or lacks a valid ``registration.pi_model``, raises ``LibraryError``.
|
|
395
|
+
"""
|
|
396
|
+
records = library_state.records()
|
|
397
|
+
target_id = _resolve_local_model_id(model_id, records)
|
|
398
|
+
others = [
|
|
399
|
+
str(r["id"]) for r in records if r.get("state") == "loaded" and str(r["id"]) != target_id
|
|
400
|
+
]
|
|
401
|
+
current = _find_record(target_id, records)
|
|
402
|
+
base_url = _record_base_url(current)
|
|
403
|
+
answering = bool(
|
|
404
|
+
current is not None
|
|
405
|
+
and current.get("state") == "loaded"
|
|
406
|
+
and base_url is not None
|
|
407
|
+
and library_status.answering(base_url)
|
|
408
|
+
)
|
|
409
|
+
if not answering or _gateway_url() is None:
|
|
410
|
+
library_serve.load(target_id, base_dir, others)
|
|
411
|
+
loaded = _find_record(target_id)
|
|
412
|
+
if loaded is None or loaded.get("state") != "loaded":
|
|
413
|
+
state_label = str(loaded.get("state")) if loaded is not None else "missing"
|
|
414
|
+
raise LibraryError(
|
|
415
|
+
"INVALID_STATE",
|
|
416
|
+
f"Target local model {target_id} is not loaded (state: {state_label}).",
|
|
417
|
+
failed=True,
|
|
418
|
+
)
|
|
419
|
+
reg = loaded.get("registration")
|
|
420
|
+
pi_model = _valid_pi_model(reg)
|
|
421
|
+
if pi_model is None:
|
|
422
|
+
raise LibraryError(
|
|
423
|
+
"GATEWAY_REGISTRATION_FAILED",
|
|
424
|
+
f"Target local model {target_id} has no valid Pi model registration.",
|
|
425
|
+
failed=True,
|
|
426
|
+
)
|
|
427
|
+
return cast(library_state.Registration, reg), pi_model
|
|
428
|
+
|
|
429
|
+
|
|
313
430
|
def _apply_local(args: argparse.Namespace) -> SourceState:
|
|
314
431
|
library_convert.convert_once()
|
|
432
|
+
reg_opt: library_state.Registration | None
|
|
315
433
|
if args.model:
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
and current.get("state") == "loaded"
|
|
325
|
-
and library_status.answering(str(current["plan"]["endpoint"]["base_url"]))
|
|
434
|
+
reg_opt, pi_model = _load_target_local_record(args.model, args.base_dir)
|
|
435
|
+
else:
|
|
436
|
+
loaded = _loaded_local_record()
|
|
437
|
+
raw_reg = (loaded or {}).get("registration")
|
|
438
|
+
reg_opt = (
|
|
439
|
+
cast(library_state.Registration, raw_reg)
|
|
440
|
+
if isinstance(raw_reg, dict) and raw_reg
|
|
441
|
+
else None
|
|
326
442
|
)
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
reg = (loaded or {}).get("registration") or {}
|
|
331
|
-
if reg and _gateway_url() is not None:
|
|
332
|
-
library_gateway.reconcile_pi_default(cast(library_state.Registration, reg))
|
|
443
|
+
pi_model = _valid_pi_model(reg_opt) or ""
|
|
444
|
+
if reg_opt is not None and _gateway_url() is not None:
|
|
445
|
+
library_gateway.reconcile_pi_default(reg_opt)
|
|
333
446
|
return source_byok.save_source_state(
|
|
334
447
|
{
|
|
335
448
|
"schema": source_byok.SOURCE_SCHEMA,
|
|
336
449
|
"mode": "local",
|
|
337
450
|
"runtime": "pi",
|
|
338
|
-
"runtime_model":
|
|
451
|
+
"runtime_model": pi_model,
|
|
339
452
|
"model_label": None,
|
|
340
453
|
"gateway_url": _gateway_url(),
|
|
341
454
|
"environment": {"PI_CODING_AGENT_DIR": str(library_gateway.pi_profile())},
|
|
@@ -219,6 +219,10 @@ def _classify_download_error(message: str) -> str:
|
|
|
219
219
|
return "CHECKSUM_MISMATCH"
|
|
220
220
|
if "low disk space" in lowered or "no space left" in lowered:
|
|
221
221
|
return "DISK_INSUFFICIENT"
|
|
222
|
+
if any(
|
|
223
|
+
phrase in lowered for phrase in ("redirect refused", "blocked redirect", "unsafe redirect")
|
|
224
|
+
):
|
|
225
|
+
return "DOWNLOAD_FAILED"
|
|
222
226
|
network_terms = ("urlopen", "name or service", "timed out", "connection", "network", "resolve")
|
|
223
227
|
if any(term in lowered for term in network_terms):
|
|
224
228
|
return "NETWORK_UNAVAILABLE"
|