omnet
aien-dev/omnet
Brought by drakestapleton
omnet / cmd / tkad / test / faults.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | """Compile test-only syscall-boundary fault variants; never production switches.""" |
| 4 | import base64 |
| 5 | import hashlib |
| 6 | import json |
| 7 | import pathlib |
| 8 | import socket |
| 9 | import struct |
| 10 | import subprocess |
| 11 | import sys |
| 12 | import tempfile |
| 13 | import time |
| 14 | |
| 15 | root, binary = map(pathlib.Path, sys.argv[1:]) |
| 16 | source = pathlib.Path(str(binary) + ".om").read_text() |
| 17 | omc = subprocess.check_output(["sh",str(root/"tools/omc.sh")],text=True).strip() |
| 18 | fixture = json.loads((root/"cmd/tkad/test/fixture.json").read_text()) |
| 19 | write_needle = "fn stwr fd int b view uchar 65536 off ulong n ulong to long\nret write fd b off n\nend" |
| 20 | sync_needle = "fn stsync fd int to long\nret fsync fd\nend" |
| 21 | assert source.count(write_needle)==1 and source.count(sync_needle)==1 |
| 22 | |
| 23 | |
| 24 | def build(label, needle, replacement): |
| 25 | p = subprocess.run([omc],input=source.replace(needle,replacement).encode(),capture_output=True) |
| 26 | assert p.returncode==0,p.stderr.decode() |
| 27 | path=root/"build"/("tkad-fault-"+label);path.write_bytes(p.stdout);path.chmod(0o700) |
| 28 | return path |
| 29 | |
| 30 | |
| 31 | def start(binary, state, init=False): |
| 32 | p=subprocess.Popen([str(binary),str(state)]+(["--init"] if init else []),stdout=subprocess.PIPE,stderr=subprocess.PIPE) |
| 33 | deadline=time.monotonic()+10 |
| 34 | while time.monotonic()<deadline: |
| 35 | assert p.poll() is None,(p.returncode,p.communicate()) |
| 36 | try: |
| 37 | with socket.socket(socket.AF_UNIX) as s:s.connect(str(state/"tkad.sock")) |
| 38 | return p |
| 39 | except (FileNotFoundError,ConnectionRefusedError):time.sleep(.01) |
| 40 | raise AssertionError("startup timeout") |
| 41 | |
| 42 | |
| 43 | def rpc(state, route, body, node=0): |
| 44 | data=json.dumps(body).encode() |
| 45 | with socket.socket(socket.AF_UNIX) as s: |
| 46 | s.settimeout(10);s.connect(str(state/"tkad.sock")) |
| 47 | s.sendall(struct.pack("<4sBBHQI",b"TKA\x01",route,1,0,node,len(data))+data) |
| 48 | def exact(n): |
| 49 | b=b"" |
| 50 | while len(b)<n: |
| 51 | x=s.recv(n-len(b)) |
| 52 | if not x:return None |
| 53 | b+=x |
| 54 | return b |
| 55 | head=exact(12) |
| 56 | if head is None:return None,None |
| 57 | magic,status,zero,n=struct.unpack("<4sHHI",head) |
| 58 | assert magic==b"TKA\x01" and zero==0 |
| 59 | return status,json.loads(exact(n)) |
| 60 | |
| 61 | |
| 62 | register=dict(NodeID=1,NodeKey=fixture["nodes"][0],RotationPubkey=fixture["rotations"][0]) |
| 63 | for size,label in [(56,"terminator"),(16,"begin-header")]: |
| 64 | replacement=f"""global ds_fault ulong 1 |
| 65 | fn stwr fd int b view uchar 65536 off ulong n ulong to long |
| 66 | if eq n {size} |
| 67 | put ds_fault 0 add get ds_fault 0 1 |
| 68 | if eq get ds_fault 0 2 |
| 69 | ret -28 |
| 70 | end |
| 71 | end |
| 72 | ret write fd b off n |
| 73 | end""" |
| 74 | mutant=build(label,write_needle,replacement) |
| 75 | with tempfile.TemporaryDirectory(prefix="tkad-precommit-") as name: |
| 76 | state=pathlib.Path(name);p=start(mutant,state,True) |
| 77 | try: |
| 78 | before=rpc(state,11,{}) |
| 79 | assert rpc(state,9,register)[0]==503 |
| 80 | assert rpc(state,11,{})==before,"failed candidate became visible" |
| 81 | assert rpc(state,9,register)[0]==200,"transient failure poisoned future mutation" |
| 82 | status,after=rpc(state,11,{}) |
| 83 | assert status==200 and after["Revision"]==1 and len(after["Nodes"])==1 |
| 84 | assert p.poll() is None |
| 85 | finally:p.kill();p.communicate(timeout=10) |
| 86 | print(f"PASS tkad one-shot {label} ENOSPC: 503, unchanged live state, next mutation succeeds") |
| 87 | |
| 88 | replacement="""global ds_fault ulong 1 |
| 89 | fn stsync fd int to long |
| 90 | put ds_fault 0 add get ds_fault 0 1 |
| 91 | if eq get ds_fault 0 4 |
| 92 | ret -5 |
| 93 | end |
| 94 | ret fsync fd |
| 95 | end""" |
| 96 | mutant=build("uncertain",sync_needle,replacement) |
| 97 | with tempfile.TemporaryDirectory(prefix="tkad-uncertain-") as name: |
| 98 | state=pathlib.Path(name);p=start(mutant,state,True) |
| 99 | assert rpc(state,9,register)==(None,None),"uncertain commit sent a normal response" |
| 100 | p.communicate(timeout=10);assert p.returncode==74,p.returncode |
| 101 | p=start(binary,state) |
| 102 | try: |
| 103 | status,after=rpc(state,11,{}) |
| 104 | assert status==200 and after["Revision"]==1 and len(after["Nodes"])==1,"renamed candidate lost" |
| 105 | finally:p.kill();p.communicate(timeout=10) |
| 106 | print("PASS tkad post-rename directory-fsync EIO: fatal74, no reply, renamed candidate recovered") |
| 107 | |
| 108 | |
| 109 | def frames(snapshot): |
| 110 | result=[];p=16 |
| 111 | while True: |
| 112 | n=struct.unpack_from("<Q",snapshot,p)[0] |
| 113 | if n==0:return result |
| 114 | result.append(bytearray(snapshot[p+40:p+40+n])) |
| 115 | p+=40+n |
| 116 | |
| 117 | |
| 118 | def reseal(magic, payloads): |
| 119 | # Independent Python implementation of the documented store framing. |
| 120 | out=bytearray(magic);chain=bytes(32);total=0 |
| 121 | for count,payload in enumerate(payloads,1): |
| 122 | digest=hashlib.blake2s(payload).digest();total+=len(payload) |
| 123 | out+=struct.pack("<Q",len(payload))+digest+payload |
| 124 | chain=hashlib.blake2s(chain+digest+struct.pack("<QQQ",len(payload),total,count)).digest() |
| 125 | out+=bytes(8)+chain+struct.pack("<QQ",total,len(payloads)) |
| 126 | return out |
| 127 | |
| 128 | |
| 129 | with tempfile.TemporaryDirectory(prefix="tkad-semantic-recovery-") as name: |
| 130 | state=pathlib.Path(name);p=start(binary,state,True) |
| 131 | common=dict(Version=131,NodeKey=fixture["nodes"][0]) |
| 132 | try: |
| 133 | assert rpc(state,9,register)[0]==200 |
| 134 | assert rpc(state,1,dict(common,GenesisAUM=fixture["genesis"]),1)[0]==200 |
| 135 | pending=(state/"snapshot").read_bytes() |
| 136 | assert rpc(state,2,dict(common,Signatures={"1":fixture["signatures"][0]},SupportDisablement=fixture["secret"]),1)[0]==200 |
| 137 | finally:p.kill();p.communicate(timeout=10) |
| 138 | active=(state/"snapshot").read_bytes() |
| 139 | # Prove the independent reframer writes a valid baseline before using it |
| 140 | # to distinguish semantic validation from the checksum layer. |
| 141 | (state/"snapshot").write_bytes(reseal(active[:16],frames(active))) |
| 142 | p=start(binary,state);p.kill();p.communicate(timeout=10) |
| 143 | for label,index,offset in [("signature",2,-1),("support-secret",3,0),("genesis",4,-1),("reserved-metadata",0,40)]: |
| 144 | payloads=frames(active);payloads[index][offset]^=1 |
| 145 | (state/"snapshot").write_bytes(reseal(active[:16],payloads)) |
| 146 | refused=subprocess.run([str(binary),name],capture_output=True,timeout=10) |
| 147 | assert refused.returncode==73,(label,refused.returncode,refused.stderr) |
| 148 | payloads=frames(pending);struct.pack_into("<Q",payloads[0],16,99) |
| 149 | (state/"snapshot").write_bytes(reseal(pending[:16],payloads)) |
| 150 | refused=subprocess.run([str(binary),name],capture_output=True,timeout=10) |
| 151 | assert refused.returncode==73 |
| 152 | print("PASS tkad checksum-valid semantic corruption: NKS, genesis, support secret, reserved metadata, pending initiator rejected") |
| 153 | canon_needle = """note Store the canonical form; an empty signature still clears the node. |
| 154 | fn dssetcanon i ulong src view uchar 65536 n ulong auth ulong to ulong |
| 155 | if eq n 0 |
| 156 | dssetsig i src 0 auth |
| 157 | ret 0 |
| 158 | end |
| 159 | c = new uchar 65536 0 |
| 160 | z = dscanon src n c |
| 161 | if gt z 65536 |
| 162 | ret 1 |
| 163 | end |
| 164 | dssetsig i c z auth |
| 165 | ret 0 |
| 166 | end""" |
| 167 | assert source.count(canon_needle)==1 |
| 168 | # Test-only: keep submitted bytes so an ignored CBOR field can reach the limit. |
| 169 | raw_store=build("raw-store",canon_needle,"""note Test-only raw storage to exercise the registry capacity guard. |
| 170 | fn dssetcanon i ulong src view uchar 65536 n ulong auth ulong to ulong |
| 171 | dssetsig i src n auth |
| 172 | ret 0 |
| 173 | end""") |
| 174 | |
| 175 | |
| 176 | def padded(signature, size): |
| 177 | raw=base64.b64decode(signature) |
| 178 | assert 0xa0<=raw[0]<=0xb7 |
| 179 | pad=b"\x18\x63" |
| 180 | n=size-len(raw)-len(pad)-1-5 |
| 181 | assert n>0 |
| 182 | return base64.b64encode(bytes([raw[0]+1])+raw[1:]+pad+b"\x5a"+struct.pack(">I",n)+bytes(n)).decode() |
| 183 | |
| 184 | |
| 185 | with tempfile.TemporaryDirectory(prefix="tkad-registry-capacity-") as name: |
| 186 | state=pathlib.Path(name);p=start(raw_store,state,True) |
| 187 | for i in (0,1): |
| 188 | assert rpc(state,9,dict(NodeID=i+1,NodeKey=fixture["nodes"][i],RotationPubkey=fixture["rotations"][i]))[0]==200 |
| 189 | common=dict(Version=131,NodeKey=fixture["nodes"][0]) |
| 190 | try: |
| 191 | assert rpc(state,1,dict(common,GenesisAUM=fixture["genesis"]),1)[0]==200 |
| 192 | assert rpc(state,2,dict(common,Signatures={"1":fixture["signatures"][0],"2":fixture["signatures"][1]}),1)[0]==200 |
| 193 | assert rpc(state,9,dict(NodeID=3,NodeKey=fixture["nodes"][2],RotationPubkey=fixture["rotations"][2]))[0]==200 |
| 194 | assert rpc(state,7,dict(Version=131,NodeKey=fixture["nodes"][2],Signature=padded(fixture["signatures"][2],30000)),3)[0]==200 |
| 195 | first=rpc(state,11,{})[1] |
| 196 | assert len(first["Nodes"])==3 and first["Nodes"][2]["KeySignature"]==padded(fixture["signatures"][2],30000),first |
| 197 | # A second individually valid signature would push the registry past the |
| 198 | # map response limit; the candidate must be rejected, never committed. |
| 199 | assert rpc(state,7,dict(common,Signature=padded(fixture["signatures"][0],30000)),1)[0]==413 |
| 200 | assert rpc(state,11,{})[1]==first,"rejected candidate cannot change the registry" |
| 201 | finally:p.kill();p.communicate(timeout=10) |
| 202 | p=start(raw_store,state) |
| 203 | try: |
| 204 | assert rpc(state,11,{})[1]==first,"over-capacity rejection is durable, registry still readable" |
| 205 | finally:p.kill();p.communicate(timeout=10) |
| 206 | print("PASS tkad registry capacity guard: ignored CBOR padding rejected 413, registry unchanged and readable") |
| 207 |