Files
NODEDC_MISSION_CORE/apps/vps-host/ndc_vps/observation.py
T

247 lines
11 KiB
Python

"""Explicit, bounded interoperability evidence on the owned socket.
Disabled unless the authenticated owner arms a 180-second lease. Unknown traffic
is never treated as telemetry. A captured identity reply may be replayed once,
only to the byte-identical request of an admitted device. No vendor connection.
"""
import hashlib
import json
import re
import time
from .web_protocol import decode_request, decode_settings_reply
class Observation:
@staticmethod
def diagnostic_lease(db, identifier, command_id, *, bind_imei=None):
"""One fixed diagnostic command per explicitly armed evidence window.
Expiry bounds our dispatch/capture, not the device's service mode.
No repeated toggle, arbitrary payload, or automatic device restart.
"""
if not db.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='observations'"
).fetchone():
raise ValueError("diagnostic observation unavailable")
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("diagnostic observation unavailable")
value = json.loads(row[0])
if value["expires_at"] <= time.time() or value.get("reference"):
raise ValueError("diagnostic observation unavailable")
bound = value.get("diagnostic_command_id")
if bound not in (None, command_id) or bind_imei is None and bound != command_id:
raise ValueError("diagnostic observation already used")
if bind_imei is not None:
value.update(diagnostic_command_id=command_id, diagnostic_imei=bind_imei)
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
return value["expires_at"]
def __init__(self, store):
self.store = store
with store.db() as db:
db.execute("CREATE TABLE IF NOT EXISTS observations(id TEXT PRIMARY KEY, body TEXT)")
db.execute(
"CREATE TABLE IF NOT EXISTS observation_data(lease TEXT, sequence INTEGER, "
"raw BLOB, metadata TEXT, PRIMARY KEY(lease,sequence))"
)
def arm(self, body):
if set(body) not in ({"id"}, {"id", "reference"}) or not re.fullmatch(
r"[a-f0-9]{32}", body["id"]
):
raise ValueError("invalid observation")
reference = body.get("reference")
if "reference" in body:
if not isinstance(reference, dict) or set(reference) != {"request", "response"}:
raise ValueError("invalid reference")
request = bytes.fromhex(reference["request"])
response = bytes.fromhex(reference["response"])
imei, command, _ = decode_request(request, observe_empty_check=True)
if not self.store.admitted(imei):
raise ValueError("unqualified reference exchange")
if command == 6 and response == bytes.fromhex("5b00030006025d"):
pass
elif command == 1 and (
response == bytes.fromhex("5b000200015d")
or (
len(response) == 10
and response[:5] == bytes.fromhex("5b00060001")
and response[-1:] == b"]"
and int.from_bytes(response[5:9], "big") > 0
)
):
# The captured four-byte response equals the bench's numeric
# device ID. Qualify its exact replay once; no image payload.
pass
elif command == 2:
if response != bytes.fromhex("5b000200025d"):
decode_settings_reply(response)
# Bounded qualification of a zero-payload no-image response.
# Not admitted in the normal product channel until physically
# verified; no CRC image or device configuration is supplied.
elif command == 5 and response == bytes.fromhex("5b00030005015d"):
# Byte-exact command-5 reply captured from the manufacturer
# for the owner-approved return of its own configuration.
pass
else:
raise ValueError("unqualified reference exchange")
now = time.time()
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
if db.execute("SELECT 1 FROM observations WHERE id=?", (body["id"],)).fetchone():
previous = json.loads(
db.execute(
"SELECT body FROM observations WHERE id=?", (body["id"],)
).fetchone()[0]
)
if previous.get("reference") != reference:
raise ValueError("observation idempotency conflict")
return self.get(body["id"])
if any(
json.loads(r[0])["expires_at"] > now
for r in db.execute("SELECT body FROM observations")
):
raise ValueError("observation already armed")
if db.execute("SELECT COUNT(*) FROM observations").fetchone()[0] >= 64:
raise ValueError("observation evidence capacity reached")
value = {"id": body["id"], "created_at": now, "expires_at": now + 180}
if reference is not None:
value["reference"] = reference
db.execute("INSERT INTO observations VALUES(?,?)", (body["id"], json.dumps(value)))
return self.get(body["id"])
def get(self, identifier):
with self.store.db() as db:
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("unknown observation")
value = json.loads(row[0])
value.pop("reference", None)
value.pop("diagnostic_imei", None)
value["captures"] = [
json.loads(r[0])
for r in db.execute(
"SELECT metadata FROM observation_data WHERE lease=? ORDER BY sequence",
(identifier,),
)
]
return value
def close(self, identifier):
"""Disarm without deleting private evidence or retrying a dispatch."""
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("unknown observation")
value = json.loads(row[0])
value["expires_at"] = min(value["expires_at"], time.time())
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
return self.get(identifier)
def reply(self, ticket, raw):
"""Persist one dispatch before writing, including across service restarts."""
request = http_body(raw)
if request is None:
return None
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM observations WHERE id=?", (ticket[0],)).fetchone()
if not row:
return None
value = json.loads(row[0])
reference = value.get("reference")
if (
not reference
or value["expires_at"] <= time.time()
or value.get("reply_dispatched_at")
or request != bytes.fromhex(reference["request"])
or not self.store.admitted(str(int.from_bytes(request[4:12], "little")))
or not db.execute(
"SELECT 1 FROM observation_data WHERE lease=? AND sequence=?", ticket
).fetchone()
):
return None
response = bytes.fromhex(reference["response"])
value.update(
reply_dispatched_at=time.time(),
reply_monotonic=time.monotonic(),
reply_sha256=hashlib.sha256(response).hexdigest(),
reply_sequence=ticket[1],
)
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), ticket[0]))
return response
def claim(self):
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
for identifier, body in db.execute("SELECT id,body FROM observations"):
if json.loads(body)["expires_at"] <= time.time():
continue
sequence = db.execute(
"SELECT COUNT(*) FROM observation_data WHERE lease=?", (identifier,)
).fetchone()[0]
if sequence >= 4:
return None
metadata = {
"sequence": sequence,
"started_at": time.time(),
"monotonic": time.monotonic(),
"state": "receiving",
}
db.execute(
"INSERT INTO observation_data VALUES(?,?,?,?)",
(identifier, sequence, b"", json.dumps(metadata)),
)
return identifier, sequence
return None
def finish(self, ticket, raw, events):
if len(raw) > 16384:
raise ValueError("observation limit")
with self.store.db() as db:
row = db.execute(
"SELECT metadata FROM observation_data WHERE lease=? AND sequence=?", ticket
).fetchone()
if not row:
raise ValueError("unknown capture")
value = json.loads(row[0])
value.update(
state="captured",
completed_at=time.time(),
bytes=len(raw),
sha256=hashlib.sha256(raw).hexdigest(),
events=events,
)
db.execute(
"UPDATE observation_data SET raw=?,metadata=? WHERE lease=? AND sequence=?",
(raw, json.dumps(value), *ticket),
)
def http_body(raw):
"""First complete, bounded B2 POST only; reject ambiguous HTTP framing."""
header, separator, body = raw.partition(b"\r\n\r\n")
if not separator or len(header) > 2048:
return None
lines = header.split(b"\r\n")
if lines[0] != b"POST /c/index.php HTTP/1.1":
return None
headers = {}
for line in lines[1:]:
key, colon, value = line.partition(b":")
key = key.lower()
if not colon or key in headers:
return None
headers[key] = value.strip()
size = headers.get(b"content-length", b"")
if b"transfer-encoding" in headers or not size.isdigit():
return None
size = int(size)
if not 1 <= size <= 16384 or len(body) < size:
return None
return bytes(body[:size])