omnet
aien-dev/omnet
Brought by drakestapleton
omnet / integration / e2e / runbook.py
| 1 | """Test-only rehearsal of docs/runbook.md, invoked through run.sh --scenario runbook. |
| 2 | |
| 3 | It walks the runbook in the same order, on a private tailnet in a fresh |
| 4 | network namespace, shaped like a small home tailnet: |
| 5 | 1. a tailnet already running on STOCK Headscale (signer-a, signer-b, server, |
| 6 | phone owned by the owner user, other owned by another user), database |
| 7 | backed up; |
| 8 | 2. deployment: stock Headscale stopped, tkad provisioned, the omnet-patched |
| 9 | Headscale started on the SAME database (the append-only migration path); |
| 10 | 2b. lock init is refused (409) while any node has no tailnet-lock key on |
| 11 | record; every node signs in again (`tailscale up --force-reauth`) and |
| 12 | keeps its address and peers; |
| 13 | 3. disablement secrets prepared before the lock exists: random 32-byte |
| 14 | secrets, their public values computed with the stock `lock disablement-kdf`; |
| 15 | 4. `lock init` on signer-a with --gen-disablements=0, the prepared values, and |
| 16 | the tailnet-lock keys of signer-a and signer-b only; every existing node must stay |
| 17 | admitted for every other node (nobody is locked out); |
| 18 | 5. a new device joins and is filtered until signer-b signs it; |
| 19 | 5b. `lock local-disable` on one device stops only that device enforcing; |
| 20 | 6. the non-owner cannot disable even with a valid secret (403); |
| 21 | 7. the escape: the owner disables with a prepared secret, everything opens; |
| 22 | 8. rollback: patched Headscale and tkad stopped; stock Headscale refuses the |
| 23 | adapter schema (negative control); downgrade.sql leaves a copy untouched |
| 24 | when its first statement fails (negative control), then is applied with the |
| 25 | documented `sqlite3 -bail` command; stock Headscale |
| 26 | started on the current database (the lock is already disabled); every node must |
| 27 | reconnect. (The pre-deployment backup is no rollback after step 2b.) |
| 28 | The secrets exist only in this process's memory and in private, disposable |
| 29 | command logs; they are never written to the receipt. |
| 30 | """ |
| 31 | import os |
| 32 | from pathlib import Path |
| 33 | import re |
| 34 | import shutil |
| 35 | |
| 36 | from lifecycle import ROOT, Failure, Harness |
| 37 | |
| 38 | OWNER_NODES = ("signer-a", "signer-b", "server", "phone") |
| 39 | SIGNERS = ("signer-a", "signer-b") |
| 40 | |
| 41 | |
| 42 | class Runbook(Harness): |
| 43 | suite = "runbook-rehearsal-v1.102.0" |
| 44 | |
| 45 | def lock_key_from_cli(self, name): |
| 46 | # The runbook reads the key from `tailscale lock` text, as a person would. |
| 47 | out = self.cli(name, "lock").stdout.decode() |
| 48 | found = re.findall(r"tlpub:[0-9a-f]{64}", out) |
| 49 | self.check(len(found) == 1, "could not read the tailnet-lock key of " + name) |
| 50 | self.check(found[0].split(":")[1] == self.keys(name)[1].split(":")[1], |
| 51 | "CLI and LocalAPI disagree on the key of " + name) |
| 52 | return found[0] |
| 53 | |
| 54 | def reauth(self, name): |
| 55 | key = self.hs("preauthkeys", "create", "--user", str(self.clients[name]["user"]), |
| 56 | "--expiration", "1h")["key"] |
| 57 | keyfile = self.clients[name]["dir"] / "auth-key" |
| 58 | keyfile.write_text(key) |
| 59 | self.stop(name + "-up") |
| 60 | self.cli(name, "up", "--force-reauth", "--login-server=" + self.url, |
| 61 | "--auth-key=file:" + str(keyfile), "--hostname=" + name, |
| 62 | "--accept-dns=false", "--accept-routes=false", "--timeout=45s") |
| 63 | |
| 64 | def all_have_nlkey(self): |
| 65 | # Read the committed rows, as the runbook's SELECT does on the server. |
| 66 | import sqlite3 |
| 67 | db = sqlite3.connect("file:" + str(self.root / "headscale.sqlite") + "?mode=ro", uri=True) |
| 68 | try: |
| 69 | rows = db.execute("SELECT COUNT(*), SUM(tka_key IS NULL OR tka_key = '') " |
| 70 | "FROM nodes WHERE deleted_at IS NULL").fetchone() |
| 71 | finally: |
| 72 | db.close() |
| 73 | return rows[0] > 0 and not rows[1] |
| 74 | |
| 75 | def all_admit(self, names): |
| 76 | keys = {n: self.keys(n)[0] for n in names} |
| 77 | return all(self.admitted(o, keys[p]) for o in names for p in names if o != p) |
| 78 | |
| 79 | def all_connected_peers(self, names): |
| 80 | keys = {n: self.keys(n)[0] for n in names} |
| 81 | return all(keys[p] in (self.local(o, "status").get("Peer") or {}) |
| 82 | for o in names for p in names if o != p) |
| 83 | |
| 84 | def scenario(self): |
| 85 | stock = self.args.stock_headscale.resolve() |
| 86 | patched = self.headscale |
| 87 | for path in (stock, patched, self.tkad, self.bin / "tailscale", self.bin / "tailscaled"): |
| 88 | self.check(path.is_file() and os.access(path, os.X_OK), "missing executable: " + str(path)) |
| 89 | everyone = OWNER_NODES + ("other",) |
| 90 | |
| 91 | # 1. The tailnet as it runs today: stock Headscale, no lock. |
| 92 | self.headscale, self.hsenv_saved, self.hsenv = stock, self.hsenv, dict(self.env) |
| 93 | self.start_headscale() |
| 94 | owner = self.hs("users", "create", "owner") |
| 95 | other = self.hs("users", "create", "other") |
| 96 | self.check(int(owner["id"]) == 1, "owner ID differs from the adapter configuration") |
| 97 | for name in everyone: |
| 98 | self.start_client(name, int(owner["id"] if name != "other" else other["id"])) |
| 99 | self.login(name) |
| 100 | self.wait(name + " registration", lambda n=name: self.joined(n)) |
| 101 | self.wait("pre-lock roster on stock Headscale", lambda: self.all_connected_peers(everyone)) |
| 102 | self.stop("headscale") |
| 103 | backup = self.root / "headscale.sqlite.before-omnet" |
| 104 | for suffix in ("", "-wal", "-shm"): |
| 105 | src = self.root / ("headscale.sqlite" + suffix) |
| 106 | if src.exists(): |
| 107 | shutil.copy2(src, str(backup) + suffix) |
| 108 | self.receipt("stock-tailnet-running-and-database-backed-up", nodes=len(everyone)) |
| 109 | |
| 110 | # 2. Deployment: tkad first, then the patched server on the same database. |
| 111 | self.headscale, self.hsenv = patched, self.hsenv_saved |
| 112 | self.start_tkad(initialize=True) |
| 113 | self.start_headscale() |
| 114 | self.wait("all nodes back on the patched server", lambda: all(self.connected(n) for n in everyone) |
| 115 | and self.all_connected_peers(everyone)) |
| 116 | self.check(not any(self.local(n)["Enabled"] for n in everyone), "lock enabled before init") |
| 117 | self.receipt("patched-headscale-adopts-existing-database-without-lock") |
| 118 | |
| 119 | # 2b. Init is refused until every node has an NLKey; then each re-registers. |
| 120 | early = self.cli("signer-a", "lock", "init", "--confirm", "--gen-disablements=1", |
| 121 | self.lock_key_from_cli("signer-a"), require=False) |
| 122 | self.check(early.returncode != 0 and b"409" in early.stdout + early.stderr, |
| 123 | "init must be refused while nodes have no tailnet-lock key") |
| 124 | self.check(not any(self.local(n)["Enabled"] for n in everyone), "refused init enabled the lock") |
| 125 | self.receipt("init-refused-until-every-node-re-registers", http_status=409) |
| 126 | before_ids = {n: (self.local(n, "status").get("Self") or {}).get("ID") for n in everyone} |
| 127 | for name in everyone: |
| 128 | self.reauth(name) |
| 129 | self.wait("every node re-registered with its tailnet-lock key", |
| 130 | lambda: self.all_have_nlkey() and all(self.connected(n) for n in everyone) |
| 131 | and self.all_connected_peers(everyone)) |
| 132 | after_ids = {n: (self.local(n, "status").get("Self") or {}).get("ID") for n in everyone} |
| 133 | self.check(before_ids == after_ids, "re-registration replaced node identities") |
| 134 | self.receipt("every-node-re-registered-same-identity") |
| 135 | |
| 136 | # 3. Disablement secrets prepared before the lock exists. |
| 137 | secrets = [os.urandom(32).hex() for _ in range(2)] |
| 138 | values = [] |
| 139 | for secret in secrets: |
| 140 | out = self.cli("signer-a", "lock", "disablement-kdf", secret).stdout.decode().strip() |
| 141 | self.check(re.fullmatch(r"disablement:[0-9a-f]{64}", out) is not None, |
| 142 | "disablement-kdf did not return one value") |
| 143 | values.append(out) |
| 144 | self.check(len(set(values)) == 2, "two secrets gave the same value") |
| 145 | self.receipt("disablement-secrets-prepared-before-init", count=len(secrets)) |
| 146 | |
| 147 | # 4. Init on signer-a: prepared values only, signer keys of signer-a and signer-b only. |
| 148 | signer_keys = [self.lock_key_from_cli(n) for n in SIGNERS] |
| 149 | out = self.cli("signer-a", "lock", "init", "--confirm", "--gen-disablements=0", *values, *signer_keys) |
| 150 | self.check(b"disablement-secret:" not in out.stdout, |
| 151 | "init generated a secret although only prepared values were given") |
| 152 | self.wait("lock on, every existing node signed and admitted by every other node", |
| 153 | lambda: self.same_head(list(everyone)) and |
| 154 | all(self.local(n)["NodeKeySigned"] for n in everyone) and self.all_admit(everyone)) |
| 155 | self.stable("nobody locked out", lambda: self.all_admit(everyone)) |
| 156 | self.check(len(self.local("server").get("TrustedKeys") or []) == len(SIGNERS), |
| 157 | "trusted keys are not exactly the signers") |
| 158 | self.receipt("init-with-two-signers-nobody-locked-out", |
| 159 | trusted_keys=len(self.local("server").get("TrustedKeys") or [])) |
| 160 | |
| 161 | # 5. A new device is filtered until a signer (signer-b) signs it. |
| 162 | self.start_client("newbox", int(owner["id"])) |
| 163 | self.login("newbox") |
| 164 | self.wait("new device registration", lambda: self.joined("newbox")) |
| 165 | nkey, npub = self.keys("newbox") |
| 166 | self.stable("new unsigned device filtered", lambda: all(self.rejected(o, nkey) for o in everyone)) |
| 167 | self.cli("signer-b", "lock", "sign", nkey, npub) |
| 168 | self.wait("signer-b's signature admits the new device", |
| 169 | lambda: all(self.admitted(o, nkey) for o in everyone)) |
| 170 | self.receipt("new-device-filtered-then-admitted-by-signer-signature") |
| 171 | |
| 172 | # 5b. Broken-server escape for one device: local-disable on phone only. |
| 173 | self.cli("phone", "lock", "local-disable") |
| 174 | self.wait("local-disable stops only that device enforcing", |
| 175 | lambda: not self.local("phone")["Enabled"] and |
| 176 | all(self.local(n)["Enabled"] for n in everyone if n != "phone")) |
| 177 | self.receipt("local-disable-affects-only-that-device") |
| 178 | enforcing = tuple(n for n in everyone if n != "phone") |
| 179 | |
| 180 | # 6. Non-owner with a valid secret is refused by the server. |
| 181 | denied = self.cli("other", "lock", "disable", "disablement-secret:" + secrets[0], require=False) |
| 182 | self.check(denied.returncode != 0 and b"403" in denied.stdout + denied.stderr, |
| 183 | "non-owner disable must be refused with 403") |
| 184 | self.check(all(self.local(n)["Enabled"] for n in enforcing), "lock dropped after refused disable") |
| 185 | self.receipt("non-owner-disable-refused", http_status=403) |
| 186 | |
| 187 | # 7. The escape: the owner disables with a prepared secret. |
| 188 | self.cli("signer-b", "lock", "disable", "disablement-secret:" + secrets[1]) |
| 189 | self.wait("escape opens the whole tailnet", |
| 190 | lambda: all(not self.local(n)["Enabled"] for n in everyone + ("newbox",))) |
| 191 | self.receipt("escape-with-prepared-secret-disables-lock") |
| 192 | |
| 193 | # 8. Rollback: stock server on the CURRENT database (lock already |
| 194 | # disabled), after integration/headscale/downgrade.sql. The pre-deployment backup is not the rollback once nodes |
| 195 | # re-registered in step 2b: their node keys changed, and stock Headscale |
| 196 | # answers "node not found" for every one of them (seen in rehearsal). |
| 197 | self.stop("headscale") |
| 198 | self.stop("tkad") |
| 199 | self.check(backup.exists(), "pre-deployment backup missing") |
| 200 | self.headscale, self.hsenv = stock, dict(self.env) |
| 201 | # Negative control: stock Headscale refuses the adapter's schema. |
| 202 | refused = self.command("stock-on-adapter-schema", [stock, "--config", self.hsconfig, "serve"], |
| 203 | env=self.hsenv, timeout=30, require=False) |
| 204 | self.check(refused.returncode != 0 and b"schema failed to validate" in refused.stdout + refused.stderr, |
| 205 | "stock Headscale was expected to refuse the adapter schema") |
| 206 | live = self.root / "headscale.sqlite" |
| 207 | # Negative control: a copy whose first ALTER must fail (column already |
| 208 | # gone) is left exactly as it was, migration row and table included. |
| 209 | broken = self.root / "downgrade-control.sqlite" |
| 210 | for suffix in ("", "-wal", "-shm"): |
| 211 | # The committed rows may still sit in the -wal file: copy all three. |
| 212 | if Path(str(live) + suffix).exists(): |
| 213 | shutil.copy2(str(live) + suffix, str(broken) + suffix) |
| 214 | self.command("downgrade-control-prepare", ["sqlite3", broken, |
| 215 | "ALTER TABLE nodes DROP COLUMN tka_signature;"]) |
| 216 | bad = self.command("downgrade-control", ["sh", "-c", 'sqlite3 "$1" < "$2"', "sh", broken, |
| 217 | ROOT / "integration/headscale/downgrade.sql"], require=False) |
| 218 | left = self.command("downgrade-control-read", ["sqlite3", broken, |
| 219 | "SELECT COUNT(*) FROM migrations WHERE id = '202610251600-omnet-tka-registration';" |
| 220 | " SELECT COUNT(*) FROM sqlite_master WHERE name = 'omnet_checkpoints';"]).stdout.split() |
| 221 | self.check(bad.returncode != 0 and left == [b"1", b"1"], |
| 222 | "a failing downgrade must change nothing") |
| 223 | # The documented command, exactly. |
| 224 | self.command("downgrade", ["sh", "-c", 'sqlite3 -bail "$1" < "$2"', "sh", live, |
| 225 | ROOT / "integration/headscale/downgrade.sql"]) |
| 226 | self.start_headscale() |
| 227 | self.wait("every node reconnects to stock Headscale", |
| 228 | lambda: all(self.connected(n) for n in everyone + ("newbox",)) |
| 229 | and self.all_connected_peers(everyone + ("newbox",))) |
| 230 | self.receipt("rollback-to-stock-headscale-on-current-database-reconnects-everyone") |
| 231 | secrets.clear() |
| 232 | |
| 233 | |
| 234 | def run(args): |
| 235 | if args.stock_headscale is None: |
| 236 | raise Failure("--stock-headscale is required for the runbook rehearsal") |
| 237 | return Runbook(args) |