The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(proxy): judge Sec-Fetch-Site and compare Origin by host and port
John Paul Solivac30ec25ec729
diff --git a/hermes_cli/proxy/server.py b/hermes_cli/proxy/server.pyindex 21d103b0235..9035e9900af 100644--- a/hermes_cli/proxy/server.py+++ b/hermes_cli/proxy/server.py@@ -59,17 +59,26 @@ _LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})_WILDCARD_HOSTS = frozenset({"", "0.0.0.0", "::"})-def _authority_hostname(authority: str) -> str:- """Lowercased hostname of a Host-header authority; ``""`` when malformed (fails closed)."""+def _canonical_host(host: str) -> str:+ # ``localhost.`` is the absolute form of ``localhost``, and ``[0:0::1]`` is ``[::1]``;+ # a rebound name stays foreign either way.+ host = host.lower().rstrip(".")+ try:+ return ipaddress.ip_address(host).compressed+ except ValueError:+ return host+++def _parse_authority(authority: str) -> Optional[tuple[str, int]]:+ """(hostname, port) of a Host header or Origin authority; None when malformed (fails closed)."""if not authority or any(c in authority for c in "@/\\?# \t"):- return ""+ return Nonetry:parts = urlsplit("//" + authority)- parts.port # noqa: B018 — raises ValueError on a malformed port+ port = parts.port or 80 # an Origin omits the default port that a Host may spell outexcept ValueError:- return ""- # ``localhost.`` is the absolute form of ``localhost``; a rebound name stays foreign either way.- return (parts.hostname or "").lower().rstrip(".")+ return None+ return (_canonical_host(parts.hostname), port) if parts.hostname else Nonedef _is_wildcard(bound: str) -> bool:@@ -79,20 +88,28 @@ def _is_wildcard(bound: str) -> bool:return False-def _local_request_error(host_header: str, origin: Optional[str], bound_host: str) -> Optional[str]:+def _local_request_error(+ host_header: str, origin: Optional[str], bound_host: str, fetch_site: Optional[str] = None+) -> Optional[str]:"""Why a request must be refused, or None. The proxy attaches the operator's subscriptioncredential to whatever reaches it, so a web page in the operator's browser must not be ableto drive it: a loopback/specific-IP bind accepts only its own Host names (a DNS-reboundhostname fails), and any Origin other than the proxy's own is a cross-site browser request.- Non-browser clients send no Origin and are unaffected. A wildcard bind is an explicit LAN- opt-in, so any Host name may reach it; it therefore has no origin of its own to match, and a- DNS-rebound page's Origin always equals its Host, so every Origin-bearing request is refused."""- hostname = _authority_hostname(host_header)- bound = bound_host.strip("[]").lower()+ Browsers omit Origin on GET, but they always send ``Sec-Fetch-Site``, which a page cannot+ forge, so it is judged too. Non-browser clients send neither and are unaffected. A wildcard+ bind is an explicit LAN opt-in, so any Host name may reach it; it therefore has no origin of+ its own to match, and a DNS-rebound page is same-origin with its Host, so every page-made+ browser request is refused there."""+ target = _parse_authority(host_header)+ bound = _canonical_host(bound_host.strip("[]"))wildcard = _is_wildcard(bound)- if not hostname or (not wildcard and hostname not in _LOOPBACK_HOSTS | {bound}):+ if target is None or (not wildcard and target[0] not in _LOOPBACK_HOSTS | {bound}):return "host_not_allowed"- if origin is not None and (wildcard or origin.strip().lower() != f"http://{host_header.strip().lower()}"):+ if origin is not None:+ scheme, sep, rest = origin.strip().partition("://")+ if wildcard or not sep or scheme.lower() != "http" or _parse_authority(rest) != target:+ return "origin_not_allowed"+ if fetch_site is not None and fetch_site.strip().lower() not in ({"none"} if wildcard else {"none", "same-origin"}):return "origin_not_allowed"return None@@ -179,7 +196,12 @@ def create_app(adapter: UpstreamAdapter, bound_host: str = DEFAULT_HOST) -> "web@web.middlewareasync def local_only(request: "web.Request", handler):- refusal = _local_request_error(request.headers.get("Host", ""), request.headers.get("Origin"), bound_host)+ refusal = _local_request_error(+ request.headers.get("Host", ""),+ request.headers.get("Origin"),+ bound_host,+ request.headers.get("Sec-Fetch-Site"),+ )if refusal:return _json_error(403, "Request refused: only local, non-browser clients may use this proxy.", code=refusal)return await handler(request)diff --git a/tests/hermes_cli/test_proxy.py b/tests/hermes_cli/test_proxy.pyindex b55798e69cd..30eb81b0db5 100644--- a/tests/hermes_cli/test_proxy.py+++ b/tests/hermes_cli/test_proxy.py@@ -373,9 +373,13 @@ def test_server_strips_client_auth_header():("127.0.0.1", {"Host": "rebound.example:{port}"}, False), # foreign Host("127.0.0.1", {"Origin": "https://site.example"}, False), # cross-site browser request("127.0.0.1", {"Origin": "null"}, False), # opaque browser origin+ ("127.0.0.1", {"Host": "localhost:80", "Origin": "http://localhost"}, True), # Origin omits :80+ ("127.0.0.1", {"Sec-Fetch-Site": "cross-site"}, False), # cross-site GET, no Origin("0.0.0.0", {"Host": "lan-name.example:{port}"}, True), # LAN API client, no Origin("0.0.0.0", {"Host": "rebound.example:{port}", # DNS-rebound page: its"Origin": "http://rebound.example:{port}"}, False), # Origin equals its Host+ ("0.0.0.0", {"Host": "rebound.example:{port}", # ...and its same-origin+ "Sec-Fetch-Site": "same-origin"}, False), # GET carries no Origin("::", {"Host": "rebound.example:{port}","Origin": "http://rebound.example:{port}"}, False),])diff --git a/website/docs/user-guide/features/subscription-proxy.md b/website/docs/user-guide/features/subscription-proxy.mdindex 535a3b4fe27..666969772bc 100644--- a/website/docs/user-guide/features/subscription-proxy.md+++ b/website/docs/user-guide/features/subscription-proxy.md@@ -163,9 +163,10 @@ OpenAI-compatible client.By default the proxy binds `127.0.0.1` (localhost only). It refuses requestswhose `Host` header is not its own address (`localhost`, `127.0.0.1`, `[::1]`-or the bound IP) and any request carrying a browser `Origin` other than its-own, so a web page open in your browser cannot use it. Clients such as SDKs-and `curl` send no `Origin` and are unaffected. To let other machines on your+or the bound IP) and any browser request from another site (an `Origin` other+than its own, or a `Sec-Fetch-Site` of `cross-site`/`same-site`), so a web page+open in your browser cannot use it. Clients such as SDKs and `curl` send+neither header and are unaffected. To let other machines on yournetwork use it:```bash@@ -174,8 +175,8 @@ hermes proxy start --host 0.0.0.0 --port 8645⚠ **Be aware:** anyone on your network can now use your Portalsubscription. A wildcard bind skips the `Host` check (any name may reach it),-so it refuses every request that carries a browser `Origin`: browsers cannot use-a wildcard-bound proxy at all. The proxy has no auth of its own — it accepts any bearer.+so it refuses every request a web page makes (any `Origin`, or a+`Sec-Fetch-Site` other than `none`): browsers cannot use a wildcard-bound proxy. The proxy has no auth of its own — it accepts any bearer.Use a firewall, VPN, or reverse proxy with proper auth if you exposethis beyond your trusted network.diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/subscription-proxy.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/subscription-proxy.mdindex 7c8f480707d..9ff0f0ebf1f 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/subscription-proxy.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/subscription-proxy.md@@ -135,13 +135,13 @@ INFERENCE_TEXT_MODEL=Hermes-4-70B## 在局域网上暴露-默认情况下,代理绑定 `127.0.0.1`(仅限本机)。它会拒绝 `Host` 头不是其自身地址(`localhost`、`127.0.0.1`、`[::1]` 或所绑定的 IP)的请求,也会拒绝带有非其自身浏览器 `Origin` 的请求,因此你浏览器中打开的网页无法使用它。SDK、`curl` 等客户端不发送 `Origin`,不受影响。若要让网络中的其他机器使用:+默认情况下,代理绑定 `127.0.0.1`(仅限本机)。它会拒绝 `Host` 头不是其自身地址(`localhost`、`127.0.0.1`、`[::1]` 或所绑定的 IP)的请求,也会拒绝来自其他站点的浏览器请求(`Origin` 不是其自身,或 `Sec-Fetch-Site` 为 `cross-site`/`same-site`),因此你浏览器中打开的网页无法使用它。SDK、`curl` 等客户端不发送这两个头,不受影响。若要让网络中的其他机器使用:```bashhermes proxy start --host 0.0.0.0 --port 8645```-⚠ **注意:** 你网络中的任何人现在都可以使用你的 Portal 订阅。通配符绑定会跳过 `Host` 检查(任何主机名都可以访问),因此它会拒绝所有带有浏览器 `Origin` 的请求:浏览器完全无法使用以通配符绑定的代理。代理本身没有认证机制——它接受任意 bearer。如果你将其暴露在可信网络之外,请使用防火墙、VPN 或带有适当认证的反向代理。+⚠ **注意:** 你网络中的任何人现在都可以使用你的 Portal 订阅。通配符绑定会跳过 `Host` 检查(任何主机名都可以访问),因此它会拒绝网页发出的所有请求(任何 `Origin`,或 `Sec-Fetch-Site` 不是 `none`):浏览器无法使用以通配符绑定的代理。代理本身没有认证机制——它接受任意 bearer。如果你将其暴露在可信网络之外,请使用防火墙、VPN 或带有适当认证的反向代理。## 速率限制