Skip to content

The agent that grows with you

test(e2e/network): hostile-network install/update suite under a private netns

teknium111a84d7d71c5
diff --git a/tests/e2e/core/upgrade/_helpers.py b/tests/e2e/core/upgrade/_helpers.py
index ba0099d8ffe..42b77848545 100644
--- a/tests/e2e/core/upgrade/_helpers.py
+++ b/tests/e2e/core/upgrade/_helpers.py
@@ -139,9 +139,17 @@ def isolated_env(
return env
-def sandbox_argv(argv: Sequence[str], *, writable: Iterable[Path]) -> list[str]:
- """Wrap ``argv`` in the bwrap sandbox (no-op when bubblewrap is unusable)."""
+def sandbox_argv(argv: Sequence[str], *, writable: Iterable[Path], unshare_net: bool = False,
+ ro_binds: Iterable[tuple[Path, Path]] = ()) -> list[str]:
+ """Wrap ``argv`` in the bwrap sandbox (no-op when bubblewrap is unusable).
+
+ Opt-in: ``unshare_net`` gives the sandbox its own network namespace (loopback only; the
+ hostile-network suites bridge their fakes in); ``ro_binds`` are ``(host_path, sandbox_path)``
+ read-only overlays (e.g. a CA bundle over the distro trust store).
+ """
if not BWRAP_OK:
+ if unshare_net:
+ raise RuntimeError("unshare_net requires the bwrap sandbox")
return list(argv)
# The child's allowlisted PATH may omit the Nix-provided bwrap (notably a login shell
# with a clean distro PATH); resolve it in the parent before wrapping the command.
@@ -156,6 +164,10 @@ def sandbox_argv(argv: Sequence[str], *, writable: Iterable[Path]) -> list[str]:
run_user = Path(f"/run/user/{UID}")
if run_user.is_dir():
cmd += ["--tmpfs", str(run_user)]
+ for src, dest in ro_binds:
+ cmd += ["--ro-bind", str(src), str(dest)]
+ if unshare_net:
+ cmd += ["--unshare-net"]
cmd += ["--unshare-pid", "--proc", "/proc", "--die-with-parent", "--"]
return cmd + list(argv)
@@ -168,10 +180,12 @@ def run(
writable: Iterable[Path],
timeout: float = 300,
input: str | None = None,
+ unshare_net: bool = False,
+ ro_binds: Iterable[tuple[Path, Path]] = (),
) -> subprocess.CompletedProcess:
"""Run one sandboxed process to completion; kills the whole sandbox on timeout."""
proc = subprocess.Popen(
- sandbox_argv(argv, writable=writable),
+ sandbox_argv(argv, writable=writable, unshare_net=unshare_net, ro_binds=ro_binds),
env=env, cwd=str(cwd), text=True,
stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
diff --git a/tests/e2e/core/upgrade/network/__init__.py b/tests/e2e/core/upgrade/network/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/e2e/core/upgrade/network/_netedge.py b/tests/e2e/core/upgrade/network/_netedge.py
new file mode 100644
index 00000000000..81884fee6ea
--- /dev/null
+++ b/tests/e2e/core/upgrade/network/_netedge.py
@@ -0,0 +1,577 @@
+"""The network edge for the hostile-network suites: every byte a sandboxed install/update sends
+leaves through something this module owns.
+
+* ``netns_usable()``: the sandbox gets its own network namespace (``bwrap --unshare-net``, only
+ ``lo``), so there is no route, no DNS and no internet. Egress is what the test provides, and a
+ cell that expected "nothing reached pypi.org" is proven by the namespace, not by trust.
+* ``Bridge``: host-side TCP services (the proxy, a fake provider, a mirror) appear inside the
+ namespace on the SAME loopback port. The host listens on a unix socket per port under the test's
+ tmp dir; ``_nsbridge.py`` (the sandbox's first process) listens on ``127.0.0.1:<port>`` in the
+ namespace and relays each connection to that socket.
+* ``EdgeProxy``: an HTTP/HTTPS forward proxy (``CONNECT``) in front of named fake sites. For a
+ routed host it terminates TLS with a leaf signed by the test's own root (a TLS-inspecting
+ corporate proxy) and serves the site's app; every other host is refused with 403 and logged, so
+ a cell can list every host the product tried to reach. Faults per host: ``eof`` (accept the
+ tunnel, then drop it before TLS: the ``UNEXPECTED_EOF`` a cut direct connection shows) and
+ optional proxy auth (407 without the right ``Proxy-Authorization``).
+* Apps: ``git_app`` (git smart-HTTP via ``git http-backend``), ``static_app`` (fixed routes with
+ scripted per-path fault sequences, e.g. 503 + Retry-After then 200).
+"""
+
+from __future__ import annotations
+
+import base64
+import datetime
+import gzip
+import http.server
+import ipaddress
+import os
+import shutil
+import socket
+import socketserver
+import ssl
+import subprocess
+import sys
+import threading
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Callable, Iterable, Iterator, Mapping
+
+from tests.e2e.core.upgrade import _helpers as H
+
+_BRIDGE_SCRIPT = Path(__file__).with_name("_nsbridge.py")
+SYSTEM_CA_BUNDLE = Path("/etc/ssl/certs/ca-certificates.crt")
+
+
+def netns_usable() -> bool:
+ """bwrap can give the sandbox a private network namespace with a working loopback."""
+ if not H.BWRAP_OK:
+ return False
+ probe = "import socket; s = socket.socket(); s.bind(('127.0.0.1', 0)); s.listen(); print('ok')"
+ try:
+ r = subprocess.run(
+ [shutil.which("bwrap") or "bwrap", "--dev-bind", "/", "/", "--unshare-net", "--unshare-pid",
+ "--proc", "/proc", "--die-with-parent", sys.executable, "-I", "-c", probe],
+ capture_output=True, text=True, timeout=30,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return r.returncode == 0 and r.stdout.strip() == "ok"
+
+
+def netns_required_reason() -> str | None:
+ if netns_usable():
+ return None
+ return "bwrap --unshare-net unavailable: the hostile-network cells need a private network namespace"
+
+
+# ---------------------------------------------------------------------------
+# Certificates: one test root, a leaf per routed host.
+# ---------------------------------------------------------------------------
+
+class TestCA:
+ """A throwaway root CA (the "corporate TLS-inspection root") and leaves signed by it."""
+
+ __test__ = False # not a pytest class
+
+ def __init__(self, directory: Path) -> None:
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import ec
+ from cryptography.x509.oid import NameOID
+
+ self._x509, self._hashes, self._ser, self._ec, self._oid = x509, hashes, serialization, ec, NameOID
+ self.dir = directory
+ directory.mkdir(parents=True, exist_ok=True)
+ self._key = ec.generate_private_key(ec.SECP256R1())
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Hermes E2E TLS Inspection Root")])
+ now = datetime.datetime.now(datetime.timezone.utc)
+ self._cert = (
+ x509.CertificateBuilder().subject_name(name).issuer_name(name)
+ .public_key(self._key.public_key()).serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(days=1)).not_valid_after(now + datetime.timedelta(days=30))
+ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
+ .add_extension(x509.KeyUsage(digital_signature=True, key_cert_sign=True, crl_sign=True,
+ content_commitment=False, key_encipherment=False, data_encipherment=False,
+ key_agreement=False, encipher_only=False, decipher_only=False), critical=True)
+ .add_extension(x509.SubjectKeyIdentifier.from_public_key(self._key.public_key()), critical=False)
+ .sign(self._key, hashes.SHA256())
+ )
+ self.pem = self._cert.public_bytes(serialization.Encoding.PEM)
+ self.cert_file = directory / "test-root.pem"
+ self.cert_file.write_bytes(self.pem)
+ self._contexts: dict[str, ssl.SSLContext] = {}
+ self._lock = threading.Lock()
+
+ def os_trust_store(self, dest: Path) -> list[tuple[Path, Path]]:
+ """What ``update-ca-certificates`` leaves after an admin installs this root as the corporate
+ root: ``/etc/ssl/certs`` with the root in ``ca-certificates.crt`` AND as a hashed link.
+ Returns the ``ro_binds`` that overlay it on the sandbox's distro trust store."""
+ certs = Path("/etc/ssl/certs")
+ if dest.exists():
+ shutil.rmtree(dest)
+ shutil.copytree(certs, dest, symlinks=True) if certs.is_dir() else dest.mkdir(parents=True)
+ bundle = dest / "ca-certificates.crt"
+ system = SYSTEM_CA_BUNDLE.read_bytes() if SYSTEM_CA_BUNDLE.is_file() else b""
+ if bundle.is_symlink():
+ bundle.unlink()
+ bundle.write_bytes(system + b"\n" + self.pem)
+ (dest / "hermes-e2e-root.pem").write_bytes(self.pem)
+ openssl = shutil.which("openssl")
+ if openssl:
+ digest = subprocess.run([openssl, "x509", "-hash", "-noout", "-in", str(self.cert_file)],
+ capture_output=True, text=True, check=True).stdout.strip()
+ link = dest / f"{digest}.0"
+ if not link.exists():
+ link.symlink_to("hermes-e2e-root.pem")
+ return [(dest, certs)]
+
+ def server_context(self, host: str) -> ssl.SSLContext:
+ with self._lock:
+ ctx = self._contexts.get(host)
+ if ctx is None:
+ ctx = self._contexts[host] = self._leaf_context(host)
+ return ctx
+
+ def _leaf_context(self, host: str) -> ssl.SSLContext:
+ x509, hashes, ser, ec, oid = self._x509, self._hashes, self._ser, self._ec, self._oid
+ key = ec.generate_private_key(ec.SECP256R1())
+ now = datetime.datetime.now(datetime.timezone.utc)
+ try:
+ san = x509.IPAddress(ipaddress.ip_address(host))
+ except ValueError:
+ san = x509.DNSName(host)
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(x509.Name([x509.NameAttribute(oid.COMMON_NAME, host)]))
+ .issuer_name(self._cert.subject).public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(days=1)).not_valid_after(now + datetime.timedelta(days=7))
+ .add_extension(x509.SubjectAlternativeName([san]), critical=False)
+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
+ .add_extension(x509.ExtendedKeyUsage([x509.oid.ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
+ .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(self._key.public_key()), critical=False)
+ .sign(self._key, hashes.SHA256())
+ )
+ stem = self.dir / f"leaf-{host.replace(':', '_')}"
+ cert_path, key_path = stem.with_suffix(".crt"), stem.with_suffix(".key")
+ cert_path.write_bytes(cert.public_bytes(ser.Encoding.PEM) + self.pem)
+ key_path.write_bytes(key.private_bytes(ser.Encoding.PEM, ser.PrivateFormat.PKCS8, ser.NoEncryption()))
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ ctx.load_cert_chain(str(cert_path), str(key_path))
+ ctx.set_alpn_protocols(["http/1.1"])
+ return ctx
+
+
+# ---------------------------------------------------------------------------
+# Apps: (request) -> Response. A request is what the site saw after TLS termination.
+# ---------------------------------------------------------------------------
+
+@dataclass
+class Request:
+ host: str
+ method: str
+ path: str
+ headers: dict[str, str]
+ body: bytes
+
+
+@dataclass
+class Response:
+ status: int
+ body: bytes | Iterator[bytes] = b""
+ headers: dict[str, str] = field(default_factory=dict)
+
+
+App = Callable[[Request], Response]
+
+
+@dataclass
+class Hit:
+ host: str
+ kind: str # "request" | "refused" | "eof" | "auth-required" | "tls-rejected"
+ method: str = ""
+ path: str = ""
+ status: int = 0
+
+ def __str__(self) -> str:
+ return f"{self.kind} {self.host} {self.method} {self.path} -> {self.status}".strip()
+
+
+def static_app(routes: Mapping[str, bytes | Callable[[Request], Response]], *,
+ faults: dict[str, list[Response]] | None = None,
+ always: dict[str, Response] | None = None) -> App:
+ """Exact-path routes (anything else 404s); a key ending in ``*`` matches every path with that
+ prefix (``{"*": body}`` is a catch-all), checked after the exact routes. ``faults[path]`` is a queue of responses served
+ before the real one, one per request (e.g. ``[Response(503, headers={"Retry-After": "1"})]``);
+ ``always[path]`` replaces the route for every request (an outage that never recovers)."""
+ queues = {k: list(v) for k, v in (faults or {}).items()}
+ lock = threading.Lock()
+
+ def app(req: Request) -> Response:
+ path = req.path.split("?", 1)[0]
+ if always and path in always:
+ return always[path]
+ with lock:
+ queue = queues.get(path) or next(
+ (q for k, q in queues.items() if k.endswith("*") and path.startswith(k[:-1]) and q), None)
+ if queue:
+ return queue.pop(0)
+ route = routes.get(path)
+ if route is None:
+ route = next((r for k, r in routes.items() if k.endswith("*") and path.startswith(k[:-1])), None)
+ if route is None:
+ return Response(404, b"not found\n")
+ if callable(route):
+ return route(req)
+ return Response(200, route, {"Content-Type": "application/octet-stream"})
+
+ return app
+
+
+def git_app(project_root: Path, *, faults: list[Response] | None = None) -> App:
+ """git smart-HTTP (fetch/clone) over ``git http-backend`` for every bare repo under
+ ``project_root`` (``/<Owner>/<repo>.git/...`` maps to ``<project_root>/<Owner>/<repo>.git``).
+ ``faults`` are served first, one per request (a rate-limited or erroring forge)."""
+ git = shutil.which("git") or "git"
+ queue = list(faults or [])
+ lock = threading.Lock()
+
+ def app(req: Request) -> Response:
+ with lock:
+ if queue:
+ return queue.pop(0)
+ path, _, query = req.path.partition("?")
+ body = req.body
+ env = {
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
+ "GIT_PROJECT_ROOT": str(project_root), "GIT_HTTP_EXPORT_ALL": "1",
+ "PATH_INFO": path, "QUERY_STRING": query, "REQUEST_METHOD": req.method,
+ "CONTENT_TYPE": req.headers.get("content-type", ""), "CONTENT_LENGTH": str(len(body)),
+ "GIT_PROTOCOL": req.headers.get("git-protocol", ""), "REMOTE_ADDR": "127.0.0.1",
+ "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(project_root),
+ }
+ if req.headers.get("content-encoding", "").lower() == "gzip":
+ body = gzip.decompress(body)
+ cp = subprocess.run([git, "http-backend"], input=body, env=env, capture_output=True, timeout=300)
+ head, _, payload = cp.stdout.partition(b"\r\n\r\n")
+ if not _:
+ head, _, payload = cp.stdout.partition(b"\n\n")
+ status, headers = 200, {}
+ for line in head.decode("latin-1").splitlines():
+ if ":" not in line:
+ continue
+ k, v = line.split(":", 1)
+ if k.lower() == "status":
+ status = int(v.strip().split()[0])
+ else:
+ headers[k.strip()] = v.strip()
+ if cp.returncode != 0 and status == 200:
+ status = 500
+ return Response(status, payload, headers)
+
+ return app
+
+
+# ---------------------------------------------------------------------------
+# Serving an app on a socket (TLS-terminated tunnel or plain HTTP).
+# ---------------------------------------------------------------------------
+
+class _SiteHandler(http.server.BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+ app: App
+ site_host: str
+ hits: list[Hit]
+
+ def log_message(self, format, *args) -> None: # noqa: A002 - quiet
+ pass
+
+ def _read_body(self) -> bytes:
+ if self.headers.get("Transfer-Encoding", "").lower() == "chunked":
+ chunks = []
+ while True:
+ size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)
+ if size == 0:
+ while self.rfile.readline() not in (b"\r\n", b"\n", b""):
+ pass
+ return b"".join(chunks)
+ chunks.append(self.rfile.read(size))
+ self.rfile.readline()
+ n = int(self.headers.get("Content-Length") or 0)
+ return self.rfile.read(n) if n else b""
+
+ def _dispatch(self) -> None:
+ path = self.path
+ if path.startswith(("http://", "https://")): # absolute-form through a plain proxy
+ path = "/" + path.split("://", 1)[1].partition("/")[2]
+ req = Request(self.site_host, self.command, path,
+ {k.lower(): v for k, v in self.headers.items()}, self._read_body())
+ try:
+ resp = self.app(req)
+ except Exception as exc: # a broken fake must be visible, not a hang
+ resp = Response(500, f"fake site error: {exc!r}\n".encode())
+ self.hits.append(Hit(self.site_host, "request", self.command, path, resp.status))
+ self.send_response(resp.status)
+ for k, v in resp.headers.items():
+ if k.lower() not in ("content-length", "transfer-encoding", "connection"):
+ self.send_header(k, v)
+ if isinstance(resp.body, bytes):
+ self.send_header("Content-Length", str(len(resp.body)))
+ self.end_headers()
+ if self.command != "HEAD":
+ self.wfile.write(resp.body)
+ else:
+ self.send_header("Connection", "close")
+ self.end_headers()
+ for chunk in resp.body:
+ self.wfile.write(chunk)
+ self.close_connection = True
+
+ do_GET = do_POST = do_HEAD = do_PUT = _dispatch
+
+
+def _serve_app(sock: socket.socket, addr, host: str, app: App, hits: list[Hit]) -> None:
+ handler = type("SiteHandler", (_SiteHandler,), {"app": staticmethod(app), "site_host": host, "hits": hits})
+ try:
+ handler(sock, addr, None) # type: ignore[arg-type]
+ except (OSError, ssl.SSLError):
+ pass
+
+
+class HttpSite:
+ """A plain-HTTP server for one app on 127.0.0.1 (a mirror reached without the proxy)."""
+
+ def __init__(self, app: App, name: str = "127.0.0.1") -> None:
+ self.hits: list[Hit] = []
+ self.name = name
+ outer = self
+
+ class _S(socketserver.ThreadingTCPServer):
+ daemon_threads = True
+ allow_reuse_address = True
+
+ def finish_request(self, request, client_address):
+ _serve_app(request, client_address, outer.name, app, outer.hits) # type: ignore[arg-type]
+
+ self._srv = _S(("127.0.0.1", 0), socketserver.BaseRequestHandler)
+ self.port = self._srv.server_address[1]
+ self.url = f"http://127.0.0.1:{self.port}"
+ threading.Thread(target=self._srv.serve_forever, daemon=True).start()
+
+ def close(self) -> None:
+ self._srv.shutdown()
+ self._srv.server_close()
+
+
+class EdgeProxy:
+ """HTTP(S) forward proxy with TLS inspection for routed hosts; refuses (and logs) the rest."""
+
+ def __init__(self, ca: TestCA, routes: dict[str, App] | None = None, *,
+ eof_hosts: Iterable[str] = (), auth: tuple[str, str] | None = None) -> None:
+ self.ca = ca
+ self.routes: dict[str, App] = dict(routes or {})
+ self.eof_hosts = set(eof_hosts)
+ self.auth = auth
+ self.hits: list[Hit] = []
+ outer = self
+
+ class _S(socketserver.ThreadingTCPServer):
+ daemon_threads = True
+ allow_reuse_address = True
+ request_queue_size = 128
+
+ def finish_request(self, request, client_address):
+ outer._handle(request, client_address) # type: ignore[arg-type]
+
+ self._srv = _S(("127.0.0.1", 0), socketserver.BaseRequestHandler)
+ self.port = self._srv.server_address[1]
+ self.url = f"http://127.0.0.1:{self.port}"
+ threading.Thread(target=self._srv.serve_forever, daemon=True).start()
+
+ def url_with_auth(self) -> str:
+ assert self.auth is not None
+ return f"http://{self.auth[0]}:{self.auth[1]}@127.0.0.1:{self.port}"
+
+ def close(self) -> None:
+ self._srv.shutdown()
+ self._srv.server_close()
+
+ # -- queries ------------------------------------------------------------
+ def hosts(self, kind: str | None = None) -> set[str]:
+ return {h.host for h in list(self.hits) if kind is None or h.kind == kind}
+
+ def requests(self, host: str) -> list[Hit]:
+ return [h for h in list(self.hits) if h.host == host and h.kind == "request"]
+
+ def transcript(self, limit: int = 60) -> str:
+ rows = [str(h) for h in list(self.hits)]
+ return "\n".join(rows[-limit:]) or "(proxy saw no traffic)"
+
+ # -- protocol -----------------------------------------------------------
+ def _authorized(self, headers: dict[str, str]) -> bool:
+ if self.auth is None:
+ return True
+ want = "Basic " + base64.b64encode(f"{self.auth[0]}:{self.auth[1]}".encode()).decode()
+ return headers.get("proxy-authorization", "") == want
+
+ def _handle(self, sock: socket.socket, addr) -> None:
+ try:
+ sock.settimeout(120)
+ rfile = sock.makefile("rb")
+ line = rfile.readline(65536).decode("latin-1").strip()
+ if not line:
+ return
+ headers: dict[str, str] = {}
+ while True:
+ h = rfile.readline(65536).decode("latin-1")
+ if h in ("\r\n", "\n", ""):
+ break
+ k, _, v = h.partition(":")
+ headers[k.strip().lower()] = v.strip()
+ method, target, _ = (line.split(" ", 2) + ["", ""])[:3]
+ if method == "CONNECT":
+ host = target.rsplit(":", 1)[0].strip("[]")
+ else:
+ host = target.split("://", 1)[-1].split("/", 1)[0].rsplit(":", 1)[0]
+ if not self._authorized(headers):
+ self.hits.append(Hit(host, "auth-required", method, target, 407))
+ sock.sendall(b"HTTP/1.1 407 Proxy Authentication Required\r\n"
+ b"Proxy-Authenticate: Basic realm=\"corp\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+ return
+ if host in self.eof_hosts:
+ self.hits.append(Hit(host, "eof", method, target, 0))
+ if method == "CONNECT":
+ sock.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
+ return # drop the tunnel before any TLS bytes: UNEXPECTED_EOF at the client
+ app = self.routes.get(host)
+ if app is None:
+ self.hits.append(Hit(host, "refused", method, target, 403))
+ sock.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+ return
+ if method != "CONNECT":
+ # Every fake site is HTTPS; a plain-HTTP request through the proxy is a product
+ # talking cleartext to a host that should be TLS. Refuse it visibly.
+ self.hits.append(Hit(host, "refused", method, target, 403))
+ sock.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+ return
+ sock.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
+ try:
+ tls = self.ca.server_context(host).wrap_socket(sock, server_side=True)
+ except (OSError, ssl.SSLError) as exc:
+ # The client rejected the inspected certificate (or hung up): its trust store
+ # does not hold the corporate root.
+ self.hits.append(Hit(host, "tls-rejected", method, str(exc)[:120], 0))
+ return
+ _serve_app(tls, addr, host, app, self.hits)
+ except (OSError, ssl.SSLError, ValueError):
+ pass
+ finally:
+ try:
+ sock.close()
+ except OSError:
+ pass
+
+
+# ---------------------------------------------------------------------------
+# Bridge: host TCP services -> the sandbox's private loopback, same port numbers.
+# ---------------------------------------------------------------------------
+
+class Bridge:
+ """Expose host ``127.0.0.1:<port>`` services inside the sandbox namespace at the same port."""
+
+ def __init__(self, directory: Path, ports: Iterable[int]) -> None:
+ self.dir = directory
+ directory.mkdir(parents=True, exist_ok=True)
+ self.ports = sorted(set(ports))
+ # Unix socket paths are capped at 108 bytes; pytest tmp paths are longer. Bind through a
+ # held directory fd (``/proc/self/fd/N/<port>``) on both sides.
+ self._dirfd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
+ self._servers: list[socket.socket] = []
+ self._stop = threading.Event()
+ for port in self.ports:
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s.bind(f"/proc/self/fd/{self._dirfd}/{port}")
+ s.listen(128)
+ self._servers.append(s)
+ threading.Thread(target=self._accept, args=(s, port), daemon=True).start()
+
+ def _accept(self, server: socket.socket, port: int) -> None:
+ while not self._stop.is_set():
+ try:
+ client, _ = server.accept()
+ except OSError:
+ return
+ threading.Thread(target=self._relay, args=(client, port), daemon=True).start()
+
+ @staticmethod
+ def _relay(client: socket.socket, port: int) -> None:
+ try:
+ upstream = socket.create_connection(("127.0.0.1", port), timeout=30)
+ except OSError:
+ client.close()
+ return
+ upstream.settimeout(None)
+ _pipe_pair(client, upstream)
+
+ def wrap(self, argv: list[str]) -> list[str]:
+ """``argv`` preceded by the in-namespace relay (exits with argv's status)."""
+ spec = ",".join(str(p) for p in self.ports)
+ return [sys.executable, "-I", str(_BRIDGE_SCRIPT), str(self.dir), spec, "--", *argv]
+
+ def close(self) -> None:
+ self._stop.set()
+ for s in self._servers:
+ try:
+ s.close()
+ except OSError:
+ pass
+ try:
+ os.close(self._dirfd)
+ except OSError:
+ pass
+
+
+def _pipe_pair(a: socket.socket, b: socket.socket) -> None:
+ def pump(src: socket.socket, dst: socket.socket) -> None:
+ try:
+ while True:
+ data = src.recv(65536)
+ if not data:
+ break
+ dst.sendall(data)
+ except OSError:
+ pass
+ finally:
+ try:
+ dst.shutdown(socket.SHUT_WR)
+ except OSError:
+ pass
+
+ t = threading.Thread(target=pump, args=(b, a), daemon=True)
+ t.start()
+ pump(a, b)
+ t.join(timeout=600)
+ for s in (a, b):
+ try:
+ s.close()
+ except OSError:
+ pass
+
+
+def proxy_env(proxy_url: str, *, no_proxy: str = "127.0.0.1,localhost,::1") -> dict[str, str]:
+ """Every spelling of the proxy variables that curl, git, uv, npm, node and Python read."""
+ return {
+ "HTTPS_PROXY": proxy_url, "https_proxy": proxy_url,
+ "HTTP_PROXY": proxy_url, "http_proxy": proxy_url,
+ "NO_PROXY": no_proxy, "no_proxy": no_proxy,
+ }
+
+
+def wait_port_free(port: int, timeout: float = 5.0) -> None: # pragma: no cover - diagnostics helper
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ with socket.socket() as s:
+ if s.connect_ex(("127.0.0.1", port)) != 0:
+ return
+ time.sleep(0.1)
diff --git a/tests/e2e/core/upgrade/network/_nsbridge.py b/tests/e2e/core/upgrade/network/_nsbridge.py
new file mode 100644
index 00000000000..5f6c05a4482
--- /dev/null
+++ b/tests/e2e/core/upgrade/network/_nsbridge.py
@@ -0,0 +1,75 @@
+"""First process inside the sandbox's private network namespace (run with ``python -I``).
+
+``_nsbridge.py <socket-dir> <port,port,...> -- <argv...>``: listen on ``127.0.0.1:<port>`` for
+each port, relay every connection to the host's unix socket ``<socket-dir>/<port>``, run argv,
+and exit with its status. Stdlib only; it must not import anything from the checkout.
+"""
+
+import os
+import socket
+import subprocess
+import sys
+import threading
+
+
+def _pump(src, dst):
+ try:
+ while True:
+ data = src.recv(65536)
+ if not data:
+ break
+ dst.sendall(data)
+ except OSError:
+ pass
+ finally:
+ try:
+ dst.shutdown(socket.SHUT_WR)
+ except OSError:
+ pass
+
+
+def _relay(client, path):
+ upstream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ try:
+ upstream.connect(path)
+ except OSError:
+ client.close()
+ upstream.close()
+ return
+ t = threading.Thread(target=_pump, args=(upstream, client), daemon=True)
+ t.start()
+ _pump(client, upstream)
+ t.join(600)
+ client.close()
+ upstream.close()
+
+
+def _serve(listener, path):
+ while True:
+ try:
+ client, _ = listener.accept()
+ except OSError:
+ return
+ threading.Thread(target=_relay, args=(client, path), daemon=True).start()
+
+
+def main():
+ sock_dir, ports, sep, *argv = sys.argv[1:]
+ assert sep == "--" and argv, "usage: _nsbridge.py <dir> <ports> -- argv"
+ dirfd = os.open(sock_dir, os.O_RDONLY | os.O_DIRECTORY)
+ for port in filter(None, ports.split(",")):
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ listener.bind(("127.0.0.1", int(port)))
+ listener.listen(128)
+ threading.Thread(target=_serve, args=(listener, f"/proc/self/fd/{dirfd}/{port}"), daemon=True).start()
+ proc = subprocess.Popen(argv, pass_fds=())
+ try:
+ sys.exit(proc.wait())
+ except KeyboardInterrupt:
+ proc.terminate()
+ sys.exit(proc.wait())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/e2e/core/upgrade/network/_seed.py b/tests/e2e/core/upgrade/network/_seed.py
new file mode 100644
index 00000000000..1a309e78a70
--- /dev/null
+++ b/tests/e2e/core/upgrade/network/_seed.py
@@ -0,0 +1,363 @@
+"""One real install per module, then every cell runs inside a private network namespace.
+
+``seed_install`` runs HEAD's ``scripts/install.sh`` into an empty fake HOME the way
+``test_install_fresh`` does, with the clone rewritten to a local bare origin and on the host
+network, because the installer provisions ~100 MB of pinned upstream artifacts (Python, Node,
+ffmpeg, ...) that no fixture may fake. The install is HEAD, so the updater under test is HEAD's
+own; each cell then publishes a NEW upstream commit (or a new release record), so the update is
+a real fetch, checkout and rebuild, never the "already current" branch.
+
+After the seed the sandbox loses the ``insteadOf`` rewrite: the checkout's origin is the official
+``https://github.com/NousResearch/hermes-agent.git`` again, and inside the namespace the only way
+to reach it is the test's proxy, which routes ``github.com`` to a git smart-HTTP server over the
+same bare origin. The partial clone (``--filter=tree:0``) makes every lazy tree/blob fetch of the
+checkout cross that proxy too.
+
+``Installed.run(..., edge=...)`` runs one command under ``bwrap --unshare-net``: no route, no
+DNS, only the edge's proxy (and optional plain-HTTP mirrors) bridged onto the namespace's
+loopback. The module fixture proves that isolation before any cell runs.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import hashlib
+import json
+import re
+import shutil
+import subprocess
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Iterable, Iterator
+
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.network import _netedge as N
+
+ASSETS = "hermes-assets.nousresearch.com"
+REPOSITORY = "NousResearch/hermes-agent"
+# Hosts a correctly isolated update must never reach directly; with the proxy they appear in
+# the proxy log as "refused" (the proxy has no route for them).
+PUBLIC_INDEXES = ("pypi.org", "files.pythonhosted.org", "registry.npmjs.org")
+
+
+@dataclass
+class Result:
+ cp: subprocess.CompletedProcess
+ secs: float
+ edge: "Edge | None"
+
+ @property
+ def rc(self) -> int:
+ return self.cp.returncode
+
+ @property
+ def out(self) -> str:
+ return (self.cp.stdout or "") + (self.cp.stderr or "")
+
+ def report(self, inst: "Installed", *extra: str) -> str:
+ parts = [f"exit={self.rc} after {self.secs:.1f}s", I.describe(self.cp)]
+ if self.edge is not None:
+ parts.append("--- network edge log ---\n" + self.edge.transcript())
+ parts.append("--- install state ---\n" + json.dumps(inst.state(), indent=1))
+ parts.append(inst.logs_tail())
+ parts.extend(extra)
+ return "\n".join(parts)
+
+
+@dataclass
+class Edge:
+ """The namespace's only egress: a TLS-inspecting proxy plus optional plain-HTTP mirrors."""
+
+ inst: "Installed"
+ proxy: N.EdgeProxy
+ sites: list[N.HttpSite] = field(default_factory=list)
+ use_auth: bool = False
+
+ @property
+ def ports(self) -> list[int]:
+ return [self.proxy.port, *(s.port for s in self.sites)]
+
+ def env(self) -> dict[str, str]:
+ return N.proxy_env(self.proxy.url_with_auth() if self.use_auth else self.proxy.url)
+
+ def transcript(self) -> str:
+ rows = [self.proxy.transcript(80)]
+ for site in self.sites:
+ rows.append(f"[mirror {site.url}] " + (", ".join(str(h) for h in site.hits[-40:]) or "(no requests)"))
+ return "\n".join(rows)
+
+ def close(self) -> None:
+ self.proxy.close()
+ for site in self.sites:
+ site.close()
+
+
+@dataclass
+class Installed:
+ root: Path
+ sb: I.Sandbox
+ origin: Path
+ gitroot: Path
+ ca: N.TestCA
+ trust: list[tuple[Path, Path]]
+ _n: int = 0
+
+ # -- upstream --------------------------------------------------------------
+ def head(self) -> str:
+ return I.git("rev-parse", "HEAD", cwd=self.sb.checkout)
+
+ def publish(self, tag: str, files: dict[str, str] | None = None) -> str:
+ """A new upstream commit on origin/main, directly on top of what is installed."""
+ self._n += 1
+ I.git("update-ref", "refs/heads/main", self.head(), cwd=self.origin)
+ files = files or {f"E2E_NETWORK_{tag}.txt": f"{tag} {time.time_ns()}\n"}
+ return I.publish_commit(self.origin, self.root, f"e2e network: {tag} #{self._n}", files)
+
+ # -- edges -----------------------------------------------------------------
+ def edge(self, *, assets: N.App | None = None, git: N.App | None = None,
+ extra: dict[str, N.App] | None = None, sites: Iterable[N.HttpSite] = (),
+ eof_hosts: Iterable[str] = (), auth: tuple[str, str] | None = None) -> Edge:
+ """Proxy routes: the release-channel host (default: no records published, so ``main``
+ follows the branch), github.com (default: the git server over the bare origin)."""
+ routes = {ASSETS: assets or N.static_app({}), "github.com": git or N.git_app(self.gitroot)}
+ routes.update(extra or {})
+ for host in eof_hosts:
+ routes.pop(host, None)
+ proxy = N.EdgeProxy(self.ca, routes, eof_hosts=eof_hosts, auth=auth)
+ return Edge(self, proxy, list(sites), use_auth=auth is not None)
+
+ # -- running -----------------------------------------------------------------
+ def run(self, argv: list[str], *, edge: Edge | None, env: dict[str, str] | None = None,
+ corporate_root: bool = True, timeout: float = 900) -> Result:
+ """``argv`` inside the sandbox with its own network namespace. ``edge=None`` is fully
+ offline. ``corporate_root`` overlays the distro trust store with one that also trusts
+ the proxy's root (what an admin's ``update-ca-certificates`` leaves behind)."""
+ e = dict(self.sb.env)
+ if edge is not None:
+ e.update(edge.env())
+ e.update(env or {})
+ bridge = N.Bridge(self.root / "bridges" / f"b{time.time_ns()}", edge.ports if edge else [])
+ t0 = time.monotonic()
+ try:
+ cp = H.run(bridge.wrap(argv), env=e, cwd=self.sb.root, writable=[self.sb.root],
+ timeout=timeout, unshare_net=True, ro_binds=self.trust if corporate_root else ())
+ finally:
+ bridge.close()
+ return Result(cp, time.monotonic() - t0, edge)
+
+ def hermes(self, *args: str, edge: Edge | None, **kw) -> Result:
+ return self.run([self.sb.hermes, *args], edge=edge, **kw)
+
+ # -- observation -------------------------------------------------------------
+ def state(self) -> dict:
+ """What an update is allowed to change: the checkout HEAD, the selected PM
+ environment, the PM runtime generation, and the installed tool store."""
+ from pm.environments import install_key
+
+ key = install_key(self.sb.checkout)
+ inst = self.sb.hermes_home / "installs" / key
+
+ def read(p: Path) -> str:
+ try:
+ return hashlib.sha256(p.read_bytes()).hexdigest()[:16]
+ except OSError:
+ return "missing"
+
+ tools = self.sb.hermes_home / "tools"
+ return {
+ "head": self.head(),
+ "facts": read(inst / "facts.json"),
+ "pm_runtime": read(inst / "pm-runtime" / "selected.json"),
+ "tools": sorted(p.name for p in tools.iterdir() if p.is_dir()) if tools.is_dir() else [],
+ }
+
+ def logs_tail(self, lines: int = 40) -> str:
+ out = []
+ for log in sorted((self.sb.hermes_home / "logs").glob("*.log")):
+ text = log.read_text(encoding="utf-8", errors="replace").splitlines()[-lines:]
+ out.append(f"--- {log.name} (tail) ---\n" + "\n".join(text))
+ return "\n".join(out) or "(no logs)"
+
+ def version_works(self) -> Result:
+ """The next ``hermes`` invocation, offline: the install must still start."""
+ return self.hermes("--version", edge=None, timeout=120)
+
+
+def seed_install(root: Path) -> Installed:
+ root.mkdir(parents=True, exist_ok=True)
+ origin = I.make_origin(root, I.head_sha())
+ I.git("config", "uploadpack.allowFilter", "true", cwd=origin)
+ sb = I.new_sandbox(root / "sb", origin)
+ # The host's SSL_CERT_FILE (allowlisted by _helpers) would replace the sandbox's trust store
+ # and hide the corporate root the cells install; the cells control trust explicitly.
+ sb.env.pop("SSL_CERT_FILE", None)
+ script = sb.root / "install.sh"
+ shutil.copy(H.WORKTREE / "scripts" / "install.sh", script)
+ cp = sb.run(["bash", str(script), "--non-interactive", "--skip-browser"], timeout=1800, input="")
+ assert cp.returncode == 0, "seed install failed:\n" + I.describe(cp)
+ # From here on the checkout talks to the official URL, which only the proxy can serve.
+ (sb.home / ".gitconfig").write_text("", encoding="utf-8")
+ gitroot = root / "gitroot"
+ (gitroot / "NousResearch").mkdir(parents=True, exist_ok=True)
+ (gitroot / "NousResearch" / "hermes-agent.git").symlink_to(origin)
+ ca = N.TestCA(root / "corporate-ca")
+ inst = Installed(root, sb, origin, gitroot, ca, ca.os_trust_store(root / "corporate-ca" / "etc-ssl-certs"))
+ assert_isolated(inst)
+ return inst
+
+
+def assert_isolated(inst: Installed) -> None:
+ """The namespace has no route out and no DNS; only the bridged proxy port answers."""
+ probe = (
+ "import socket,sys\n"
+ "bad=[]\n"
+ "for host in ('github.com','pypi.org','hermes-assets.nousresearch.com'):\n"
+ " try: socket.getaddrinfo(host,443); bad.append('dns:'+host)\n"
+ " except OSError: pass\n"
+ "for ip in ('140.82.112.3','1.1.1.1'):\n"
+ " s=socket.socket(); s.settimeout(3)\n"
+ " try: s.connect((ip,443)); bad.append('tcp:'+ip)\n"
+ " except OSError: pass\n"
+ "print('LEAK' if bad else 'ISOLATED', bad)\n"
+ )
+ edge = inst.edge()
+ try:
+ r = inst.run([inst.sb.python, "-c", probe], edge=edge, timeout=60)
+ finally:
+ edge.close()
+ assert r.rc == 0 and "ISOLATED" in r.cp.stdout, "network namespace is not isolated:\n" + I.describe(r.cp)
+
+
+# ---------------------------------------------------------------------------
+# Release-channel records (the R2 objects under https://hermes-assets.nousresearch.com/).
+# ---------------------------------------------------------------------------
+
+def canonical(value: object) -> bytes:
+ """The channel wire encoding (sorted keys, compact, trailing newline)."""
+ return (json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + "\n").encode()
+
+
+def _identity(name: str, token: str) -> dict:
+ pascal = f"HermesChannel{token}"
+ return {"token": token, "displayName": f"Hermes {name}", "appId": f"ai.hermes.channel.h{token}",
+ "appNamePascal": pascal, "artifactNamePascal": pascal, "cliName": f"hermes-{name}",
+ "windowsExecutableName": pascal, "msixAppIdWithOrg": f"NousResearch.{pascal}"}
+
+
+def stable_objects(commit: str, *, version: str = "2099.1.1", build_id: str = "c" * 32,
+ repository: str = REPOSITORY) -> dict[str, bytes]:
+ """A published stable release pinned at ``commit``: the channel record and its build manifest."""
+ identity = _identity("stable", "5" * 16)
+ prefix = f"releases/channel-builds/{build_id}/"
+ request = {"schema": 1, "buildId": build_id, "channel": "stable", "sequence": 1,
+ "repository": repository, "commit": commit, "sourceVersion": version, "version": version,
+ "windowsVersion": version + ".0", "releaseTag": "v" + version, "identity": identity,
+ "bundleEnv": {}, "publicBase": f"https://{ASSETS}"}
+ manifest = {"schema": 1, "receiverProtocol": 1, "request": request, "packages": [
+ {"platform": "darwin", "arch": "arm64", "variant": "bundled", "identity": identity["appId"],
+ "version": version, "teamId": "ABCDEFGHIJ",
+ "artifact": {"key": prefix + "Hermes.dmg", "sha256": "d" * 64, "size": 100},
+ "feed": {"key": prefix + "stable-mac.yml", "channel": "stable"}}]}
+ body = canonical(manifest)
+ record = {"schema": 1, "name": "stable", "repository": repository, "policy": "stable-release",
+ "state": "active", "revision": 1, "nextSequence": 2, "identity": identity,
+ "head": {"buildId": build_id, "sequence": 1, "manifestKey": prefix + "build.json",
+ "sha256": hashlib.sha256(body).hexdigest()}}
+ return {"/releases/channels/stable.json": canonical(record), f"/{prefix}build.json": body}
+
+
+# ---------------------------------------------------------------------------
+# Mirrors: a PEP 503 simple index and an npm registry holding a small pre-fetched set.
+# ---------------------------------------------------------------------------
+
+def prefetch(url: str, sha256: str, dest: Path) -> Path:
+ """Fixture-time download (host network, like the seed install) verified against its pin."""
+ import urllib.request
+
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ if dest.is_file() and hashlib.sha256(dest.read_bytes()).hexdigest() == sha256:
+ return dest
+ with urllib.request.urlopen(url, timeout=120) as resp: # noqa: S310 - pinned URL + digest
+ data = resp.read()
+ got = hashlib.sha256(data).hexdigest()
+ assert got == sha256, f"prefetched {url} has sha256 {got}, pinned {sha256}"
+ dest.write_bytes(data)
+ return dest
+
+
+def lock_wheels(lock: Path) -> list[tuple[str, str, str]]:
+ """``(project, wheel_url, sha256)`` for every pure-Python wheel pinned in a uv.lock."""
+ import tomllib
+
+ out = []
+ for pkg in tomllib.loads(lock.read_text(encoding="utf-8")).get("package", []):
+ for wheel in pkg.get("wheels", []):
+ if wheel["url"].endswith("-none-any.whl"):
+ out.append((pkg["name"], wheel["url"], wheel["hash"].split(":", 1)[1]))
+ return out
+
+
+def simple_index_app(files: dict[str, list[tuple[Path, str]]]) -> N.App:
+ """PEP 503 index: ``/simple/<name>/`` lists links (with ``#sha256=``) to ``/files/<wheel>``."""
+ routes: dict[str, bytes] = {"/simple/": b"<html><body>" + b"".join(
+ f'<a href="/simple/{n}/">{n}</a>'.encode() for n in files) + b"</body></html>"}
+ for name, wheels in files.items():
+ links = "".join(f'<a href="/files/{p.name}#sha256={sha}">{p.name}</a><br/>' for p, sha in wheels)
+ page = f"<!DOCTYPE html><html><body>{links}</body></html>".encode()
+ for spelling in {name, re.sub(r"[-_.]+", "-", name).lower()}:
+ routes[f"/simple/{spelling}/"] = page
+ for p, _ in wheels:
+ routes[f"/files/{p.name}"] = p.read_bytes()
+ base = N.static_app(routes)
+
+ def app(req: N.Request) -> N.Response:
+ resp = base(req)
+ if resp.status == 200 and req.path.startswith("/simple/"):
+ resp.headers["Content-Type"] = "text/html"
+ return resp
+
+ return app
+
+
+def env_without(env: dict[str, str], *names: str) -> dict[str, str]:
+ return {k: v for k, v in env.items() if k not in names}
+
+
+def installed_tool(inst: Installed, name: str) -> dict:
+ facts = json.loads((inst.sb.hermes_home / "tools" / "facts.json").read_text(encoding="utf-8"))
+ return facts["packages"][name]
+
+
+def tool_missing(inst: Installed, name: str) -> Iterator[dict]:
+ """A provisioned tool's store entry is gone (pruned or deleted), so PM must fetch it again.
+ The entry is parked, not deleted, and put back afterwards unless the cell re-provisioned it."""
+ tool = installed_tool(inst, name)
+ entry = inst.sb.hermes_home / "tools" / tool["entry"]
+ parked = inst.root / "parked" / tool["entry"]
+ parked.parent.mkdir(parents=True, exist_ok=True)
+ shutil.move(str(entry), str(parked))
+ try:
+ yield tool
+ finally:
+ if not entry.exists():
+ shutil.move(str(parked), str(entry))
+ else:
+ shutil.rmtree(parked, ignore_errors=True)
+
+
+SUCCESS_BANNERS = ("Update complete", "Code updated", "Already up to date")
+
+
+def assert_nothing_changed(inst: Installed, before: dict, r: Result, what: str) -> None:
+ """The failure contract: non-zero, says why, nothing reported as success, nothing moved,
+ and the next ``hermes`` still starts."""
+ assert r.rc != 0, f"{what}: the command reported success\n" + r.report(inst)
+ claimed = [b for b in SUCCESS_BANNERS if b in r.out]
+ assert not claimed, f"{what}: failed run printed a success banner {claimed}\n" + r.report(inst)
+ after = inst.state()
+ assert after == before, f"{what}: install state moved {before} -> {after}\n" + r.report(inst)
+ v = inst.version_works()
+ assert v.rc == 0 and I.TRACEBACK not in v.out, f"{what}: `hermes --version` broken afterwards\n" + I.describe(v.cp)
diff --git a/tests/e2e/core/upgrade/network/test_mirrors.py b/tests/e2e/core/upgrade/network/test_mirrors.py
new file mode 100644
index 00000000000..a692a6ad3cc
--- /dev/null
+++ b/tests/e2e/core/upgrade/network/test_mirrors.py
@@ -0,0 +1,120 @@
+"""Package mirrors: with a pip index mirror and an npm registry configured, nothing contacts the
+public indexes, and the locked install paths accept the mirror.
+
+This is the network CN/IR/corporate users actually have: ``pip.conf`` ``index-url`` and
+``~/.npmrc`` ``registry`` point at an internal mirror, and pypi.org, files.pythonhosted.org and
+registry.npmjs.org are unreachable. Every command runs in a private network namespace; the mirror
+is a plain-HTTP server bridged onto the namespace's loopback (what users configure), the proxy
+is the only other egress and refuses (and logs) every public index. The mirror holds a small set
+pre-fetched at fixture time and verified against the pins: the PM runtime's locked wheels
+(``pm/uv.lock``) and the npm tarball PM provisions.
+
+Classes: an update that ships a PM runtime change restages it with ``uv sync --locked`` against
+the committed lock while pip's mirror is bridged into uv (#124418, #123943, #122112), and PM's
+npm-hosted tool downloads (#123132: hardcoded registry.npmjs.org).
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+
+import pytest
+
+from tests.e2e.core._pending_fixes import known_failure
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.network import _netedge as N
+from tests.e2e.core.upgrade.network import _seed as S
+
+pytestmark = [
+ pytest.mark.platforms("linux"),
+ # Every `hermes update` here targets a throwaway sandboxed install, never the real checkout.
+ pytest.mark.live_system_guard_bypass,
+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),
+ pytest.mark.skipif(N.netns_required_reason() is not None, reason=str(N.netns_required_reason())),
+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+]
+
+
[email protected](scope="module")
+def inst(tmp_path_factory):
+ return S.seed_install(tmp_path_factory.mktemp("net-mirrors"))
+
+
+def _public_index_hits(edge: S.Edge) -> list[str]:
+ return [str(h) for h in edge.proxy.hits if h.host in S.PUBLIC_INDEXES]
+
+
+def test_pip_mirror_update_restages_pm_runtime_through_the_mirror(inst):
+ """The new upstream commit changes the PM runtime's inputs (``pm/pyproject.toml``), so the
+ update must restage that runtime from ``pm/uv.lock``. pip.conf names the mirror; the public
+ index is unreachable. The update must land, restage through the mirror, and never ask pypi."""
+ pm = inst.sb.checkout / "pm"
+ wheels: dict[str, list] = {}
+ for name, url, sha in S.lock_wheels(pm / "uv.lock"):
+ path = S.prefetch(url, sha, inst.root / "pypi-mirror" / url.rsplit("/", 1)[1])
+ wheels.setdefault(name, []).append((path, sha))
+ mirror = N.HttpSite(S.simple_index_app(wheels))
+ pip_conf = inst.sb.home / ".config" / "pip" / "pip.conf"
+ pip_conf.parent.mkdir(parents=True, exist_ok=True)
+ pip_conf.write_text(f"[global]\nindex-url = {mirror.url}/simple/\n", encoding="utf-8")
+ pyproject = (pm / "pyproject.toml").read_text(encoding="utf-8")
+ new = inst.publish("pm-runtime-input", {"pm/pyproject.toml": pyproject + "\n# e2e: PM runtime input change\n"})
+ before = inst.state()
+ edge = inst.edge(sites=[mirror])
+ try:
+ r = inst.hermes("update", "--yes", edge=edge, timeout=900)
+ finally:
+ edge.close()
+ pip_conf.unlink()
+ public = _public_index_hits(edge)
+ with known_failure(
+ r"needs to be updated, but `--locked` was provided",
+ "gated on #124418: with a pip index mirror bridged into uv, `uv sync --locked` rejects the "
+ "committed pm/uv.lock (registry URL mismatch) and the update fails restaging the PM runtime",
+ ):
+ assert r.rc == 0 and inst.head() == new, "update with a pip mirror configured failed\n" + r.report(inst)
+ after = inst.state()
+ assert after["pm_runtime"] != before["pm_runtime"], "the PM runtime was not restaged for its new inputs\n" + r.report(inst)
+ assert not public, f"a public index was contacted despite the mirror: {public}\n" + r.report(inst)
+
+
+def test_npm_registry_mirror_serves_pm_npm_download(inst):
+ """``~/.npmrc`` names the mirror; the npm tool's store entry is missing, so
+ `hermes pm install npm` has to fetch its pinned tarball: from the mirror, never from
+ registry.npmjs.org."""
+ tool = S.installed_tool(inst, "npm")
+ version = tool["version"]
+ tarball = f"npm-{version}.tgz"
+ blob = S.prefetch(f"https://registry.npmjs.org/npm/-/{tarball}", tool["artifacts"][0],
+ inst.root / "npm-mirror" / tarball)
+ packument = json.dumps({"name": "npm", "dist-tags": {"latest": version}, "versions": {version: {
+ "name": "npm", "version": version, "dist": {"tarball": f"MIRROR/npm/-/{tarball}"}}}})
+ routes: dict = {f"/npm/-/{tarball}": blob.read_bytes()}
+ mirror = N.HttpSite(N.static_app(routes))
+ routes["/npm"] = packument.replace("MIRROR", mirror.url).encode()
+ npmrc = inst.sb.home / ".npmrc"
+ npmrc.write_text(f"registry={mirror.url}/\n", encoding="utf-8")
+ try:
+ with S.tool_missing(inst, "npm") as tool:
+ edge = inst.edge(sites=[mirror])
+ try:
+ r = inst.hermes("pm", "install", "npm", edge=edge, timeout=600)
+ finally:
+ edge.close()
+ public = _public_index_hits(edge)
+ with known_failure(
+ r"registry\.npmjs\.org",
+ "gated on #123132: PM downloads npm-hosted tools from a hardcoded registry.npmjs.org "
+ "URL and ignores the configured npm registry",
+ ):
+ assert not public and r.rc == 0, (
+ f"npm provisioning with a registry mirror failed or reached the public registry {public}\n"
+ + r.report(inst))
+ assert (inst.sb.hermes_home / "tools" / tool["entry"]).is_dir(), "npm was not re-provisioned\n" + r.report(inst)
+ assert any(h.path.endswith(tarball) and h.status == 200 for h in mirror.hits), (
+ "the tarball was not served by the mirror\n" + r.report(inst))
+ finally:
+ npmrc.unlink()
diff --git a/tests/e2e/core/upgrade/network/test_offline_and_flaky.py b/tests/e2e/core/upgrade/network/test_offline_and_flaky.py
new file mode 100644
index 00000000000..0b339144d9d
--- /dev/null
+++ b/tests/e2e/core/upgrade/network/test_offline_and_flaky.py
@@ -0,0 +1,157 @@
+"""Offline and flaky networks: fail fast, loud and truthfully, or retry within bounds.
+
+Every command runs in a private network namespace. ``edge=None`` is a machine with no network
+at all; otherwise the only egress is the test's proxy, whose sites script the failure: a release
+host answering 503 with ``Retry-After``, a forge that rate-limits (HTTP 429), an artifact host
+serving bytes that don't match the pinned digest.
+
+The contract for a failure (``_seed.assert_nothing_changed``): non-zero exit, a message naming
+what failed, no success banner, the checkout / selected PM environment / PM runtime / tool store
+exactly as before, and the next ``hermes`` still starts. For a transient fault the contract is
+that the operation retries within bounds and then succeeds.
+
+Classes: offline update (channel and git phases) and offline PM provisioning; transient and
+persistent 503 on the channel record; persistent 429 from the forge (#106026 printed the success
+banner after a failed fetch); transient 503 then a digest mismatch on a PM download, for the
+tools whose artifacts come from GitHub releases and from nodejs.org (#106027's class: a Node
+tarball accepted without verification).
+"""
+
+from __future__ import annotations
+
+import shutil
+
+import pytest
+
+from tests.e2e.core._pending_fixes import known_failure
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.network import _netedge as N
+from tests.e2e.core.upgrade.network import _seed as S
+
+pytestmark = [
+ pytest.mark.platforms("linux"),
+ # Every `hermes update` here targets a throwaway sandboxed install, never the real checkout.
+ pytest.mark.live_system_guard_bypass,
+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),
+ pytest.mark.skipif(N.netns_required_reason() is not None, reason=str(N.netns_required_reason())),
+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+]
+
+MAIN_RECORD = "/releases/channels/main.json"
+FAST = 60 # seconds a no-network failure may take, bounded retries included
+
+
[email protected](scope="module")
+def inst(tmp_path_factory):
+ return S.seed_install(tmp_path_factory.mktemp("net-flaky"))
+
+
+def test_offline_update_fails_fast_and_changes_nothing(inst):
+ inst.publish("offline")
+ before = inst.state()
+ r = inst.hermes("update", "--yes", edge=None, timeout=300)
+ assert r.secs < FAST, f"an offline update took {r.secs:.0f}s to give up\n" + r.report(inst)
+ assert "unavailable" in r.out.lower() or "cannot reach" in r.out.lower(), (
+ "the offline failure does not say the network was unreachable\n" + r.report(inst))
+ S.assert_nothing_changed(inst, before, r, "offline update")
+
+
+def test_offline_provisioning_of_a_missing_tool_fails_loudly(inst):
+ """The tool store lost an entry (pruned, antivirus, disk cleanup) and the machine is offline:
+ the documented remedy `hermes pm install <tool>` must fail within bounds, name the tool and
+ the download, and leave every other tool alone."""
+ with S.tool_missing(inst, "ripgrep") as tool:
+ before = inst.state()
+ r = inst.hermes("pm", "install", "ripgrep", edge=None, timeout=300)
+ assert r.secs < FAST, f"offline provisioning took {r.secs:.0f}s to give up\n" + r.report(inst)
+ assert "ripgrep" in r.out and "download failed" in r.out, (
+ "the failure does not name the tool and the failed download\n" + r.report(inst))
+ assert not (inst.sb.hermes_home / "tools" / tool["entry"]).exists(), (
+ "an offline install left a store entry behind\n" + r.report(inst))
+ S.assert_nothing_changed(inst, before, r, "offline `hermes pm install ripgrep`")
+
+
+def test_channel_503_with_retry_after_is_retried_then_updates(inst):
+ """One 503 + ``Retry-After: 1`` from the release host (a CDN blip), then normal service."""
+ new = inst.publish("channel-blip")
+ assets = N.static_app({}, faults={MAIN_RECORD: [N.Response(503, b"busy\n", {"Retry-After": "1"})]})
+ edge = inst.edge(assets=assets)
+ try:
+ r = inst.hermes("update", "--yes", edge=edge)
+ finally:
+ edge.close()
+ reads = [h for h in edge.proxy.requests(S.ASSETS) if h.path == MAIN_RECORD]
+ with known_failure(
+ r"Channel read unavailable: HTTP 503",
+ "gated on #NEW_CHANNEL_RETRY: the channel record read makes one attempt, so a single 503 "
+ "with Retry-After aborts `hermes update`",
+ ):
+ assert r.rc == 0 and inst.head() == new, (
+ f"a single transient 503 aborted the update ({len(reads)} channel read(s))\n" + r.report(inst))
+ assert len(reads) >= 2, f"update succeeded without re-reading the record ({reads})\n" + r.report(inst)
+
+
+def test_channel_outage_fails_truthfully_within_bounds(inst):
+ """The release host answers 503 to every request: bounded retries, then a truthful failure,
+ and no fall-through to the git branch."""
+ inst.publish("channel-outage")
+ before = inst.state()
+ assets = N.static_app({}, always={MAIN_RECORD: N.Response(503, b"down\n", {"Retry-After": "1"})})
+ edge = inst.edge(assets=assets)
+ try:
+ r = inst.hermes("update", "--yes", edge=edge, timeout=300)
+ finally:
+ edge.close()
+ assert r.secs < FAST, f"a persistent 503 took {r.secs:.0f}s to give up\n" + r.report(inst)
+ assert "503" in r.out and "channel" in r.out.lower(), "the failure does not name the 503 from the channel\n" + r.report(inst)
+ S.assert_nothing_changed(inst, before, r, "channel outage")
+
+
+def test_forge_rate_limit_fails_truthfully(inst):
+ """Every git request gets HTTP 429 (the repo-scoped throttle users hit): the update must exit
+ non-zero, say it was rate limited, and print no success banner (#106026)."""
+ inst.publish("forge-429")
+ before = inst.state()
+ git = N.git_app(inst.gitroot, faults=[N.Response(429, b"rate limited\n", {"Retry-After": "1"})] * 50)
+ edge = inst.edge(git=git)
+ try:
+ r = inst.hermes("update", "--yes", edge=edge, timeout=300)
+ finally:
+ edge.close()
+ assert r.secs < FAST * 2, f"a rate-limited fetch took {r.secs:.0f}s to give up\n" + r.report(inst)
+ assert "429" in r.out or "rate limit" in r.out.lower(), "the failure does not say the forge rate-limited\n" + r.report(inst)
+ S.assert_nothing_changed(inst, before, r, "forge rate limit")
+
+
+# Where each tool's pinned artifact is downloaded from, as the PM lock declares it; the edge
+# serves those hosts (and the content-addressed hermes-assets mirror) with wrong bytes.
+ARTIFACT_HOSTS = {
+ "ripgrep": ("github.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com"),
+ "node": ("nodejs.org",),
+}
+
+
[email protected]("tool_name", sorted(ARTIFACT_HOSTS))
+def test_pm_download_retries_then_refuses_a_digest_mismatch(inst, tool_name):
+ """Artifact host: two 503s with Retry-After (retried), then bytes that are not the pinned
+ artifact. PM must refuse them, say so, and install nothing."""
+ bad = b"not the pinned artifact\n" * 4096
+ flaky = {"*": [N.Response(503, b"busy\n", {"Retry-After": "1"})] * 2}
+ extra = {host: N.static_app({"*": bad}, faults=flaky) for host in ARTIFACT_HOSTS[tool_name]}
+ with S.tool_missing(inst, tool_name) as tool:
+ before = inst.state()
+ edge = inst.edge(assets=N.static_app({"*": bad}), git=extra.pop("github.com", None), extra=extra)
+ try:
+ r = inst.hermes("pm", "install", tool_name, edge=edge, timeout=600)
+ finally:
+ edge.close()
+ served = [h for h in edge.proxy.hits if h.kind == "request" and h.host in ARTIFACT_HOSTS[tool_name]]
+ assert any(h.status == 503 for h in served) and any(h.status == 200 for h in served), (
+ f"the artifact host was not retried past its 503s: {[str(h) for h in served]}\n" + r.report(inst))
+ assert "sha256 mismatch" in r.out or "digest" in r.out.lower(), (
+ f"{tool_name}: the failure does not say the download failed verification\n" + r.report(inst))
+ assert not (inst.sb.hermes_home / "tools" / tool["entry"]).exists(), (
+ f"{tool_name}: unverified bytes were published to the tool store\n" + r.report(inst))
+ S.assert_nothing_changed(inst, before, r, f"`hermes pm install {tool_name}` with a digest mismatch")
diff --git a/tests/e2e/core/upgrade/network/test_proxy_only_egress.py b/tests/e2e/core/upgrade/network/test_proxy_only_egress.py
new file mode 100644
index 00000000000..b884dcc38e9
--- /dev/null
+++ b/tests/e2e/core/upgrade/network/test_proxy_only_egress.py
@@ -0,0 +1,120 @@
+"""Proxy-only egress: ``hermes update`` on a network whose ONLY way out is an HTTP(S) proxy.
+
+Every command runs in its own network namespace (no route, no DNS; proven per module by
+``_seed.assert_isolated``). The proxy is what a corporate network runs: it tunnels ``CONNECT``,
+inspects TLS with the company's own root, may demand credentials, and refuses every host it has no
+route for, logging it. The installed checkout was cloned from the official GitHub URL, so the
+update's channel read (``hermes-assets.nousresearch.com``), its git fetch and every lazy blob
+fetch of the partial clone (``github.com``) have to cross the proxy, and the cell reads the
+proxy's log to show they did.
+
+Failure classes: #124022 (updater dies with ``UNEXPECTED_EOF`` when direct TLS is cut and it
+ignores the proxy), a proxy that requires auth, and a corporate root supplied via
+``SSL_CERT_FILE`` instead of the OS store.
+"""
+
+from __future__ import annotations
+
+import shutil
+
+import pytest
+
+from tests.e2e.core._pending_fixes import known_failure
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.network import _netedge as N
+from tests.e2e.core.upgrade.network import _seed as S
+
+pytestmark = [
+ pytest.mark.platforms("linux"),
+ # Every `hermes update` here targets a throwaway sandboxed install, never the real checkout.
+ pytest.mark.live_system_guard_bypass,
+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),
+ pytest.mark.skipif(N.netns_required_reason() is not None, reason=str(N.netns_required_reason())),
+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+]
+
+GIT_PATH = "/NousResearch/hermes-agent.git/"
+
+
[email protected](scope="module")
+def inst(tmp_path_factory):
+ return S.seed_install(tmp_path_factory.mktemp("net-proxy"))
+
+
+def _assert_updated_through_proxy(inst: S.Installed, r: S.Result, new: str) -> None:
+ edge = r.edge
+ assert edge is not None
+ assert r.rc == 0, "update through the proxy failed\n" + r.report(inst)
+ assert inst.head() == new, f"update exited 0 but HEAD is {inst.head()}, not the published {new}\n" + r.report(inst)
+ channel = [h for h in edge.proxy.requests(S.ASSETS) if h.path.startswith("/releases/channels/")]
+ assert channel, "the channel record was never read through the proxy\n" + r.report(inst)
+ fetches = [h for h in edge.proxy.requests("github.com") if h.path.startswith(GIT_PATH) and h.status == 200]
+ assert any("git-upload-pack" in h.path for h in fetches), "no git fetch crossed the proxy\n" + r.report(inst)
+ stray = sorted(edge.proxy.hosts("refused") | edge.proxy.hosts("tls-rejected"))
+ assert not stray, f"the update tried to reach hosts the proxy does not route: {stray}\n" + r.report(inst)
+ v = inst.version_works()
+ assert v.rc == 0 and I.TRACEBACK not in v.out, "`hermes --version` broken after the update\n" + I.describe(v.cp)
+
+
+def test_update_through_tls_inspecting_proxy_lands_on_the_new_commit(inst):
+ """Corporate root installed in the OS trust store, HTTPS_PROXY set, direct egress impossible."""
+ new = inst.publish("tls-inspecting")
+ edge = inst.edge()
+ try:
+ r = inst.hermes("update", "--yes", edge=edge)
+ finally:
+ edge.close()
+ _assert_updated_through_proxy(inst, r, new)
+
+
+def test_update_through_authenticating_proxy_and_credentials_stay_private(inst):
+ """The proxy answers 407 without ``Proxy-Authorization``; the user's HTTPS_PROXY carries
+ ``user:password@``. The update must authenticate everywhere and never print the password."""
+ new = inst.publish("auth-proxy")
+ edge = inst.edge(auth=("corp-user", "pr0xy-s3cret-e2e"))
+ try:
+ r = inst.hermes("update", "--yes", edge=edge)
+ finally:
+ edge.close()
+ _assert_updated_through_proxy(inst, r, new)
+ assert "pr0xy-s3cret-e2e" not in r.out, "the proxy password was printed by the updater\n" + r.report(inst)
+
+
+def test_update_with_corporate_root_only_in_ssl_cert_file(inst):
+ """The corporate root is NOT in the OS store; the user points ``SSL_CERT_FILE`` at a bundle
+ that has it (the usual workaround on machines they don't administer). Every TLS client the
+ updater drives has to trust it: the channel read and the git fetch."""
+ new = inst.publish("ssl-cert-file")
+ bundle = inst.root / "ssl-cert-file-bundle.pem"
+ bundle.write_bytes(N.SYSTEM_CA_BUNDLE.read_bytes() + b"\n" + inst.ca.pem)
+ edge = inst.edge()
+ try:
+ r = inst.hermes("update", "--yes", edge=edge, corporate_root=False, env={"SSL_CERT_FILE": str(bundle)})
+ finally:
+ edge.close()
+ with known_failure(
+ r"unable to access 'https://github\.com/NousResearch/hermes-agent\.git/': "
+ r"(SSL certificate|server certificate verification failed|SSL certificate problem)",
+ "gated on #NEW_SSLCERT: the updater's git fetch ignores SSL_CERT_FILE, so a corporate root "
+ "supplied that way passes the channel read and then fails at `Fetching updates`",
+ ):
+ _assert_updated_through_proxy(inst, r, new)
+
+
+def test_tunnel_cut_to_channel_host_fails_fast_and_changes_nothing(inst):
+ """The #124022 symptom made deterministic: the proxy accepts the CONNECT to the release
+ host and hangs up before TLS (``UNEXPECTED_EOF``). The update must stop, say the channel
+ could not be read, and must not silently fall through to the git branch."""
+ inst.publish("tunnel-cut")
+ before = inst.state()
+ edge = inst.edge(eof_hosts=[S.ASSETS])
+ try:
+ r = inst.hermes("update", "--yes", edge=edge, timeout=300)
+ finally:
+ edge.close()
+ assert r.secs < 60, f"a cut tunnel took {r.secs:.0f}s to fail\n" + r.report(inst)
+ assert "channel" in r.out.lower() and "unavailable" in r.out.lower(), (
+ "the failure does not say the release channel was unreachable\n" + r.report(inst))
+ S.assert_nothing_changed(inst, before, r, "tunnel cut to the channel host")
diff --git a/tests/e2e/core/upgrade/network/test_release_channel_records.py b/tests/e2e/core/upgrade/network/test_release_channel_records.py
new file mode 100644
index 00000000000..166150e2b36
--- /dev/null
+++ b/tests/e2e/core/upgrade/network/test_release_channel_records.py
@@ -0,0 +1,125 @@
+"""Release-channel records: the updater follows the stable record exactly, or refuses.
+
+A source install subscribed to ``stable`` resolves its target from the channel record at
+``https://hermes-assets.nousresearch.com/releases/channels/stable.json`` and the build manifest
+it names (digest-pinned). The edge serves those objects (a fake of the R2 bucket, behind the
+TLS-inspecting proxy that is the namespace's only egress) and the git server behind the same
+proxy serves the source. In every cell origin/main has moved past what stable pins, so "the
+updater silently followed main" is visible as a HEAD that landed on the main tip.
+
+Classes: the record is valid (land exactly on its commit), unavailable (404 / 503 / tunnel cut),
+malformed (not JSON, manifest digest mismatch, another repository's record), or names a commit
+the forge does not have. #124309 is the missing live record; this suite pins that the updater
+then refuses stable with a clear message instead of moving to main.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+
+import pytest
+
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.network import _netedge as N
+from tests.e2e.core.upgrade.network import _seed as S
+
+pytestmark = [
+ pytest.mark.platforms("linux"),
+ # Every `hermes update` here targets a throwaway sandboxed install, never the real checkout.
+ pytest.mark.live_system_guard_bypass,
+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),
+ pytest.mark.skipif(N.netns_required_reason() is not None, reason=str(N.netns_required_reason())),
+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+]
+
+STABLE = "/releases/channels/stable.json"
+
+
[email protected](scope="module")
+def inst(tmp_path_factory):
+ inst = S.seed_install(tmp_path_factory.mktemp("net-channels"))
+ r = inst.hermes("update", "--set-channel", "stable", edge=None, timeout=120)
+ assert r.rc == 0, "could not subscribe the install to stable\n" + r.report(inst)
+ return inst
+
+
+def _release_and_main_tip(inst: S.Installed, tag: str) -> tuple[str, str]:
+ """A stable candidate commit on top of the install, then a newer main tip on top of it."""
+ release = inst.publish(f"{tag}-release")
+ tip = I.publish_commit(inst.origin, inst.root, f"e2e network: {tag} main tip",
+ {f"E2E_NETWORK_{tag}_TIP.txt": "unreleased\n"})
+ return release, tip
+
+
+def _update(inst: S.Installed, assets: N.App | None = None, **edge_kw) -> S.Result:
+ edge = inst.edge(assets=assets, **edge_kw)
+ try:
+ return inst.hermes("update", "--yes", edge=edge, timeout=600)
+ finally:
+ edge.close()
+
+
+def test_valid_stable_record_lands_exactly_on_its_commit(inst):
+ release, tip = _release_and_main_tip(inst, "valid")
+ r = _update(inst, N.static_app(S.stable_objects(release)))
+ assert r.rc == 0, "update to a valid stable record failed\n" + r.report(inst)
+ head = inst.head()
+ assert head != tip, "stable subscriber was moved to the unreleased main tip\n" + r.report(inst)
+ assert head == release, f"stable update landed on {head}, not the released {release}\n" + r.report(inst)
+ reads = [h.path for h in r.edge.proxy.requests(S.ASSETS)] if r.edge else []
+ assert STABLE in reads, f"the stable record was not read through the proxy: {reads}\n" + r.report(inst)
+
+
+def _refused(inst: S.Installed, r: S.Result, before: dict, what: str) -> None:
+ assert "stable" in r.out and "No update was applied" in r.out, (
+ f"{what}: the refusal does not name the stable channel and say nothing was applied\n" + r.report(inst))
+ S.assert_nothing_changed(inst, before, r, what)
+
+
+UNAVAILABLE = {
+ "not-published-404": dict(assets=N.static_app({})),
+ "outage-503": dict(assets=N.static_app({}, always={STABLE: N.Response(503, b"down\n")})),
+ "tunnel-cut": dict(eof_hosts=[S.ASSETS]),
+}
+
+
[email protected]("fault", sorted(UNAVAILABLE))
+def test_unavailable_stable_record_refuses_and_never_moves_to_main(inst, fault):
+ _release_and_main_tip(inst, f"unavailable-{fault}")
+ before = inst.state()
+ r = _update(inst, **UNAVAILABLE[fault])
+ _refused(inst, r, before, f"stable record {fault}")
+
+
+def _malformed(release: str) -> dict[str, dict[str, bytes]]:
+ good = S.stable_objects(release)
+ manifest_key = next(k for k in good if k != STABLE)
+ tampered = dict(good)
+ manifest = json.loads(good[manifest_key])
+ manifest["request"]["commit"] = "f" * 40 # a different build than the record's digest pins
+ tampered[manifest_key] = S.canonical(manifest)
+ return {
+ "not-json": {STABLE: b"<html>502 Bad Gateway</html>\n"},
+ "manifest-digest-mismatch": tampered,
+ "other-repository": S.stable_objects(release, repository="someone-else/hermes-agent"),
+ }
+
+
[email protected]("fault", ["manifest-digest-mismatch", "not-json", "other-repository"])
+def test_malformed_stable_record_refuses(inst, fault):
+ release, _ = _release_and_main_tip(inst, f"malformed-{fault}")
+ before = inst.state()
+ r = _update(inst, N.static_app(_malformed(release)[fault]))
+ _refused(inst, r, before, f"stable record {fault}")
+
+
+def test_stable_record_naming_a_commit_the_forge_does_not_have(inst):
+ """The record was published for a build whose commit never reached the forge (or was
+ force-pushed away): the fetch of that exact commit fails and nothing may change."""
+ _release_and_main_tip(inst, "unpublished-commit")
+ before = inst.state()
+ r = _update(inst, N.static_app(S.stable_objects("0123456789abcdef0123456789abcdef01234567")))
+ S.assert_nothing_changed(inst, before, r, "stable record naming an unpublished commit")