@simplexai/localmodels-win32-x64 0.1.0-dev.60 → 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 +78 -64
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +5 -3
- package/modules/localmodels/auth_proxy.py +185 -19
- package/modules/localmodels/catalog.json +363 -0
- package/modules/localmodels/catalog.py +1 -1
- package/modules/localmodels/catalog_add.py +5 -5
- package/modules/localmodels/catalog_license.py +2 -0
- package/modules/localmodels/catalog_recipes.py +2 -0
- package/modules/localmodels/cli_parser.py +6 -2
- package/modules/localmodels/context_policy.py +40 -4
- package/modules/localmodels/custom_hub_http.py +27 -104
- package/modules/localmodels/debug_mode.py +13 -0
- package/modules/localmodels/debug_stub_server.py +156 -1
- package/modules/localmodels/deploy.py +11 -2
- package/modules/localmodels/download-mirrors.json +12 -0
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
- package/modules/localmodels/engines-whisper-b5454.json +120 -1
- package/modules/localmodels/gateway_app_bifrost.py +14 -14
- package/modules/localmodels/gateway_bifrost.py +4 -1
- package/modules/localmodels/gateway_cli.py +14 -80
- package/modules/localmodels/gateway_server.py +88 -16
- package/modules/localmodels/gpu_specs.py +35 -1
- package/modules/localmodels/harness.py +1 -2
- package/modules/localmodels/hf_repo.py +12 -4
- package/modules/localmodels/install.py +4 -4
- package/modules/localmodels/library_jobs.py +4 -0
- package/modules/localmodels/library_serve.py +69 -13
- package/modules/localmodels/memcalc_load.py +9 -4
- package/modules/localmodels/npm_transport.py +4 -58
- package/modules/localmodels/recommend_cli.py +2 -1
- package/modules/localmodels/remote_ops.py +120 -713
- package/modules/localmodels/remote_ops_common.py +670 -0
- package/modules/localmodels/remote_ops_download.py +399 -381
- package/modules/localmodels/remote_ops_mirrors.py +27 -66
- package/modules/localmodels/remote_ops_prepare.py +43 -35
- package/modules/localmodels/remote_ops_ranges.py +102 -63
- package/modules/localmodels/remote_ops_redirect.py +393 -0
- package/modules/localmodels/remote_ops_remove.py +30 -22
- package/modules/localmodels/remote_ops_service.py +102 -95
- package/modules/localmodels/remote_ops_verify.py +94 -63
- package/modules/localmodels/runtime_cli.py +15 -5
- package/modules/localmodels/runtime_io.py +54 -1
- package/modules/localmodels/source_cli.py +136 -23
- package/modules/localmodels/speech-sv.txt +93 -0
- package/modules/localmodels/speech_admission.py +437 -0
- package/modules/localmodels/speech_catalog.py +170 -0
- package/modules/localmodels/speech_cli.py +273 -0
- package/modules/localmodels/speech_jobs.py +776 -0
- package/modules/localmodels/speech_model.py +404 -0
- package/modules/localmodels/speech_serve.py +287 -0
- package/modules/localmodels/speech_server.py +837 -0
- package/modules/localmodels/speech_state.py +697 -0
- package/modules/localmodels/speech_worker_sensevoice.py +255 -0
- package/modules/localmodels/speech_workers.py +783 -0
- package/modules/localmodels/stack.py +0 -33
- package/modules/localmodels/stack_auto.py +5 -3
- package/modules/localmodels/stack_aux_gpu.py +45 -4
- package/modules/localmodels/stack_capacity.py +77 -8
- package/modules/localmodels/stack_cli.py +16 -1
- package/modules/localmodels/stack_compose.py +1 -1
- package/modules/localmodels/stack_down.py +24 -1
- package/modules/localmodels/stack_hardware.py +57 -88
- package/modules/localmodels/stack_hardware_text.py +4 -59
- package/modules/localmodels/stack_memory.py +13 -3
- package/modules/localmodels/stack_suite.py +9 -10
- package/modules/localmodels/stack_summary.py +4 -4
- package/modules/localmodels/stack_view_llm.py +1 -1
- package/modules/localmodels/transport.py +4 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/RECORD +75 -61
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/NOTICE +9 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev60.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
|
|
@@ -2,9 +2,8 @@
|
|
|
2
2
|
"""remote_ops ``remove`` action: service files and the shared slice; weights stay unless purged.
|
|
3
3
|
|
|
4
4
|
Part of the remote_ops bundle shipped to the target as one stdin payload (transport.BUNDLES):
|
|
5
|
-
standard library only, Python 3.8+. Shared primitives
|
|
6
|
-
here
|
|
7
|
-
private-name imports.
|
|
5
|
+
standard library only, Python 3.8+. Shared primitives live in ``remote_ops_common`` and are used
|
|
6
|
+
here via ``remote_ops_common.<name>`` so the bundle stays acyclic with no private-name accesses.
|
|
8
7
|
"""
|
|
9
8
|
|
|
10
9
|
from __future__ import annotations
|
|
@@ -15,9 +14,14 @@ import time
|
|
|
15
14
|
from typing import Callable
|
|
16
15
|
|
|
17
16
|
try:
|
|
18
|
-
from localmodels import
|
|
17
|
+
from localmodels import (
|
|
18
|
+
remote_ops_common,
|
|
19
|
+
remote_ops_launchd,
|
|
20
|
+
remote_ops_prepare,
|
|
21
|
+
remote_ops_service,
|
|
22
|
+
)
|
|
19
23
|
except ImportError: # run as a bare file from this directory
|
|
20
|
-
import
|
|
24
|
+
import remote_ops_common # type: ignore[import-not-found,no-redef]
|
|
21
25
|
import remote_ops_launchd # type: ignore[import-not-found,no-redef]
|
|
22
26
|
import remote_ops_prepare # type: ignore[import-not-found,no-redef]
|
|
23
27
|
import remote_ops_service # type: ignore[import-not-found,no-redef]
|
|
@@ -26,10 +30,10 @@ except ImportError: # run as a bare file from this directory
|
|
|
26
30
|
RELEASE_WAIT_S = 30.0
|
|
27
31
|
|
|
28
32
|
|
|
29
|
-
def _purgeable(p:
|
|
33
|
+
def _purgeable(p: remote_ops_common.RemoveParams, preparation: list[str]) -> list[list[object]]:
|
|
30
34
|
"""[path, bytes, links] for every file in the deployment directory and the model files named."""
|
|
31
|
-
found = [
|
|
32
|
-
for root, _, names in os.walk(
|
|
35
|
+
found = [remote_ops_common.expand(f) for f in p.get("purge_files") or []] + preparation
|
|
36
|
+
for root, _, names in os.walk(remote_ops_common.expand(p["deploy_dir"])):
|
|
33
37
|
found += [os.path.join(root, n) for n in names]
|
|
34
38
|
stats = [(f, os.lstat(f)) for f in sorted(set(found)) if os.path.lexists(f)]
|
|
35
39
|
return [[f, st.st_size, st.st_nlink] for f, st in stats if not os.path.isdir(f)]
|
|
@@ -66,7 +70,7 @@ def _delete(path: str, remove: Callable[[str], None] = os.remove) -> None:
|
|
|
66
70
|
time.sleep(0.25)
|
|
67
71
|
|
|
68
72
|
|
|
69
|
-
def act_remove(p:
|
|
73
|
+
def act_remove(p: remote_ops_common.RemoveParams) -> None:
|
|
70
74
|
"""Stop and delete the service and config files, and the slice once no unit uses it; logs,
|
|
71
75
|
weights and engines stay. ``dry_run`` lists a purge; ``purge`` deletes approved files."""
|
|
72
76
|
purging = p.get("dry_run") or p.get("purge")
|
|
@@ -77,48 +81,52 @@ def act_remove(p: remote_ops.RemoveParams) -> None:
|
|
|
77
81
|
_remove(p, preparation)
|
|
78
82
|
|
|
79
83
|
|
|
80
|
-
def _remove(p:
|
|
84
|
+
def _remove(p: remote_ops_common.RemoveParams, preparation: list[str]) -> None:
|
|
81
85
|
listed = _purgeable(p, preparation) if p.get("dry_run") or p.get("purge") else []
|
|
82
86
|
if p.get("dry_run"):
|
|
83
|
-
|
|
87
|
+
remote_ops_common.emit("result", files=listed, bytes=sum(int(str(f[1])) for f in listed))
|
|
84
88
|
return
|
|
85
|
-
paths =
|
|
89
|
+
paths = remote_ops_common.paths(p)
|
|
86
90
|
systemd = p["service_kind"] == "systemd-user"
|
|
87
91
|
theirs = systemd and remote_ops_service.unit_runs_elsewhere(paths)
|
|
88
92
|
if theirs: # a same-named unit of another install: its service and file stay
|
|
89
|
-
|
|
93
|
+
remote_ops_common.emit(
|
|
94
|
+
"log", message=f"kept {p['service']}.service: it runs another deployment"
|
|
95
|
+
)
|
|
90
96
|
else:
|
|
91
|
-
|
|
97
|
+
remote_ops_service.act_stop(p)
|
|
92
98
|
if p["service_kind"] == "launchd-user":
|
|
93
99
|
plist, _ = remote_ops_launchd.identity(p["deploy_dir"])
|
|
94
100
|
if plist.exists():
|
|
95
101
|
plist.unlink()
|
|
96
102
|
if systemd and not theirs and os.path.exists(paths["unit"]):
|
|
97
|
-
|
|
103
|
+
remote_ops_common.systemctl("disable", p["service"] + ".service")
|
|
98
104
|
part = "".join(
|
|
99
|
-
ln[6:]
|
|
105
|
+
ln[6:]
|
|
106
|
+
for ln in remote_ops_common.read_text(paths["unit"]).splitlines()
|
|
107
|
+
if ln[:6] == "Slice="
|
|
100
108
|
)
|
|
101
109
|
os.remove(paths["unit"])
|
|
102
110
|
units = os.path.dirname(paths["unit"])
|
|
103
111
|
rest = [
|
|
104
|
-
|
|
112
|
+
remote_ops_common.read_text(os.path.join(units, n))
|
|
105
113
|
for n in os.listdir(units)
|
|
106
114
|
if n.endswith(".service")
|
|
107
115
|
]
|
|
108
116
|
suite = os.path.join(units, part)
|
|
109
117
|
if part and os.path.isfile(suite) and not any(f"Slice={part}\n" in t for t in rest):
|
|
110
|
-
if "Description=localmodels suite" in
|
|
118
|
+
if "Description=localmodels suite" in remote_ops_common.read_text(
|
|
111
119
|
suite
|
|
112
120
|
): # the slice _write_slice wrote
|
|
113
121
|
os.remove(suite)
|
|
114
|
-
|
|
122
|
+
remote_ops_common.systemctl("daemon-reload")
|
|
115
123
|
for path in [
|
|
116
124
|
*(paths[k] for k in ("script", "pid", "spec", "key")),
|
|
117
125
|
paths["pid"] + ".identity.json",
|
|
118
126
|
*p.get("config_files", []),
|
|
119
127
|
]:
|
|
120
|
-
if os.path.exists(
|
|
121
|
-
_delete(
|
|
128
|
+
if os.path.exists(remote_ops_common.expand(path)):
|
|
129
|
+
_delete(remote_ops_common.expand(path))
|
|
122
130
|
_delete_prompt_caches(paths["root"])
|
|
123
131
|
approved = set(p.get("purge") or []) & {str(f[0]) for f in listed}
|
|
124
132
|
for path in approved:
|
|
@@ -128,4 +136,4 @@ def _remove(p: remote_ops.RemoveParams, preparation: list[str]) -> None:
|
|
|
128
136
|
if not os.listdir(root):
|
|
129
137
|
_delete(root, os.rmdir)
|
|
130
138
|
kept = [paths["log"]] if os.path.exists(paths["log"]) else []
|
|
131
|
-
|
|
139
|
+
remote_ops_common.emit("result", removed=True, purged=len(approved), kept=kept)
|