Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omnet/blob/main/integration/e2e/lifecycle.py # omnet aien-dev/omnet Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omnet / integration / e2e / lifecycle.py` 546 lines ยท 29538 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Test-only stock-client lifecycle, invoked exclusively through run.sh. 3 4 No synthetic control replies or direct tkad mutations: every authority change is 5 made by the unmodified tailscale CLI. Observations use the real tailscaled LocalAPI 6 (/tka/status and /status), not CLI text parsing. Source contracts: Tailscale 7 v1.102.0 client/local/tailnetlock.go, ipn/ipnstate/ipnstate.go, and 8 control/controlclient/direct.go (LoginInteractive regenerates the node key). 9 Rotation completes Headscale's real `auth register` flow only after observing 10 an AuthURL and checking the old identity remains committed while auth is pending. 11 Negative requests use stock-generated signatures and require explicit upstream 12 HTTP rejection; CLI-local validation failures and timeouts do not count. 13 14 This proves client netmap admission, not packet delivery, production isolation, 15 power-loss durability, or immediate revocation of already-installed peers during 16 an outage. DERP is deliberately unavailable on loopback: only control-plane state 17 is asserted. All subprocesses and state belong to this one disposable invocation. 18 """ 19 import argparse 20 import hashlib 21 import http.client 22 import json 23 import os 24 from pathlib import Path 25 import re 26 import shutil 27 import signal 28 import socket 29 import subprocess 30 import sys 31 import tempfile 32 import time 33 import urllib.request 34 35 ROOT = Path(__file__).resolve().parents[2] 36 TIMEOUT = 90 37 38 39 class Failure(Exception): 40 pass 41 42 43 class UnixHTTP(http.client.HTTPConnection): 44 def __init__(self, path): 45 super().__init__("local-tailscaled.sock", timeout=4) 46 self.path = str(path) 47 48 def connect(self): 49 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 50 self.sock.settimeout(self.timeout) 51 self.sock.connect(self.path) 52 53 54 class Harness: 55 def __init__(self, args): 56 self.args = args 57 self.root = Path(tempfile.mkdtemp(prefix="omnet-e2e-", dir="/tmp")) 58 self.root.chmod(0o700) 59 self.bin = args.bin_dir.resolve() 60 self.headscale = args.headscale.resolve() 61 self.tkad = args.tkad.resolve() 62 self.env = {k: v for k, v in os.environ.items() 63 if not k.startswith(("TS_", "HEADSCALE_", "OMNET_", "TAILSCALE_")) 64 and k.lower() not in ("http_proxy", "https_proxy", "all_proxy", "no_proxy")} 65 self.env.update(HOME=str(self.root / "home"), XDG_CONFIG_HOME=str(self.root / "config"), 66 XDG_CACHE_HOME=str(self.root / "cache"), TS_NO_LOGS_NO_SUPPORT="true", 67 NO_PROXY="*") 68 for name in ("home", "config", "cache", "authority"): 69 (self.root / name).mkdir(mode=0o700) 70 self.processes = {} 71 self.clients = {} 72 self.events = [] 73 self.sequence = 0 74 self.url = "http://127.0.0.1:18080" 75 self.hsenv = dict(self.env, OMNET_TKAD_SOCKET=str(self.root / "authority/tkad.sock"), 76 OMNET_TKAD_ADMIN_USER_ID="1") 77 self.hsconfig = self.root / "headscale.json" 78 # Headscale accepts JSON through Viper. A nonempty local-only DERP map is 79 # mandatory upstream even when no data-plane checks are requested. 80 # Local DERP files use Go YAML field names, unlike the remote JSON API. 81 (self.root / "derp.yaml").write_text( 82 "regions:\n 999:\n regionid: 999\n regioncode: e2e\n" 83 " regionname: Isolated E2E\n nodes:\n" 84 " - name: e2e\n regionid: 999\n hostname: localhost\n" 85 " ipv4: 127.0.0.1\n derpport: 9\n stunport: -1\n") 86 self.hsconfig.write_text(json.dumps({ 87 "server_url": self.url, "listen_addr": "127.0.0.1:18080", 88 "metrics_listen_addr": "127.0.0.1:19090", "grpc_listen_addr": "127.0.0.1:15043", 89 "grpc_allow_insecure": False, "disable_check_updates": True, 90 "unix_socket": str(self.root / "headscale.sock"), "unix_socket_permission": "0600", 91 "noise": {"private_key_path": str(self.root / "noise.key")}, 92 "database": {"type": "sqlite", "sqlite": {"path": str(self.root / "headscale.sqlite"), 93 "write_ahead_log": True}}, 94 "prefixes": {"v4": "100.64.0.0/24", "allocation": "sequential"}, 95 "dns": {"magic_dns": False, "override_local_dns": False, 96 "base_domain": "e2e.invalid", "nameservers": {"global": []}}, 97 "derp": {"server": {"enabled": False}, "urls": [], 98 "paths": [str(self.root / "derp.yaml")], "auto_update_enabled": False}, 99 "logtail": {"enabled": False}, "log": {"level": "info"}, 100 "policy": {"mode": "file"}, "node": {"ephemeral": {"inactivity_timeout": "30m"}}, 101 })) 102 103 def start(self, label, argv, env=None): 104 old = self.processes.get(label) 105 if old and old.poll() is None: 106 raise Failure("attempt to duplicate process " + label) 107 self.sequence += 1 108 with open(self.root / f"{self.sequence:03}-{label}.log", "wb") as log: 109 proc = subprocess.Popen([str(x) for x in argv], stdin=subprocess.DEVNULL, 110 stdout=log, stderr=subprocess.STDOUT, env=env or self.env, 111 cwd=self.root, start_new_session=True) 112 self.processes[label] = proc 113 return proc 114 115 def stop(self, label, crash=False): 116 proc = self.processes.pop(label, None) 117 if not proc or proc.poll() is not None: 118 return 119 os.killpg(proc.pid, signal.SIGKILL if crash else signal.SIGTERM) 120 try: 121 proc.wait(timeout=8) 122 except subprocess.TimeoutExpired: 123 os.killpg(proc.pid, signal.SIGKILL) 124 proc.wait(timeout=8) 125 126 def command(self, label, argv, env=None, timeout=40, require=True): 127 self.sequence += 1 128 try: 129 result = subprocess.run([str(x) for x in argv], stdin=subprocess.DEVNULL, 130 stdout=subprocess.PIPE, stderr=subprocess.PIPE, 131 timeout=timeout, env=env or self.env, cwd=self.root) 132 except subprocess.TimeoutExpired as exc: 133 raise Failure(label + " timed out (not counted as a negative-test success)") from exc 134 (self.root / f"{self.sequence:03}-{label}.stdout").write_bytes(result.stdout) 135 (self.root / f"{self.sequence:03}-{label}.stderr").write_bytes(result.stderr) 136 if require and result.returncode != 0: 137 raise Failure(label + f" returned {result.returncode}; private log retained only with --keep") 138 return result 139 140 def hs(self, *args): 141 result = self.command("headscale-cli", [self.headscale, "--config", self.hsconfig, 142 *args, "--output", "json"], env=self.hsenv) 143 return json.loads(result.stdout) 144 145 def cli(self, name, *args, require=True): 146 return self.command(name + "-cli", [self.bin / "tailscale", "--socket", 147 self.clients[name]["socket"], *args], require=require) 148 149 def local(self, name, endpoint="tka/status"): 150 connection = UnixHTTP(self.clients[name]["socket"]) 151 try: 152 connection.request("GET", "/localapi/v0/" + endpoint, 153 headers={"Sec-Tailscale": "localapi", "Connection": "close"}) 154 response = connection.getresponse() 155 data = response.read(1024 * 1024 + 1) 156 if response.status != 200 or len(data) > 1024 * 1024: 157 raise Failure("LocalAPI read failed on " + name) 158 return json.loads(data) 159 finally: 160 connection.close() 161 162 def wait(self, label, predicate, timeout=TIMEOUT): 163 deadline = time.monotonic() + timeout 164 while time.monotonic() < deadline: 165 for service in ("tkad", "headscale"): 166 p = self.processes.get(service) 167 if p and p.poll() is not None and not getattr(self, "outage", False): 168 raise Failure(service + f" exited unexpectedly ({p.returncode}) during " + label) 169 try: 170 value = predicate() 171 if value: 172 return value 173 except (OSError, http.client.HTTPException, json.JSONDecodeError): 174 pass # The same bounded predicate must eventually positively succeed. 175 time.sleep(0.25) 176 raise Failure("timed out awaiting " + label) 177 178 def check(self, condition, message): 179 if not condition: 180 raise Failure(message) 181 182 def receipt(self, name, **details): 183 self.events.append({"scenario": name, "verdict": "PASS", **details}) 184 print("PASS: " + name, flush=True) 185 186 def start_tkad(self, initialize=False): 187 argv = [self.tkad, self.root / "authority"] 188 if initialize: 189 argv.append("--init") 190 self.start("tkad", argv) 191 # Connect only: do not act as a trusted adapter or fabricate any RPC. 192 def ready(): 193 with socket.socket(socket.AF_UNIX) as sock: 194 sock.settimeout(1) 195 sock.connect(str(self.root / "authority/tkad.sock")) 196 return True 197 self.wait("tkad socket", ready) 198 199 def start_headscale(self): 200 self.start("headscale", [self.headscale, "--config", self.hsconfig, "serve"], self.hsenv) 201 def healthy(): 202 with urllib.request.urlopen(self.url + "/health", timeout=2) as response: 203 return response.status == 200 204 self.wait("Headscale health", healthy) 205 206 def start_client(self, name, user=None): 207 if name not in self.clients: 208 directory = self.root / name 209 directory.mkdir(mode=0o700) 210 self.clients[name] = {"socket": directory / "tailscaled.sock", "dir": directory, 211 "user": user} 212 client = self.clients[name] 213 self.start(name, [self.bin / "tailscaled", "--tun=userspace-networking", "--port=0", 214 "--socket=" + str(client["socket"]), 215 "--state=" + str(client["dir"] / "tailscaled.state"), 216 "--statedir=" + str(client["dir"])]) 217 self.wait(name + " LocalAPI", lambda: self.local(name, "status")) 218 219 def login(self, name): 220 key = self.hs("preauthkeys", "create", "--user", str(self.clients[name]["user"]), 221 "--expiration", "1h", "--reusable")["key"] 222 # The authentication key is kept in the private runtime directory, not 223 # printed in the test receipt. All CLI calls select an explicit socket. 224 keyfile = self.clients[name]["dir"] / "auth-key" 225 keyfile.write_text(key) 226 args = [self.bin / "tailscale", "--socket", self.clients[name]["socket"], "up", 227 "--login-server=" + self.url, "--auth-key=file:" + str(keyfile), 228 "--hostname=" + name, "--accept-dns=false", "--accept-routes=false", 229 "--timeout=45s"] 230 self.stop(name + "-up") 231 self.start(name + "-up", args) 232 233 def rotate_interactively(self, name): 234 old_key = self.keys(name)[0] 235 old_url = self.local(name, "status").get("AuthURL") 236 before = [n for n in self.hs("nodes", "list") if n["node_key"] == old_key] 237 self.check(len(before) == 1, "rotation requires one committed original identity") 238 original = before[0] 239 self.stop(name + "-up") 240 # Deliberately supply no preauth key: the stock LoginInteractive flow 241 # generates and signs the new key, then requires real controller auth. 242 proc = self.start(name + "-up", [ 243 self.bin / "tailscale", "--socket", self.clients[name]["socket"], "up", 244 "--login-server=" + self.url, "--force-reauth", "--hostname=" + name, 245 "--accept-dns=false", "--accept-routes=false", "--timeout=45s"]) 246 247 def pending_auth(): 248 self.check(proc.poll() is None, "interactive rotation exited before authentication") 249 url = self.local(name, "status").get("AuthURL") 250 return url if url and url != old_url else None 251 252 url = self.wait("interactive rotation authentication URL", pending_auth, timeout=30) 253 match = re.fullmatch(re.escape(self.url) + r"/register/([A-Za-z0-9_-]+)", url) 254 self.check(match is not None, "unexpected interactive registration URL") 255 256 def uncommitted(): 257 nodes = [n for n in self.hs("nodes", "list") if n["id"] == original["id"]] 258 return (proc.poll() is None and len(nodes) == 1 and 259 nodes[0]["node_key"] == old_key and nodes[0]["user"]["id"] == original["user"]["id"]) 260 261 self.stable("rotation waits for authenticated registration", uncommitted, seconds=1) 262 # CLI auth registration is the upstream non-OIDC operator flow. The 263 # registration ID and its output stay only in the private runtime logs. 264 registered = self.hs("auth", "register", "--auth-id", match.group(1), 265 "--user", original["user"]["name"]) 266 self.check(registered["id"] == original["id"] and 267 registered["user"]["id"] == original["user"]["id"], 268 "interactive registration changed node or user identity") 269 self.wait("authenticated rotation CLI completion", lambda: proc.poll() is not None, timeout=30) 270 self.check(proc.returncode == 0, "authenticated rotation CLI failed") 271 272 def joined(self, name): 273 st = self.local(name, "status") 274 return (st.get("Self") or {}).get("ID") and self.local(name).get("NodeKey") 275 276 def connected(self, name): 277 status = self.local(name, "status") 278 # Cached client state alone must not satisfy a server recovery check. 279 return status.get("BackendState") == "Running" and (status.get("Self") or {}).get("Online") 280 281 def keys(self, name): 282 status = self.local(name) 283 return status["NodeKey"], status["PublicKey"] 284 285 @staticmethod 286 def peers(status, field): 287 return {p["NodeKey"] for p in status.get(field) or []} 288 289 def admitted(self, observer, nodekey): 290 status = self.local(observer) 291 normal = self.local(observer, "status") 292 return (status["Enabled"] and nodekey in self.peers(status, "VisiblePeers") 293 and nodekey not in self.peers(status, "FilteredPeers") 294 and nodekey in (normal.get("Peer") or {})) 295 296 def rejected(self, observer, nodekey): 297 status = self.local(observer) 298 normal = self.local(observer, "status") 299 return (status["Enabled"] and nodekey in self.peers(status, "FilteredPeers") 300 and nodekey not in self.peers(status, "VisiblePeers") 301 and nodekey not in (normal.get("Peer") or {})) 302 303 def same_head(self, names, expected=None): 304 states = [self.local(n) for n in names] 305 head = states[0].get("Head") 306 return head and all(s.get("Enabled") and s.get("Head") == head for s in states) and ( 307 expected is None or head == expected) 308 309 def stable(self, label, predicate, seconds=3): 310 self.wait(label, predicate) 311 deadline = time.monotonic() + seconds 312 while time.monotonic() < deadline: 313 self.check(predicate(), label + " regressed during stable observation") 314 time.sleep(0.25) 315 316 def restart_all(self): 317 for name in self.clients: 318 self.stop(name + "-up") 319 self.stop(name) 320 self.stop("headscale") 321 self.stop("tkad", crash=True) 322 self.start_tkad() 323 self.start_headscale() 324 for name in self.clients: 325 self.start_client(name) 326 327 def scenario(self): 328 for path in (self.headscale, self.tkad, self.bin / "tailscale", self.bin / "tailscaled"): 329 self.check(path.is_file() and os.access(path, os.X_OK), "missing executable: " + str(path)) 330 provenance = json.loads((self.bin / "stock-client.json").read_text()) 331 self.check(provenance["version"] == "v1.102.0", "wrong stock-client version") 332 for name in ("tailscale", "tailscaled"): 333 digest = hashlib.sha256((self.bin / name).read_bytes()).hexdigest() 334 self.check(digest == provenance["sha256"][name], "stock-client provenance mismatch: " + name) 335 self.receipt("stock-client-artifacts", version=provenance["version"], sha256=provenance["sha256"]) 336 self.start_tkad(initialize=True) 337 self.start_headscale() 338 owner = self.hs("users", "create", "owner") 339 member = self.hs("users", "create", "member") 340 self.check(int(owner["id"]) == 1, "fresh DB owner ID differs from explicit adapter configuration") 341 for name in ("a", "b"): 342 self.start_client(name, int(owner["id"])) 343 self.login(name) 344 self.wait(name + " registration", lambda n=name: self.joined(n)) 345 akey, apub = self.keys("a") 346 bkey, bpub = self.keys("b") 347 self.wait("pre-lock peer roster", lambda: bkey in (self.local("a", "status").get("Peer") or {})) 348 output = self.cli("a", "lock", "init", "--confirm", "--gen-disablements=1", apub, bpub) 349 secrets = re.findall(rb"disablement-secret:[0-9A-Fa-f]{64}", output.stdout) 350 self.check(len(secrets) == 1, "init did not return exactly one disablement secret") 351 secret = secrets[0].decode("ascii") 352 self.wait("initialized authority", lambda: self.same_head(["a", "b"]) and 353 self.local("a")["NodeKeySigned"] and self.local("b")["NodeKeySigned"] and 354 self.admitted("a", bkey) and self.admitted("b", akey)) 355 self.receipt("init-and-initial-roster-signatures") 356 357 self.start_client("c", int(member["id"])) 358 self.login("c") 359 self.wait("unsigned node registration", lambda: self.joined("c")) 360 ckey, cpub = self.keys("c") 361 self.stable("unsigned peer rejection", lambda: self.rejected("a", ckey) and 362 self.rejected("b", ckey) and self.local("c")["Enabled"] and 363 not self.local("c")["NodeKeySigned"]) 364 self.receipt("new-unsigned-node-filtered-by-stock-clients") 365 self.cli("b", "lock", "sign", ckey, cpub) 366 self.wait("signature-only notification", lambda: self.admitted("a", ckey) and 367 self.admitted("b", ckey) and self.local("c")["NodeKeySigned"]) 368 self.receipt("sign-and-signature-only-peer-notification") 369 370 # The stock client signs its rotation wrapper, but that is not a user 371 # login. Complete upstream interactive auth before accepting the change. 372 self.rotate_interactively("c") 373 self.wait("client node-key rotation", lambda: self.joined("c") and 374 self.keys("c")[0] != ckey and self.local("c")["NodeKeySigned"]) 375 rotated = self.keys("c")[0] 376 self.wait("rotated peer signature", lambda: self.admitted("a", rotated) and self.admitted("b", rotated)) 377 rotation = self.local("c")["NodeKeySignature"] 378 self.check(rotation.get("SigKind") == 2 and rotation.get("Nested"), "client did not retain a rotation signature") 379 for observer in ("a", "b"): 380 self.check(ckey not in (self.local(observer, "status").get("Peer") or {}), "old node key remained visible") 381 self.receipt("stock-client-node-key-rotation", 382 authentication="headscale-auth-register", pending_rotation_uncommitted=True) 383 384 # A real, valid stock-generated signature for the retired key must reach 385 # the daemon and get 404. Local validation failures and transport failures 386 # are not passes, and the rejection must not poison other clients. 387 rotation_head = self.local("a")["Head"] 388 failed = self.cli("a", "lock", "sign", ckey, cpub, require=False) 389 self.check(failed.returncode > 0 and b"404" in failed.stderr + failed.stdout, 390 "retired-key sign must produce explicit 404, not success or local validation failure") 391 self.stable("rejected signature leaves active tailnet healthy", lambda: 392 self.same_head(["a", "b", "c"], rotation_head) and 393 all(self.connected(n) for n in ("a", "b", "c")) and 394 self.admitted("a", rotated) and self.admitted("b", rotated) and 395 self.local("c")["NodeKeySigned"]) 396 self.receipt("retired-node-key-signature-request-rejected", http_status=404) 397 398 # Disabling automatic re-sign is deliberate: it makes key removal's 399 # authorization effect observable rather than transparently repairing it. 400 self.cli("a", "lock", "remove", "--re-sign=false", bpub) 401 self.wait("authority-key removal", lambda: self.same_head(["a", "b", "c"]) and 402 all(bpub not in {k["Key"] for k in self.local(n)["TrustedKeys"]} for n in ("a", "b", "c"))) 403 self.stable("removed authority rejects its rotated node", lambda: self.rejected("a", rotated) and 404 self.rejected("b", rotated) and not self.local("c")["NodeKeySigned"]) 405 self.receipt("authority-key-removal-invalidates-rotated-node") 406 self.cli("a", "lock", "sign", rotated, cpub) 407 self.wait("surviving authority re-sign", lambda: self.admitted("a", rotated) and self.local("c")["NodeKeySigned"]) 408 409 head = self.local("a")["Head"] 410 state_id = self.local("a")["StateID"] 411 self.restart_all() 412 self.wait("persisted active authority", lambda: self.same_head(["a", "b", "c"], head) and 413 self.admitted("a", rotated) and self.local("c")["NodeKeySigned"] and 414 all(self.connected(n) and self.local(n)["StateID"] == state_id for n in ("a", "b", "c"))) 415 self.check(self.keys("c")[0] == rotated, "restart changed node identity") 416 self.check({k["Key"] for k in self.local("a")["TrustedKeys"]} == {apub}, "removed key returned after recovery") 417 self.receipt("daemon-controller-and-client-persisted-recovery") 418 419 # c belongs to the non-owner Headscale user. Its real client validates 420 # this known-good secret locally, then the authenticated controller must 421 # deny the operation; possession of the secret is not an admin assertion. 422 denied = self.cli("c", "lock", "disable", secret, require=False) 423 self.check(denied.returncode > 0 and b"403" in denied.stderr + denied.stdout, 424 "non-owner disable must produce explicit 403, not success, timeout, or local validation failure") 425 self.stable("owner policy preserves authority", lambda: self.same_head(["a", "b", "c"], head) 426 and all(self.local(n)["StateID"] == state_id for n in ("a", "b", "c"))) 427 self.receipt("non-owner-valid-secret-disable-denied", http_status=403) 428 429 self.start_client("d", int(member["id"])) 430 self.login("d") 431 self.wait("outage test unsigned registration", lambda: self.joined("d")) 432 dkey, dpub = self.keys("d") 433 self.wait("outage test initial rejection", lambda: self.rejected("a", dkey)) 434 self.outage = True 435 self.stop("tkad", crash=True) 436 for operation in (("sign", dkey, dpub), ("disable", secret)): 437 failed = self.cli("a", "lock", *operation, require=False) 438 self.check(failed.returncode > 0 and b"503" in failed.stderr + failed.stdout, 439 "outage must produce explicit 503, not success, timeout, or local CLI validation failure") 440 self.stable("outage retains client protection", lambda: self.local("a")["Enabled"] and 441 self.local("a")["Head"] == head and self.rejected("a", dkey)) 442 self.start_client("e", int(member["id"])) 443 self.login("e") 444 # Positive observation of the upstream registration failure, plus actual 445 # client state, distinguishes a rejected request from a merely slow join. 446 def registration_rejected(): 447 logs = list(self.root.glob("*-e.log")) 448 if not logs: 449 return False 450 data = logs[-1].read_bytes() 451 # RegisterResponse.Error is an upstream application-level rejection, 452 # unlike the TKA RPCs' HTTP503. Require a completed negative response. 453 return (b"RegisterReq: got response; nodeKeyExpired=false, machineAuthorized=false; authURL=false" in data 454 and b"Received error:" in data 455 and self.local("e", "status").get("BackendState") == "NeedsLogin") 456 self.wait("registration receives explicit outage rejection", registration_rejected, timeout=30) 457 self.check(not self.joined("e"), "fresh client joined during tkad outage") 458 self.receipt("daemon-outage-sign-disable-and-registration-fail-closed") 459 self.start_tkad() 460 self.outage = False 461 self.wait("outage recovery retains authority", lambda: self.same_head(["a", "b", "c", "d"], head)) 462 self.wait("retry joins after daemon recovery", lambda: self.joined("e")) 463 ekey, _ = self.keys("e") 464 self.wait("retry remains unsigned", lambda: self.rejected("a", ekey) and self.rejected("a", dkey)) 465 self.receipt("outage-recovery-does-not-authorize-failed-mutations") 466 467 self.cli("a", "lock", "disable", secret) 468 names = list(self.clients) 469 self.wait("disable propagates to all stock clients", lambda: all(not self.local(n)["Enabled"] for n in names) 470 and all(k in (self.local("a", "status").get("Peer") or {}) for k in (rotated, dkey, ekey))) 471 self.receipt("disable-unfilters-previously-unsigned-peers") 472 self.restart_all() 473 self.wait("persisted disablement", lambda: all(self.connected(n) and not self.local(n)["Enabled"] for n in names) 474 and all(k in (self.local("a", "status").get("Peer") or {}) for k in (rotated, dkey, ekey))) 475 self.receipt("disablement-persists-across-full-restart") 476 477 def close(self): 478 for label in reversed(list(self.processes)): 479 self.stop(label) 480 if self.args.keep: 481 print("Private disposable state retained at " + str(self.root), file=sys.stderr) 482 else: 483 shutil.rmtree(self.root) 484 485 486 def main(): 487 parser = argparse.ArgumentParser(description=__doc__) 488 parser.add_argument("--outer-netns", required=True, help=argparse.SUPPRESS) 489 parser.add_argument("--bin-dir", type=Path, default=ROOT / "build/e2e") 490 parser.add_argument("--headscale", type=Path, default=ROOT / "build/headscale") 491 parser.add_argument("--tkad", type=Path, default=ROOT / "build/tkad") 492 parser.add_argument("--run-uid", type=int, help=argparse.SUPPRESS) 493 parser.add_argument("--run-gid", type=int, help=argparse.SUPPRESS) 494 parser.add_argument("--keep", action="store_true") 495 parser.add_argument("--scenario", choices=("lifecycle", "runbook"), default="lifecycle") 496 parser.add_argument("--stock-headscale", type=Path, 497 help="unpatched Headscale at the pinned commit (runbook rehearsal only)") 498 parser.add_argument("--result", type=Path, help="write a redacted machine-readable receipt") 499 args = parser.parse_args() 500 if os.readlink("/proc/self/ns/net") == args.outer_netns or {n for _, n in socket.if_nameindex()} != {"lo"}: 501 print("NOT_RUN: requires a fresh loopback-only network namespace; use run.sh", file=sys.stderr) 502 return 77 503 subprocess.run(["ip", "link", "set", "lo", "up"], check=True) 504 # Stock clients pause control traffic with only loopback. A namespace-local 505 # dummy link satisfies their network monitor without providing any egress. 506 subprocess.run(["ip", "link", "add", "e2e0", "type", "dummy"], check=True) 507 subprocess.run(["ip", "addr", "add", "192.0.2.1/32", "dev", "e2e0"], check=True) 508 subprocess.run(["ip", "link", "set", "e2e0", "up"], check=True) 509 if args.run_uid is not None or args.run_gid is not None: 510 if args.run_uid is None or args.run_gid is None or args.run_uid <= 0 or args.run_gid < 0: 511 raise SystemExit("privileged launcher requires a non-root invoking UID and its GID") 512 os.setgroups([]) 513 os.setresgid(args.run_gid, args.run_gid, args.run_gid) 514 os.setresuid(args.run_uid, args.run_uid, args.run_uid) 515 if os.getuid() != args.run_uid or os.geteuid() != args.run_uid: 516 raise SystemExit("failed to drop namespace setup privileges") 517 os.umask(0o077) 518 if args.scenario == "runbook": 519 # runbook.py imports this file as "lifecycle"; share one module (and 520 # one Failure class) instead of loading a second copy. 521 sys.modules.setdefault("lifecycle", sys.modules[__name__]) 522 import runbook 523 harness = runbook.run(args) 524 suite = runbook.Runbook.suite 525 else: 526 harness = Harness(args) 527 suite = "stock-client-tailnet-lock-v1.102.0" 528 result = {"verdict": "FAIL", "suite": suite, "scenarios": harness.events} 529 try: 530 harness.scenario() 531 result["verdict"] = "PASS" 532 returncode = 0 533 except (Failure, OSError, ValueError, KeyError, http.client.HTTPException) as exc: 534 result["failure"] = str(exc) 535 print("FAIL: " + str(exc), file=sys.stderr) 536 returncode = 1 537 finally: 538 harness.close() 539 if args.result: 540 args.result.resolve().write_text(json.dumps(result, indent=2) + "\n") 541 print(json.dumps(result, sort_keys=True)) 542 return returncode 543 544 545 if __name__ == "__main__": 546 sys.exit(main())