interplane.Get Omega
Read in your language

omnet

aien-dev/omnet

Brought by drakestapleton

branch main Branches Tags History

omnet / om / store / test / run.py

376 lines · 14814 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Native process tests. Python is an independent framing referee, never runtime logic."""
3import errno
4import hashlib
5import os
6from pathlib import Path
7import socket
8import struct
9import subprocess
10import tempfile
11
12ROOT = Path(__file__).resolve().parents[3]
13UNIT = ROOT / "om/store"
14COMPILER = subprocess.check_output([str(ROOT / "tools/omc.sh")], text=True).strip()
15BASE = (ROOT / "om/blake2s/blake2s.om").read_text()
16QUANT = (ROOT / "om/quantity/quantity.om").read_text()
17HELP = (UNIT / "store.om").read_text()
18POOL = (UNIT / "storepool.om").read_text()
19DRIVER = (UNIT / "test/driver.om").read_text()
20RESUME = (UNIT / "test/resume.om").read_text()
21COUNT = 0
22
23
24def compile_binary(folder, name, helpers=HELP, pool=POOL, driver=DRIVER, prefix=""):
25 source = QUANT + "\n" + BASE + "\n" + prefix + "\n" + helpers + "\n" + pool + "\n" + driver
26 result = subprocess.run([COMPILER], input=source.encode(), capture_output=True)
27 if result.returncode:
28 (folder / (name + ".om")).write_text(source)
29 raise AssertionError(f"compile {name}: {result.stderr.decode()}")
30 target = folder / name
31 target.write_bytes(result.stdout)
32 target.chmod(0o700)
33 return target
34
35
36def call(binary, path, mode, expected=0, seed="a"):
37 global COUNT
38 r = subprocess.run([str(binary), str(path), mode, seed], capture_output=True, timeout=120)
39 assert r.returncode == 0, (mode, "driver did not complete", r.returncode, r.stderr)
40 assert r.stdout == bytes([expected]), (mode, r.stdout, expected, r.stderr)
41 COUNT += 1
42
43
44def directory(root, name):
45 p = root / name
46 p.mkdir(mode=0o700)
47 return p
48
49
50def frame(payloads):
51 result = bytearray(b"OMNETSNAP0000001")
52 chain = bytes(32)
53 total = 0
54 for count, payload in enumerate(payloads, 1):
55 digest = hashlib.blake2s(payload).digest()
56 total += len(payload)
57 chain = hashlib.blake2s(chain + digest + struct.pack("<QQQ", len(payload), total, count)).digest()
58 result.extend(struct.pack("<Q", len(payload)) + digest + payload)
59 result.extend(struct.pack("<Q", 0) + chain + struct.pack("<QQ", total, len(payloads)))
60 return bytes(result)
61
62
63def save(path, data):
64 path.write_bytes(data)
65 path.chmod(0o600)
66
67
68def inherited_call(binary, first=None, second=None, arg="--resume", expected=b"\1"):
69 global COUNT
70 targets = []
71 try:
72 for target, source in ((64, first), (65, second)):
73 try:
74 os.fstat(target)
75 except OSError as e:
76 assert e.errno == errno.EBADF
77 else:
78 raise AssertionError("test handoff target already occupied")
79 if source is not None:
80 os.dup2(source, target, inheritable=True)
81 targets.append(target)
82 result = subprocess.run([str(binary), str(arg)], pass_fds=targets,
83 input=b"x", capture_output=True, timeout=20)
84 assert result.returncode == 0 and result.stdout == expected, (
85 "inheritance driver failed", result.returncode, result.stdout, result.stderr)
86 COUNT += 1
87 finally:
88 for target in targets:
89 os.close(target)
90
91
92with tempfile.TemporaryDirectory(prefix="omnet-store-") as tmp:
93 root = Path(tmp)
94 binary = compile_binary(root, "store")
95 for boundary in ("ret write fd b off n", "ret read fd b off n", "ret fsync fd",
96 "ret renames p ulong 0 ulong 26 int 0"):
97 assert HELP.count(boundary) == 1, ("fault boundary drift", boundary)
98 injected = HELP.replace("ret write fd b off n", """if eq get testfi 0 long 87
99ret -5
100end
101if eq get testfi 0 long 90
102ret 0
103end
104if eq get testfi 0 long 88
105ret -4
106end
107if eq get testfi 0 long 74
108if eq get testfi 2 long 0
109put testfi 2 1
110ret -4
111end
112end
113if eq get testfi 0 long 80
114if gt n 7
115ret write fd b off ulong 7
116end
117end
118ret write fd b off n""").replace("ret read fd b off n", """if eq get testfi 0 long 82
119ret -5
120end
121if eq get testfi 0 long 86
122ret 0
123end
124if eq get testfi 0 long 74
125if eq get testfi 3 long 0
126put testfi 3 1
127ret -4
128end
129end
130if eq get testfi 0 long 84
131if gt n 7
132ret read fd b off ulong 7
133end
134end
135ret read fd b off n""").replace("ret fsync fd", """put testfi 1 add get testfi 1 long 1
136if eq get testfi 0 long 70
137ret -5
138end
139if eq get testfi 0 long 68
140if eq get testfi 1 long 2
141ret -5
142end
143end
144ret fsync fd""").replace("ret renames p ulong 0 ulong 26 int 0", """if eq get testfi 0 long 78
145ret -5
146end
147ret renames p ulong 0 ulong 26 int 0""")
148 assert injected != HELP
149 fault = compile_binary(root, "fault", helpers=injected,
150 prefix="global testfi long 4",
151 driver=DRIVER.replace("note TEST_ARM", "put testfi 0 long mode\nput testfi 1 0"))
152 p = directory(root, "state")
153 call(binary, p, "L", 1)
154 call(binary, p, "I")
155 original = (p / "snapshot").read_bytes()
156 payload = bytes((ord("a") + i) & 255 for i in range(65536))
157 assert original == frame([payload, b"a" * 17]), "independent framing mismatch"
158 call(binary, p, "L")
159 ident = p.stat()
160 with socket.socket(socket.AF_UNIX) as guard:
161 guard.bind(b"\0omnet.store.v1." + struct.pack("<QQ", ident.st_dev, ident.st_ino))
162 call(binary, p, "S", 1)
163 call(binary, p, "I", 1)
164 call(binary, p, "A", seed="b")
165 call(binary, p, "L")
166 call(binary, p, "S", seed="b")
167 call(binary, p, "L", seed="b")
168 call(binary, p, "S")
169 resume = compile_binary(root, "resume", driver=RESUME)
170 rollover = subprocess.Popen([str(resume), str(p)], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
171 try:
172 pid = rollover.pid
173 assert rollover.stdout.read(2) == b"\x08\x09", "self-exec did not recover"
174 assert rollover.pid == pid and rollover.poll() is None
175 call(binary, p, "S", 1)
176 rollover.stdin.write(b"x")
177 rollover.stdin.flush()
178 assert rollover.stdout.read(1) == b"\0"
179 assert rollover.wait(timeout=5) == 0
180 COUNT += 1
181 finally:
182 if rollover.poll() is None:
183 rollover.kill()
184 rollover.wait(timeout=5)
185 rollover.stdin.close()
186 rollover.stdout.close()
187 call(binary, p, "L")
188 partial_driver = RESUME.replace("if ne stpass 64 65 0\nret rsresult 1",
189 "if ne stpass 64 2147483647 0\n"
190 "if ne stbegin 1\nret rsresult 4\nend\n"
191 "if ne stload 1\nret rsresult 4\nend\n"
192 "ret rsresult 1")
193 assert partial_driver != RESUME
194 partial = compile_binary(root, "partial-handoff", driver=partial_driver)
195 inherited_call(partial, arg=p) # first dup succeeds, impossible second FD fails, fail-stop
196 call(binary, p, "L")
197 failed_driver = RESUME.replace("put p 4 47", "put p 4 120")
198 assert failed_driver != RESUME
199 failed_exec = compile_binary(root, "failed-exec", driver=failed_driver)
200 inherited_call(failed_exec, arg=p, expected=b"\x08\x05")
201 call(binary, p, "L")
202 inherited_call(resume) # missing descriptors
203 otherdir = directory(root, "other-directory")
204 dirfd = os.open(p, os.O_RDONLY | os.O_DIRECTORY)
205 otherfd = os.open(otherdir, os.O_RDONLY | os.O_DIRECTORY)
206 filefd = os.open(p / "snapshot", os.O_RDONLY)
207 try:
208 inherited_call(resume, dirfd, None)
209 inherited_call(resume, dirfd, filefd) # non-socket lock
210 inherited_call(resume, dirfd, None, arg=p) # occupied first handoff target
211 with socket.socket(socket.AF_UNIX) as guard:
212 inherited_call(resume, dirfd, guard.fileno()) # unnamed socket
213 guard.bind(b"\0omnet.store.v1." + struct.pack("<QQ", ident.st_dev, ident.st_ino))
214 inherited_call(resume, guard.fileno(), dirfd) # swapped resources
215 inherited_call(resume, otherfd, guard.fileno()) # lock belongs to another directory
216 inherited_call(resume, dirfd, guard.fileno(), expected=b"\x09\0")
217 with socket.socket(socket.AF_UNIX) as guard:
218 guard.bind(b"\0omnet.store.v1." + struct.pack("<QQ", ident.st_dev, ident.st_ino) + b"x")
219 inherited_call(resume, dirfd, guard.fileno()) # full address length must match
220 finally:
221 os.close(dirfd)
222 os.close(otherfd)
223 os.close(filefd)
224
225 # Lock key is directory identity, not the spelling of its path.
226 holder = subprocess.Popen([str(binary), str(p), "H"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
227 try:
228 assert holder.stdout.read(1) == b"\x09"
229 aliases = [p, p / ".", root / "state/../state"]
230 link = root / "parent-alias"
231 link.symlink_to(root, target_is_directory=True)
232 aliases.append(link / "state") # trusted ancestor alias, final component is a directory
233 for alias in aliases:
234 call(binary, alias, "S", 1)
235 save(p / "snapshot.tmp", b"stale")
236 call(binary, p, "S", 1)
237 assert (p / "snapshot.tmp").exists(), "contender removed owner's temporary file"
238 finally:
239 holder.kill()
240 holder.wait(timeout=5)
241 holder.stdin.close()
242 holder.stdout.close()
243 call(binary, p, "L")
244 assert not (p / "snapshot.tmp").exists()
245 # Kill a writer with real staged frames, not merely an invented stale file.
246 holder = subprocess.Popen([str(binary), str(p), "K", "b"],
247 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
248 try:
249 assert holder.stdout.read(1) == b"\x09"
250 assert (p / "snapshot.tmp").stat().st_size > 65536
251 call(binary, p, "S", 1)
252 finally:
253 holder.kill()
254 holder.wait(timeout=5)
255 holder.stdin.close()
256 holder.stdout.close()
257 call(binary, p, "L")
258 assert (p / "snapshot").read_bytes() == original
259 assert not (p / "snapshot.tmp").exists()
260
261 # Only explicit init accepts absent committed state; orphan temp is never promoted.
262 orphan = directory(root, "orphan")
263 save(orphan / "snapshot.tmp", original)
264 call(binary, orphan, "L", 1)
265 assert (orphan / "snapshot.tmp").exists()
266 call(binary, orphan, "I")
267 empty = directory(root, "empty")
268 call(binary, empty, "E")
269 assert (empty / "snapshot").read_bytes() == frame([])
270 call(binary, empty, "L", 3) # framing accepts empty; driver expects nonempty semantic records
271 call(binary, p, "U") # too-large chunk is a declared error, not an array trap
272 call(binary, p, "Q") # exactly 65536 frames, then refuse one more
273 call(binary, p, "C") # exactly 32 MiB payload, then refuse one more byte
274 call(binary, p, "Y") # a negative running byte charge is a declared refusal, not a trap
275 call(binary, p, "B") # a negative running frame count is a declared refusal, not a trap
276 assert (p / "snapshot").read_bytes() == original
277 capacity = directory(root, "capacity")
278 call(binary, capacity, "E")
279 call(binary, capacity, "G") # durable full-capacity snapshot and streaming recovery
280
281 symlink = root / "dir-link"
282 symlink.symlink_to(p, target_is_directory=True)
283 call(binary, symlink, "L", 1)
284 for mode in (0o755, 0o750, 0o1700):
285 p.chmod(mode)
286 call(binary, p, "L", 1)
287 p.chmod(0o700)
288 regular = root / "not-directory"
289 save(regular, b"x")
290 call(binary, regular, "L", 1)
291 for name in ("snapshot", "snapshot.tmp"):
292 target = p / name
293 if target.exists():
294 target.unlink()
295 target.symlink_to(regular)
296 call(binary, p, "L", 1)
297 assert target.is_symlink()
298 target.unlink()
299 target.mkdir(mode=0o700)
300 call(binary, p, "L", 1)
301 target.rmdir()
302 os.mkfifo(target, 0o600)
303 call(binary, p, "L", 1)
304 target.unlink()
305 sock = socket.socket(socket.AF_UNIX)
306 sock.bind(str(target))
307 call(binary, p, "L", 1)
308 sock.close()
309 target.unlink()
310 save(target, original)
311 for mode in (0o644, 0o400, 0o1600):
312 target.chmod(mode)
313 call(binary, p, "L", 1)
314 target.chmod(0o600)
315 other = root / "extra-link"
316 os.link(target, other)
317 call(binary, p, "L", 1)
318 other.unlink()
319 if os.geteuid() == 0:
320 os.chown(target, 12345, -1)
321 call(binary, p, "L", 1)
322 os.chown(target, 0, -1)
323 target.unlink()
324 save(p / "snapshot", original)
325 if os.geteuid() == 0:
326 os.chown(p, 12345, -1)
327 call(binary, p, "L", 1)
328 os.chown(p, 0, -1)
329
330 # Truncations span header, frames, payload and footer. Corruption includes every field class.
331 for size in (0, 1, 15, 16, 23, 55, 56, 65591, 65592, len(original)-56, len(original)-1):
332 save(p / "snapshot", original[:size])
333 call(binary, p, "L", 1)
334 for offset in (0, 15, 16, 20, 24, 55, 56, 1000, 65591, len(original)-49, len(original)-16, len(original)-1):
335 broken = bytearray(original)
336 broken[offset] ^= 1
337 save(p / "snapshot", broken)
338 call(binary, p, "L", 1)
339 save(p / "snapshot", original + b"x")
340 call(binary, p, "L", 1)
341 save(p / "snapshot", original)
342 # Oversize metadata rejected before reading attacker-controlled file contents.
343 with (p / "snapshot").open("r+b") as f:
344 f.truncate(36175945)
345 call(binary, p, "L", 1)
346 save(p / "snapshot", original)
347
348 # Fault controls exist only in a separately compiled test image, never in store source.
349 for mode in ("W", "Z", "R", "F", "N", "X", "V"):
350 call(fault, p, mode, 1, seed="b")
351 assert (p / "snapshot").read_bytes() == original, mode
352 call(binary, p, "L")
353 for mode in ("P", "T", "J"):
354 call(fault, p, mode, seed="b")
355 call(binary, p, "L", seed="b")
356 call(binary, p, "S")
357 call(fault, p, "D", 2, seed="b")
358 call(binary, p, "L", seed="b") # selected new snapshot, startup re-syncs it
359
360 # Completed-result mutant: removing payload checksum comparison must be observable.
361 mutant_pool = POOL.replace("if ne steqhash h 8 d 0", "if ne int 0 int 0")
362 assert mutant_pool != POOL
363 mutant = compile_binary(root, "mutant", pool=mutant_pool)
364 # A payload mismatch still reaches semantic checking (3), rather than framing refusal (1).
365 # Keep the original frame digest but forge the final chain for altered payload bytes.
366 changed = bytearray(payload)
367 changed[944] ^= 1
368 forged = bytearray(frame([bytes(changed), b"a" * 17]))
369 forged[24:56] = original[24:56]
370 save(p / "snapshot", forged)
371 call(binary, p, "L", 1)
372 call(mutant, p, "L", 3)
373 save(p / "snapshot", original)
374 print(f"PASS store: {COUNT} completed native cases; independent BLAKE2s framing; checksum mutant detected")
375 if os.geteuid() != 0:
376 print("SKIP store foreign-UID chown fixtures: runner is non-root")