"""Crash and response-loss qualification on isolated loopback sockets and SQLite. Uses the installed ndc_vps package unchanged. One synthetic tracker at a time, no production database, TLS endpoint, firewall, physical device or service change. The internal HTTP loopback harness does not qualify production TLS transport. """ import asyncio import hashlib import json import os import struct import sys import tempfile import time import uuid from datetime import UTC, datetime from pathlib import Path from ndc_vps import VERSION from ndc_vps.service import Service from ndc_vps.store import Store IMEI = "123456789012345" TOKEN = "synthetic-owner-token-" + "a" * 32 def initialize(root): (root / "host.json").write_text( json.dumps( { "host_id": "vps_" + "a" * 64, "tracker": {"host": "synthetic.example", "port": 9922}, } ) ) store = Store(root) store.set_devices([{"imei": IMEI, "instance_id": "c" * 32}]) with store.db() as db: db.execute( "INSERT INTO state VALUES('owner',?)", ( json.dumps( { "core_id": "synthetic", "token": hashlib.sha256(TOKEN.encode()).hexdigest(), } ), ), ) return store async def child(root): service = Service(Store(root)) api = await asyncio.start_server(service.api, "127.0.0.1", 0) tracker = await asyncio.start_server(service.tracker, "127.0.0.1", 0) print( json.dumps( {"api": api.sockets[0].getsockname()[1], "tracker": tracker.sockets[0].getsockname()[1]} ), flush=True, ) async with api, tracker: await asyncio.gather(api.serve_forever(), tracker.serve_forever()) class Harness: def __init__(self, root): self.root, self.process, self.peer = root, None, None self.store = initialize(root) self.frames = [] async def start(self): self.process = await asyncio.create_subprocess_exec( sys.executable, str(Path(__file__).resolve()), "--child", str(self.root), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) line = await asyncio.wait_for(self.process.stdout.readline(), 8) if not line: raise RuntimeError((await self.process.stderr.read()).decode()) self.ports = json.loads(line) async def stop(self): if self.peer: self.peer[1].transport.abort() self.peer = None if self.process and self.process.returncode is None: self.process.kill() # Deliberately no graceful drain or in-memory handoff. await asyncio.wait_for(self.process.wait(), 5) async def restart(self): await self.stop() await self.start() def body(self, **extra): return { "id": uuid.uuid4().hex, "imei": IMEI, "kind": "request-position", "model": 231, "firmware": "0.01", "not_after": time.time() + 15, **extra, } async def http(self, method, path, body=None, *, loss=None): reader, writer = await asyncio.open_connection("127.0.0.1", self.ports["api"]) data = json.dumps(body or {}).encode() header = ( f"{method} {path} HTTP/1.1\r\nHost: localhost\r\n" f"Authorization: Bearer {TOKEN}\r\nContent-Length: {len(data)}\r\n\r\n" ).encode() try: writer.write(header + (data[:-4] if loss == "before-body" else data)) await writer.drain() if loss == "before-body": return None if loss == "after-commit": async with asyncio.timeout(3): while True: with self.store.db() as db: exists = db.execute( "SELECT 1 FROM commands WHERE id=?", (body["id"],) ).fetchone() if exists: return None # The client intentionally never observes the HTTP result. await asyncio.sleep(0.02) raw = await asyncio.wait_for(reader.read(), 4) head, payload = raw.split(b"\r\n\r\n", 1) return int(head.split()[1]), json.loads(payload) finally: writer.transport.abort() async def get(self, body): status, result = await self.http("GET", "/v1/commands/" + body["id"]) assert status == 200, result return result async def submit(self, body, **kwargs): value = await self.http("POST", "/v1/commands", body, **kwargs) if value is not None: assert value[0] == 200, value return value[1] async def connect(self): if self.peer: self.peer[1].transport.abort() self.peer = await asyncio.open_connection("127.0.0.1", self.ports["tracker"]) self.peer[1].write(b"\xff\x23" + int(IMEI).to_bytes(8, "little")) await self.peer[1].drain() assert len(await asyncio.wait_for(self.peer[0].readexactly(9), 2)) == 9 async def frame(self): first = await asyncio.wait_for(self.peer[0].readexactly(4), 3) raw = first + await asyncio.wait_for(self.peer[0].readexactly(first[1] + 1), 2) assert raw[0] == 0x7B and raw[-1] == 0x7D self.frames.append(raw) return raw async def no_frame(self): try: data = await asyncio.wait_for(self.peer[0].read(1), 0.35) except TimeoutError: return raise AssertionError(f"Unexpected data or connection loss: {data.hex()}") async def reply(self, frame): payload = struct.pack("