omnet
aien-dev/omnet
Brought by drakestapleton
omnet / cmd / tkad / test / identity.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | """Store identity and header schema. |
| 4 | |
| 5 | The daemon header carries one schema word and a 128-bit store identity, so a |
| 6 | client that follows a path can tell whether the store behind it is still the |
| 7 | same store it was talking to. This pins the four properties that make the |
| 8 | identity usable, and the header validation that keeps it honest: |
| 9 | |
| 10 | * init draws a fresh identity, from the kernel CSPRNG, once; |
| 11 | * the identity survives a restart and follows the directory when it is |
| 12 | renamed, so it names the store and not the path; |
| 13 | * two independent stores never share an identity, so the A6 replacement case |
| 14 | is detectable rather than silent; |
| 15 | * a header whose schema, identity or reserved words were altered is refused |
| 16 | instead of being served. |
| 17 | """ |
| 18 | import base64 |
| 19 | import hashlib |
| 20 | import json |
| 21 | import pathlib |
| 22 | import socket |
| 23 | import struct |
| 24 | import subprocess |
| 25 | import sys |
| 26 | import tempfile |
| 27 | import time |
| 28 | |
| 29 | PROBE = "--probe" in sys.argv |
| 30 | BIN = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "build/tkad") |
| 31 | if not BIN.is_absolute(): |
| 32 | BIN = pathlib.Path.cwd() / BIN |
| 33 | checks = 0 |
| 34 | |
| 35 | |
| 36 | def check(value, message): |
| 37 | global checks |
| 38 | assert value, message |
| 39 | checks += 1 |
| 40 | |
| 41 | |
| 42 | def exact(sock, count): |
| 43 | result = b"" |
| 44 | while len(result) < count: |
| 45 | part = sock.recv(count - len(result)) |
| 46 | if not part: |
| 47 | raise AssertionError("truncated daemon reply") |
| 48 | result += part |
| 49 | return result |
| 50 | |
| 51 | |
| 52 | class Daemon: |
| 53 | def __init__(self, directory, initialize=False): |
| 54 | self.directory = pathlib.Path(directory) |
| 55 | self.path = str(self.directory / "tkad.sock") |
| 56 | self.p = subprocess.Popen( |
| 57 | [str(BIN), str(self.directory)] + (["--init"] if initialize else []), |
| 58 | stdout=subprocess.PIPE, |
| 59 | stderr=subprocess.PIPE, |
| 60 | ) |
| 61 | deadline = time.monotonic() + 30 |
| 62 | while time.monotonic() < deadline: |
| 63 | if self.p.poll() is not None: |
| 64 | raise AssertionError(f"startup rc={self.p.returncode}: {self.p.communicate()}") |
| 65 | try: |
| 66 | with socket.socket(socket.AF_UNIX) as s: |
| 67 | s.settimeout(.2) |
| 68 | s.connect(self.path) |
| 69 | return |
| 70 | except (FileNotFoundError, ConnectionRefusedError, TimeoutError): |
| 71 | time.sleep(.02) |
| 72 | raise AssertionError("socket readiness timeout") |
| 73 | |
| 74 | def stop(self): |
| 75 | if self.p.poll() is None: |
| 76 | self.p.kill() |
| 77 | self.p.communicate(timeout=10) |
| 78 | |
| 79 | def map(self): |
| 80 | return self.rpc(11, {}) |
| 81 | |
| 82 | def rpc(self, route, body, admin=1): |
| 83 | payload = json.dumps(body, separators=(",", ":")).encode() |
| 84 | frame = struct.pack("<4sBBHQI", b"TKA\x01", route, admin, 0, 0, len(payload)) + payload |
| 85 | with socket.socket(socket.AF_UNIX) as s: |
| 86 | s.settimeout(30) |
| 87 | s.connect(self.path) |
| 88 | s.sendall(frame) |
| 89 | magic, status, reserved, size = struct.unpack("<4sHHI", exact(s, 12)) |
| 90 | check(magic == b"TKA\x01" and reserved == 0 and size <= 65536, "reply header") |
| 91 | answer = json.loads(exact(s, size)) |
| 92 | check(status == 200, f"route {route} status {status}: {answer}") |
| 93 | return answer |
| 94 | |
| 95 | |
| 96 | def store(state): |
| 97 | state.mkdir(mode=0o700) |
| 98 | d = Daemon(state, initialize=True) |
| 99 | try: |
| 100 | return d.map()["StoreID"] |
| 101 | finally: |
| 102 | d.stop() |
| 103 | |
| 104 | |
| 105 | def restart(state): |
| 106 | d = Daemon(state) |
| 107 | try: |
| 108 | return d.map()["StoreID"] |
| 109 | finally: |
| 110 | d.stop() |
| 111 | |
| 112 | |
| 113 | def header(state, word, value): |
| 114 | """Rewrite one header word with the framing and checksums recomputed.""" |
| 115 | snapshot = (state / "snapshot").read_bytes() |
| 116 | payloads = frames(snapshot) |
| 117 | struct.pack_into("<Q", payloads[0], word * 8, value) |
| 118 | (state / "snapshot").write_bytes(reseal(snapshot[:16], payloads)) |
| 119 | |
| 120 | |
| 121 | def frames(snapshot): |
| 122 | result = [] |
| 123 | p = 16 |
| 124 | while True: |
| 125 | n = struct.unpack_from("<Q", snapshot, p)[0] |
| 126 | if n == 0: |
| 127 | return result |
| 128 | result.append(bytearray(snapshot[p + 40:p + 40 + n])) |
| 129 | p += 40 + n |
| 130 | |
| 131 | |
| 132 | def reseal(magic, payloads): |
| 133 | # Independent Python implementation of the documented store framing. |
| 134 | out = bytearray(magic) |
| 135 | chain = bytes(32) |
| 136 | total = 0 |
| 137 | for count, payload in enumerate(payloads, 1): |
| 138 | digest = hashlib.blake2s(payload).digest() |
| 139 | total += len(payload) |
| 140 | out += struct.pack("<Q", len(payload)) + digest + payload |
| 141 | chain = hashlib.blake2s(chain + digest + struct.pack("<QQQ", len(payload), total, count)).digest() |
| 142 | out += bytes(8) + chain + struct.pack("<QQ", total, len(payloads)) |
| 143 | return out |
| 144 | |
| 145 | |
| 146 | def resumes(state): |
| 147 | """None when the daemon served the store, else its exit code.""" |
| 148 | p = subprocess.Popen([str(BIN), str(state)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 149 | try: |
| 150 | code = p.wait(timeout=1.5) |
| 151 | except subprocess.TimeoutExpired: |
| 152 | p.kill() |
| 153 | p.communicate() |
| 154 | return None |
| 155 | p.communicate() |
| 156 | return code |
| 157 | |
| 158 | |
| 159 | def refused(state): |
| 160 | return resumes(state) == 73 |
| 161 | |
| 162 | |
| 163 | with tempfile.TemporaryDirectory(prefix="tkad-identity-") as top: |
| 164 | root = pathlib.Path(top) |
| 165 | |
| 166 | if PROBE: |
| 167 | # Negative control: against a daemon without the identity guard this |
| 168 | # must exit 0 (the guard is gone, a zero identity is served) and |
| 169 | # against the production binary it must exit 3. run.sh requires both. |
| 170 | probe = root / "probe" |
| 171 | store(probe) |
| 172 | header(probe, 9, 0) |
| 173 | header(probe, 10, 0) |
| 174 | sys.exit(0 if resumes(probe) is None else 3) |
| 175 | |
| 176 | # A fresh identity per store, and the same identity after a restart. |
| 177 | first = store(root / "one") |
| 178 | check(len(first) == 32 and all(c in "0123456789abcdef" for c in first), f"identity hex32: {first}") |
| 179 | check(first != "0" * 32, "identity drawn, not absent") |
| 180 | check(restart(root / "one") == first, "identity survives restart") |
| 181 | |
| 182 | # Independent stores never share an identity, so the A6 replacement case is |
| 183 | # detectable: the path is the same, the identity is not. |
| 184 | second = store(root / "two") |
| 185 | check(second != first, "independent stores have distinct identities") |
| 186 | |
| 187 | # A durable mutation rewrites the header; the identity must not move. |
| 188 | nodekey = "nodekey:" + "11" * 32 |
| 189 | rotation = base64.b64encode(bytes(range(1, 33))).decode() |
| 190 | with tempfile.TemporaryDirectory(prefix="tkad-identity-commit-") as name: |
| 191 | committed = pathlib.Path(name) / "commit" |
| 192 | live = store(committed) |
| 193 | d = Daemon(committed) |
| 194 | try: |
| 195 | d.rpc(9, {"NodeID": 1, "NodeKey": nodekey, "RotationPubkey": rotation}, admin=True) |
| 196 | check(d.map()["StoreID"] == live, "identity unchanged by a durable mutation") |
| 197 | after = d.map() |
| 198 | check(after["Revision"] == 1 and len(after["Nodes"]) == 1, "mutation committed and durable") |
| 199 | finally: |
| 200 | d.stop() |
| 201 | check(restart(committed) == live, "identity unchanged after a committed restart") |
| 202 | |
| 203 | # The identity names the store, not the path: rename and it is unchanged. |
| 204 | (root / "one").rename(root / "one-moved") |
| 205 | check(restart(root / "one-moved") == first, "identity follows the directory rename") |
| 206 | check(store(root / "one") != first, "a new store at the vacated path has its own identity") |
| 207 | |
| 208 | # Header validation: schema, identity and reserved words are all enforced, |
| 209 | # and each refusal is a refusal to serve, not a silent repair. |
| 210 | for label, word, value in [ |
| 211 | ("schema absent", 8, 0), |
| 212 | ("schema unknown", 8, 2), |
| 213 | ("identity zero", 9, 0), |
| 214 | ("reserved word", 12, 1), |
| 215 | ]: |
| 216 | mutated = root / label.replace(" ", "-") |
| 217 | store(mutated) |
| 218 | if word == 9: |
| 219 | header(mutated, 9, 0) |
| 220 | header(mutated, 10, 0) |
| 221 | else: |
| 222 | header(mutated, word, value) |
| 223 | check(refused(mutated), f"{label} refused") |
| 224 | check((mutated / "snapshot").exists(), f"{label}: refused without rewriting the snapshot") |
| 225 | print(f"PASS tkad store identity: {checks} checks, header schema and reserved words enforced, identity drawn once, follows the store across rename and restart") |