From d684eb7e05b6c3b4b9ca1e56c8239186db398f83 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Mon, 28 Sep 2026 18:43:39 +0300 Subject: [PATCH] feat(vps): ship durable ARNavi host with reproducible install and recovery --- apps/vps-host/README.md | 447 +++++++++++++++ apps/vps-host/firewall.py | 95 ++++ apps/vps-host/install.py | 429 ++++++++++++++ apps/vps-host/ndc_vps/__init__.py | 3 + apps/vps-host/ndc_vps/__main__.py | 19 + apps/vps-host/ndc_vps/actions.py | 120 ++++ apps/vps-host/ndc_vps/commands.py | 585 ++++++++++++++++++++ apps/vps-host/ndc_vps/configuration.py | 85 +++ apps/vps-host/ndc_vps/delivery.py | 109 ++++ apps/vps-host/ndc_vps/full_configuration.py | 113 ++++ apps/vps-host/ndc_vps/observation.py | 246 ++++++++ apps/vps-host/ndc_vps/operations.py | 492 ++++++++++++++++ apps/vps-host/ndc_vps/restart.py | 30 + apps/vps-host/ndc_vps/service.py | 402 ++++++++++++++ apps/vps-host/ndc_vps/sim_guard.py | 83 +++ apps/vps-host/ndc_vps/sim_selection.py | 55 ++ apps/vps-host/ndc_vps/store.py | 262 +++++++++ apps/vps-host/ndc_vps/transport_evidence.py | 71 +++ apps/vps-host/owner_entry.py | 92 +++ apps/vps-host/portable_state.py | 311 +++++++++++ apps/vps-host/qualify_configuration.py | 100 ++++ apps/vps-host/qualify_delivery.py | 117 ++++ apps/vps-host/qualify_faults.py | 286 ++++++++++ apps/vps-host/qualify_operations.py | 95 ++++ apps/vps-host/qualify_receipts.py | 82 +++ apps/vps-host/qualify_recovery.py | 158 ++++++ apps/vps-host/qualify_runtime.py | 131 +++++ scripts/build_vps_host.py | 94 ++++ scripts/qualify_vps_clean_client.py | 69 +++ scripts/qualify_vps_clean_host.py | 339 ++++++++++++ 30 files changed, 5520 insertions(+) create mode 100644 apps/vps-host/README.md create mode 100644 apps/vps-host/firewall.py create mode 100644 apps/vps-host/install.py create mode 100644 apps/vps-host/ndc_vps/__init__.py create mode 100644 apps/vps-host/ndc_vps/__main__.py create mode 100644 apps/vps-host/ndc_vps/actions.py create mode 100644 apps/vps-host/ndc_vps/commands.py create mode 100644 apps/vps-host/ndc_vps/configuration.py create mode 100644 apps/vps-host/ndc_vps/delivery.py create mode 100644 apps/vps-host/ndc_vps/full_configuration.py create mode 100644 apps/vps-host/ndc_vps/observation.py create mode 100644 apps/vps-host/ndc_vps/operations.py create mode 100644 apps/vps-host/ndc_vps/restart.py create mode 100644 apps/vps-host/ndc_vps/service.py create mode 100644 apps/vps-host/ndc_vps/sim_guard.py create mode 100644 apps/vps-host/ndc_vps/sim_selection.py create mode 100644 apps/vps-host/ndc_vps/store.py create mode 100644 apps/vps-host/ndc_vps/transport_evidence.py create mode 100644 apps/vps-host/owner_entry.py create mode 100644 apps/vps-host/portable_state.py create mode 100644 apps/vps-host/qualify_configuration.py create mode 100644 apps/vps-host/qualify_delivery.py create mode 100644 apps/vps-host/qualify_faults.py create mode 100644 apps/vps-host/qualify_operations.py create mode 100644 apps/vps-host/qualify_receipts.py create mode 100644 apps/vps-host/qualify_recovery.py create mode 100644 apps/vps-host/qualify_runtime.py create mode 100644 scripts/build_vps_host.py create mode 100644 scripts/qualify_vps_clean_client.py create mode 100644 scripts/qualify_vps_clean_host.py diff --git a/apps/vps-host/README.md b/apps/vps-host/README.md new file mode 100644 index 00000000..c2047402 --- /dev/null +++ b/apps/vps-host/README.md @@ -0,0 +1,447 @@ +# NODE.DC Mission VPS Host 0.1.41 + +Version 0.1.41 completes the extracted transport observation batch before a +socket closure cancels its sender. Closing a stream can no longer abandon a +pending observation commit. All monitoring commands now wait for device input +on their selected socket no older than five seconds, as configuration commands +already did. Empty send queues alone are insufficient evidence of a live path. +The pending intent and original attempt deadlines are preserved; device input +wakes the sender without an extra probing command. This mitigates stale-stream +dispatch but does not guarantee delivery on a cellular network. + +Version 0.1.40 persists command transport observations separately from B2 +execution: prepared, written, TCP acknowledged, or unconfirmed with a reason. +The Linux send-queue watchdog records when the complete command prefix was +acknowledged; it never promotes the command to executed. Socket closure, expiry +and process restart preserve uncertainty. Observations are available on command +and operation APIs and attempt history, including late observations after a +device reply. No payload, password, modem address or SIM identity is logged. +Existing deadlines, retry policy and Core-to-VPS polling direction are unchanged. + + +Version 0.1.39 adds engineering-only `probe-diagnostic-mode` (INTERNAL +SERVER_COM `01 00`) for model 231 / firmware 0.01. A separately armed, +authenticated observation ID is mandatory; exactly one command may consume +each observation. Dispatch is restricted to an existing admitted connection, +expires within three seconds, and is never replayed across reconnect/restart. +Closing the observation prevents a queued dispatch. There is no raw-command +input and this action is absent from the operator catalogue/durable operations. +The 180-second lease bounds capture/dispatch, **not** the device's mode lifetime. +A token receipt does not establish a mode change or fresh SIM identity. +Physical qualification and termination semantics are recorded separately. + +Version 0.1.35 publishes imported state with a single same-filesystem rename. +A failed staging copy cannot expose a partial host identity, and restoration +does not need a second full-size journal copy. + +Version 0.1.34 adds portable, quiesced state export and empty-host import. +The source stays fenced across service/OS restarts. TLS identity, ownership, +registered devices and the entire durable journal move together. Import uses +the exact matching installer and preserves the configured endpoint. + +Version 0.1.33 makes service-code directory traversal independent of the root +installer caller's umask. Private credentials and state retain their restricted +permissions. It otherwise preserves the 0.1.32 durable maintenance runtime. + +Version 0.1.31 accepts matching binary command token receipts through either +admitted monitoring connection of the same B2, including a reconnected stream. +ACK (code 6) remains distinct from a final result. Text replies, revoked devices, +unknown sessions and other trackers cannot confirm a binary command. + +Version 0.1.30 resumes only independent readback of a committed `configure-all` +image after a VPS process restart or a new B2 connection, preserving its ID, target, original +deadline and stage pacing. No image, SIM switch, restart or output action replays. +Fresh readback can establish the target, the predecessor or an unknown image; +an unavailable device still ends with an uncertain outcome. This is recovery of +verification, not proof that the B2 modem can recover autonomously. + +Version 0.1.29 additionally defers configuration commands on a silent monitoring +stream until the B2 sends fresh input (within five monotonic seconds). A drained +TCP queue alone does not prove a live cellular path. The original operation +deadline is retained; dispatched stages never replay. Position/output command +policy is unchanged. This is a transport admission guard, not a cellular latency +guarantee. + +Version 0.1.28 answers the observed empty HTTP opcode-7 request with current Unix +UTC seconds from the owner's VPS, using the reference-qualified u32be envelope. +Only an admitted model-231/0.01 identity with an active matching modem peer can +receive it. It does not change settings, complete an operation or extend its +deadline. The host clock must be correct. Device dialogue/repeated configuration +acceptance is recorded separately; a clock response alone is not that acceptance. + +Version 0.1.27 admits a new command only when the selected Linux socket has +no unacknowledged kernel bytes or pending asyncio bytes. Among eligible streams +the most recently active one wins. Blocked streams cannot steal a command from +a drained stream; deadlines remain unchanged and dispatched commands never +replay. Transport readiness does not confirm execution. + +Version 0.1.26 adds immutable request deadlines for idempotent Core delivery, +a durable bounded wait for undispatched position requests, and event-driven idle +senders. Terminal operation history is indexed out of the packet/dispatch path. +Commands already dispatched to a tracker are never automatically replayed. + +The engineering `qualify_faults.py` harness checks crash recovery, lost HTTP +responses, immutable expiry and no replay using the installed package with +temporary SQLite and loopback sockets. It does not use production state or +physical hardware. See [fault qualification](../../docs/arnavi_b2/FAULT_RECOVERY_20260927.md). + +Version 0.1.25 bounds command bytes in the Linux TCP queue to the earlier of +the operation deadline and 30 seconds after dispatch. HTTP settings replies +have a 12-second transport bound, capped by the operation deadline. Monotonic +watchdogs account for both asyncio and kernel buffers; abortive close prevents +queued data from lingering after disconnect. TCP acknowledgement only releases +the transport watchdog, never confirms device execution. Interrupted or expired +actions are never replayed. Already received commands cannot be cancelled. + +Version 0.1.24 adds exclusive SIM selection on qualified B2 model 231 / firmware +0.01: fresh configuration preflight, one image write, exact readback, one restart, +and fresh type-1 DS2 evidence of GPRS on the requested SIM over a new connection. +The operation has a 360-second bound. Field 72 bits 10/20 prohibit data on the +other SIM; this is not automatic failover. APNs and access credentials are kept +unless explicitly edited. Interrupted writes/restarts are never replayed. +Full cellular-only physical qualification is recorded separately in the ledger. + + +Version 0.1.23 retains the independently registered numeric-ID reply, but removes +the experimental empty settings response: physical 0.1.22 evidence showed an +ID/settings loop, not completion. A settings image is still sent only during +an explicit, bounded write. Startup qualification remains open. + +Version 0.1.22 qualifies the continuous startup exchange: reply with the +independently enrolled numeric device ID, then an empty settings response when +no explicit image write is pending. Numeric IDs are immutable per IMEI and +never inferred from its digits. Unknown IDs and unadmitted peers fail closed. +An explicit pending write retains its single-image dispatch/readback contract. +Physical qualification of the combined exchange is required before publication. + +Version 0.1.21 admits the captured ten-byte command-1 response in a one-shot +engineering lease. Its four-byte payload equals the independently known device +ID. Product behavior is unchanged pending a fresh, unchanged device upload. + +Version 0.1.20 admits one exact empty reply to the observed empty command-1 +request in the engineering observation lease. This follows the physical 2→1 +transition after an empty command-2 reply. No firmware image can be supplied, +and normal product parsing remains closed until the exchange is qualified. + +Version 0.1.19 admits one exact, zero-payload command-2 response only in +the bounded engineering observation lease for no-image-response qualification. +No product-channel behavior changes before physical verification. + +Version 0.1.18 adds an engineering-only binary encoding of the documented +read-only settings upload request (0109), to qualify post-restart behavior. +It does not change the qualified product settings transport or retry writes. + +Version 0.1.17 adds the qualified-model restart request (B2 manual §10, binary +0107). Dispatch expires after three seconds; the request is never replayed. +A token ACK is recorded separately. Only fresh type-1 telemetry measured after +dispatch on a newly opened connection records return, with a 180-second deadline. +This is observed network return, not proof of a hardware power cycle. Old sessions, +archive packets and replies alone cannot complete the operation. + +Version 0.1.16 spaces full-configuration stages and successive operations by +15 seconds after each HTTP image exchange. The bench sometimes ignored a new +SERV request shortly after an upload despite TCP acknowledgment. This pacing +does not affect position/output commands or replay a settings write. + +Version 0.1.15 adds complete configuration reads and profile writes on the +qualified B2 model 231 / firmware 0.01 HTTP settings channel. It reads the +current image before writing, requires an exact predecessor, preserves recovery +channels, sends the image once and verifies by an independent full readback. +Command-5 ACK is the captured seven-byte response with payload 01. Restart or +timeout after dispatch does not silently replay a write. No manufacturer API +is contacted by this runtime. + +Version 0.1.14 chooses the active TCP session with the most recent incoming data +for command dispatch. A half-open predecessor left by a device configuration +reload cannot take a new command while a fresher session exists. It also allows +a bounded engineering upload-ACK qualification using the observed reply-envelope +structure, matching the complete validated upload body. Up to 64 observation +leases are retained (four 16-KiB captures each); raw evidence remains private. + +Version 0.1.13 qualifies the observed configuration reply framing with the +shared B2 CRC/TLV codec. An engineering observation lease can serve a validated +configuration once to a byte-identical admitted B2 settings request. Explicit +close disarms the lease while retaining evidence. This is a real write path: +prepare an exact baseline and rollback image and verify a fresh device upload; +dispatch alone never establishes successful application. No vendor HTTP calls. + +Version 0.1.12 additionally permits the documented `SERV*1.8` configuration +download request for protocol qualification. It can apply a configuration from +the device's configured endpoint; that endpoint must be owned and its payload +qualified before use. The current observation lease serves only a captured +identity answer, never a configuration. No firmware/erase/reset commands exist. + +Version 0.1.11 adds an engineering-only, allowlisted B2 settings upload request +(`SERV*1.9`), preserving active-session expiry and no replay. It also permits one +captured seven-byte configuration identity answer to the exact corresponding +21-byte request, under an authenticated 180-second observation lease. The device +must be admitted; expiry, byte mismatch, duplicate HTTP framing and repeat +dispatch fail closed. This is bounded protocol qualification, not a general +proxy or full configuration support. The service never contacts a vendor. + +Version 0.1.10 adds explicit `set-output` using the B2 manual section 10 FC +command `password*SERV*8.PIN.STATE`. PIN4..6 only, strict boolean `enabled`, +model 231 / firmware 0.01, instance password required. This sets a persistent +output state; it is not a timed pulse or a physical-contact confirmation. +It uses the existing active-session, three-second dispatch expiry and no-replay +contract. Unknown fields and arbitrary commands are rejected. Bench operators +must verify manual output mode and deliberately restore the observed baseline. + +Version 0.1.9 adds the documented FC text encoding for the same bounded +`pulse-output` operation: PIN4..6, 1..5 seconds, model 231 / firmware 0.01. +An explicit `encoding: text` requires the instance's six-digit password; the +generated command remains private. No arbitrary text is accepted. This format +has no token-correlated confirmation: the receipt stays unconfirmed even when +unrelated token or text replies arrive. Dispatch still requires a current +session and expires after three seconds; commands never replay after restart. +A text PIN5 pulse produced an operator- and subsequently camera-observed LED +on/off transition. Earlier binary PIN4/PIN5 pulses had no visible effect. +A token ACK alone is not relay feedback; other outputs require qualification. + +Headless receiver owned by Mission Core, independently of any rover's onboard PC. +Supported installation profile: **Ubuntu Server 24.04 amd64, Python 3.12, +OpenSSL 3, systemd**. Other OS/architectures fail preflight. No pip, Docker, GUI, +Node.js, compiler or vendor cloud is required. Minimal images missing OS +prerequisites are rejected with the missing capability; no blind system repair. + +## Reproduce + +From this repository: + +```sh +.venv/bin/python scripts/build_vps_host.py --output /tmp/ndc-mission-vps.tar +``` + +The builder produces both a `.tar` engineering archive and a single `.pyz` +operator installer. Mission Core serves an explicitly published, checksum-verified +`.pyz` in Equipment → root plus → VPS Host ARNavi. The same window contains the +supported OS, installation instructions and pairing-key field. The installer +carries no tracker identities, SIM data, address, keys or private evidence. + +Copy the downloaded file to the VPS and run: + +```sh +sudo python3 ndc-mission-vps.pyz --host trackers.example.org +``` + +Use the actual downloaded filename. Omitting `--host` prompts for the public +address. The wrapper runs the same preflight/plan/apply engine, with an exact +plan digest; it does not require a separate installer GUI. The engineering tar +retains the explicit plan/apply interface: + +```sh +python3 ndc-mission-vps/install.py plan --host trackers.example.org +python3 ndc-mission-vps/install.py apply --host trackers.example.org --expect PLAN_SHA256 +``` + +Run apply as root. The exact current plan hash is required. DNS/IP is an install +parameter, never source code. Use stable DNS so a VPS migration does not require +rewriting thousands of trackers. Default ports: TCP 9922 (B2 INTERNAL), TLS 19443 +(Mission Core). Cloud firewall must allow these exact ports. The installer preserves existing services, including DeviceCore on 443/9921. +For the detected legacy NODE.DC `nodedc_b2_vps` nftables policy it adds two +comment-owned allow rules and a persistent include, checks predecessor hashes, +and records a bounded rollback. It never flushes rules. Unknown firewall +policies remain external and require public endpoint acceptance. +Existing listener/foreign installation conflicts stop first install. + +Installation paths: + +- `/opt/nodedc-mission-vps/current`: immutable release selected by content digest. +- **`/opt/nodedc-mission-vps/connect.key`**: fixed root-level pairing file, + symlink to protected state; read as root. +- `/var/lib/ndc-mission-vps`: host identity, TLS key, owner and durable journal, + mode 0700, files 0600, owned by dedicated system user `ndc-mission-vps`. +- `/etc/systemd/system/ndc-mission-vps.service`: versioned managed system unit. + +Open an apparatus → Equipment → top plus → VPS Host ARNavi. Paste the key, choose a +name and served apparatuses. It expires after 24 hours and is consumed once. +The same VPS appears under every assigned rover. To attach an existing VPS to +another rover, choose it in the connection dialog, or change the host's apparatus +list in settings. One host retains one identity and one Mission Core owner. + +An unused expired key can be renewed with the shipped CLI: + +```sh +cd /opt/nodedc-mission-vps/current +sudo -u ndc-mission-vps /usr/bin/python3 -m ndc_vps invitation +``` + +Paired hosts cannot silently regenerate/reassign ownership. Back up the whole +private state directory and Mission Core fleet state. A new host has a new key. +An update retains the same identity and queue. Applying the current release is +a health-checking no-op. Failed updates restore the previous release and unit. +Explicit rollback preserves private state and the journal: + +```sh +python3 ndc-mission-vps/install.py rollback --host trackers.example.org --expect INSTALLED_ARTIFACT_DIGEST +``` + +For the first release rollback disables the new service; it does not delete +identities, evidence or any unrelated service. Schema v1 updates are additive; +a future incompatible migration must supply its own reversible migration. + +## Clean product reinstallation + +```sh +sudo python3 ndc-mission-vps.pyz --host trackers.example.org --fresh +``` + +This explicitly replaces this product's installation and identity. First the +installer stops its own unit and creates a private, hash-recorded backup under +`/var/backups/ndc-mission-vps/`. It preserves original application/state trees, +then installs empty product state and creates a new pairing key. A failed fresh +installation restores the backup and health-checks the old service. Foreign +services and unrelated files are preserved. This is not an OS reimage. + +In the Core admission form select the previous record under «После переустановки» +and paste the new key. Replacement is explicit: duplicate live host records at +the same endpoint are refused. The former record and telemetry journal remain +in private history; only the newly paired identity is synchronized. + +To restore a selected backup with the same installer: + +```sh +sudo python3 ndc-mission-vps.pyz --host trackers.example.org --restore /var/backups/ndc-mission-vps/BACKUP_ID +``` + +After a successful new pairing, restoring the server alone does not restore the +Core's host registration. Restore a matching private Core fleet backup as part +of disaster recovery; do not substitute identities or disclose tokens manually. + +## Publish qualified downloads + +The operator runtime keeps installers under its private fleet root, outside Git. +Publishing a release only changes the download; it never installs on a board or +VPS. Run the publisher with the exact SHA from the accepted build receipt: + +```sh +.venv/bin/python scripts/publish_fleet_installer.py \ + --fleet-root /path/to/operator/fleet --kind vps-arnavi \ + --file /path/to/qualified-vps.pyz --version 0.1.3 --sha256 ACCEPTED_SHA256 +``` + +For the onboard computer use `--kind node` and the version/SHA of the already +qualified owner installer. Copy the finished installer back from the build host +before publishing it. A source-build bundle is not an owner installer. Publishing +the Node archive does not update the board. Catalog and download endpoints verify +size and SHA; a missing or changed archive is unavailable instead of silently +falling back to an older build. + +## Tracker admission and delivery + +Register/read a B2 over USB in Mission Core, select the registered VPS in its +connection settings, save, then apply over USB. Slot 2 is initially proposed to +preserve an existing slot 1. Profiles contain common settings, not IMEI/ICCID, +SIM phone number or assignment. Firmware-qualified writer performs backup, +identity/config preconditions, acknowledgement and independent readback. + +Core synchronizes an allowlist of registered IMEIs assigned to that host's +apparatuses and configured endpoint. Unknown devices receive no telemetry ACK. +**IMEI is a claimed identity, not cryptographic tracker authentication**: legacy +INTERNAL is plaintext. For untrusted deployments use an operator private APN or +network protection; this release does not claim end-to-end tracker encryption. + +VPS ACKs a B2 package only after a SQLite FULL commit. Core pulls a bounded batch, +stores raw evidence, derives valid coordinates and advances its cursor in the +same transaction, then acknowledges the VPS queue. Replays are idempotent; +package sequence reuse cannot replace content. Header-time and package ACKs +follow the published INTERNAL framing. No arbitrary tracker command API exists. + +The authenticated VPS API also qualifies the allowlisted, read-only `GETP` +command over an existing tracker TCP session. Commands have durable IDs and +bounded expiry; a dispatched command is never automatically replayed after a +restart. A text response means `reply_received`, not «settings applied». +Version 0.1.6 adds the bounded `configure-server1` operation for B2 model 231 / +firmware 0.01. Fresh GETP must match the expected primary endpoint and show this +VPS as the secondary server. Only documented SETP #1 host/port is changed; a +separate GETP must verify the endpoint and preservation of every other group. +Operations bind to one TCP session, reject stale/duplicate responses, expire +after 120 seconds and never replay writes after restart. Reversal is a separate +preconditioned operation. FC has no correlation token: timestamp/session checks +bound freshness but do not create cryptographic command attribution. +Device clock skew is bounded to 10 seconds behind / 5 seconds ahead of VPS time; +successive operation stages require strictly increasing device timestamps. +After a dispatched SETP the host waits at least 15 seconds before its separate +GETP. Only this read may bind to a new TCP session after tracker reconnection; +SET P is never resent. Verification also runs when SETP's acknowledgement is lost. +The 0.1.4 experiment stopped before writing because its timestamp comparison +incorrectly required synchronized clocks; the measured B2 was about 4 s behind. + +Full profiles, APN/active-channel migration, other server slots and disabling the +vendor configurator remain unqualified. The authenticated API is private: raw +GETP replies contain credentials and must never be proxied into the browser. +See [network configuration audit](../../docs/arnavi_b2/NETWORK_CONFIGURATION.md). + +The VPS queue has a 512 MiB budget and preserves a 256 MiB disk reserve. When +full/unwritable it withholds ACK, never drops unconsumed packages. Receipts retain +retransmission deduplication for seven days. Core must remain available often +enough to drain the queue. Capacity for thousands of simultaneously active +trackers has **not** been load-qualified; the first profile caps 256 connections +and service memory at 192 MiB. Scale/retention qualification is a separate gate. + +Core API uses TLS 1.3 with certificate fingerprint verified **before** sending a +pairing secret or bearer token. Invitation is obtained through the owner's SSH +channel. DNS resolves only to public IPv4. Redirects/ambient HTTP proxies are +not followed. Node's private-network pairing contract is unchanged. + +Coordinates are derived from valid packet tags. Missing/invalid/zero coordinates +are not invented. Device measurement time and reception time remain separate; +an older replay cannot move the map backwards in time. UI shows freshness and +last contact, independently of the onboard computer. + +## Acceptance boundary + +`tests/test_vps_host.py` covers framing, partial TCP reads, checksum rejection, +one-time enrollment, retry identity, admission, durable delivery, deduplication, +Core cursor transaction, stale data and shared rover reassignment. Hardware and +operator VPS acceptance are recorded separately in a private deployment ledger. +A successful install on the existing Ubuntu VPS is not clean-image qualification. + +## Portable transfer to a clean VPS + +Use the same qualified installer file on both hosts. Upgrade the source to it +first. Then on the source: + +```sh +sudo python3 ndc-mission-vps.pyz --export-state /root/mission-vps-state.tar.gz +``` + +This stops this service and persistently fences it before taking the snapshot. +The source remains stopped, including after reboot. Export prints the archive's +SHA-256. The archive contains credentials and the SQLite journal: keep it private +and transfer it through the owner's SSH channel together with the installer. +No executable, system unit, account ID or firewall configuration crosses hosts. +A failure after fencing leaves the source stopped and preserves its state. + +On the clean supported Ubuntu VPS: + +```sh +sudo python3 ndc-mission-vps.pyz --import-state /root/mission-vps-state.tar.gz --sha256 ARCHIVE_SHA256 +``` + +Import checks the exact archive SHA, complete file manifest, matching installer +release, TLS key/certificate identity and SQLite integrity before installation. +Existing product paths are refused. It creates the system account, code and unit +through the same installer and verifies service health. TLS identity and Core +pairing survive; commands retain IDs, attempts, deadlines and stop markers. +The normal runtime reconciles interrupted attempts; a snapshot is not proof of +tracker execution. No old live TCP session is restored. + +Keep the existing DNS name and ports, then direct that DNS name to the target +after its health and external reachability checks. For an endpoint configured +as a literal IP, this operation alone does not migrate Core or tracker addresses; +a transferable IP or a separately verified endpoint change is required. Provider +firewalls and DNS changes require their owner's controls/API and are not inferred +from guest installation success. The receiving installation needs 2.25 GiB of +free staging space; portable state is capped at 2 GiB. + +To abandon migration, **stop the target first**, then explicitly resume the source: + +```sh +sudo python3 ndc-mission-vps.pyz --resume-source +``` + +The source cannot observe the target across an outage. The installer therefore +never resumes it automatically. Retain the private archive and exact installer +for recovery. Do not run both identities simultaneously. A stale archive also +cannot contain commands or confirmations recorded after its snapshot. diff --git a/apps/vps-host/firewall.py b/apps/vps-host/firewall.py new file mode 100644 index 00000000..044a69c7 --- /dev/null +++ b/apps/vps-host/firewall.py @@ -0,0 +1,95 @@ +"""Bounded migration of the observed NODE.DC B2 nftables policy; no flush.""" + +import hashlib +import json +import subprocess +from pathlib import Path + +CONFIG = Path("/etc/nftables.conf") +FRAGMENT = Path("/etc/nftables.d/ndc-mission-vps.nft") +BACKUP = Path("/opt/nodedc-mission-vps/firewall-before.json") +INCLUDE = 'include "/etc/nftables.d/ndc-mission-vps.nft"' +MARKER = "ndc-mission-vps-v1" + + +def run(*args, **kwargs): + return subprocess.run(args, check=True, capture_output=True, **kwargs) + + +def plan(): + if not CONFIG.exists() or "table inet nodedc_b2_vps" not in CONFIG.read_text(): + # A clean host can use its own provider firewall. Unknown local policies + # are not rewritten; public endpoint acceptance remains mandatory. + return {"mode": "external", "config_sha256": None} + live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout) + chain = next(x["chain"] for x in live["nftables"] if "chain" in x) + if chain.get("policy") != "drop" or chain.get("hook") != "input": + raise ValueError("unsupported legacy firewall policy") + if FRAGMENT.exists() and MARKER not in FRAGMENT.read_text(): + raise ValueError("foreign firewall fragment conflict") + return { + "mode": "nodedc-b2-v1", + "config_sha256": hashlib.sha256(CONFIG.read_bytes()).hexdigest(), + } + + +def rules(api, tracker): + return ( + f"add rule inet nodedc_b2_vps input tcp dport {api} ct state new " + f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-api"\n' + f"add rule inet nodedc_b2_vps input tcp dport {tracker} ct state new " + f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-tracker"\n' + ) + + +def removal(): + live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout) + commands = [] + for item in live["nftables"]: + rule = item.get("rule", {}) + if rule.get("comment") in (MARKER + "-api", MARKER + "-tracker"): + commands.append(f"delete rule inet nodedc_b2_vps input handle {int(rule['handle'])}\n") + return "".join(commands) + + +def apply(proposal, api, tracker, atomic): + if proposal["mode"] != "nodedc-b2-v1": + return False + if plan() != proposal: + raise ValueError("firewall changed after plan") + content = rules(api, tracker) + if INCLUDE in CONFIG.read_text(): + if not FRAGMENT.exists() or FRAGMENT.read_text() != content: + raise ValueError("managed firewall drift") + # Reconcile only our named live rules if nftables was reloaded. + run("nft", "-f", "-", input=(removal() + content).encode()) + return False + original = CONFIG.read_text() + desired = original.rstrip() + "\n\n" + INCLUDE + "\n" + backup = { + "before": original, + "after_sha256": hashlib.sha256(desired.encode()).hexdigest(), + "fragment_sha256": hashlib.sha256(content.encode()).hexdigest(), + } + atomic(BACKUP, json.dumps(backup).encode()) + FRAGMENT.parent.mkdir(mode=0o755, exist_ok=True) + # Validate the live transaction before modifying persistent files. + run("nft", "-c", "-f", "-", input=(removal() + content).encode()) + atomic(FRAGMENT, content.encode(), 0o644) + atomic(CONFIG, desired.encode(), 0o644) + run("nft", "-f", "-", input=(removal() + content).encode()) + return True + + +def rollback(atomic): + record = json.loads(BACKUP.read_text()) + if ( + hashlib.sha256(CONFIG.read_bytes()).hexdigest() != record["after_sha256"] + or hashlib.sha256(FRAGMENT.read_bytes()).hexdigest() != record["fragment_sha256"] + ): + raise ValueError("firewall changed; rollback will not overwrite foreign edits") + commands = removal() + if commands: + run("nft", "-f", "-", input=commands.encode()) + atomic(CONFIG, record["before"].encode(), 0o644) + FRAGMENT.unlink() diff --git a/apps/vps-host/install.py b/apps/vps-host/install.py new file mode 100644 index 00000000..305288d3 --- /dev/null +++ b/apps/vps-host/install.py @@ -0,0 +1,429 @@ +#!/usr/bin/env python3 +"""Versioned Ubuntu 24.04 amd64 installer. Run plan, then apply its exact digest.""" + +import argparse +import hashlib +import json +import os +import platform +import pwd +import re +import shutil +import socket +import ssl +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import firewall + +ROOT = Path("/opt/nodedc-mission-vps") +STATE = Path("/var/lib/ndc-mission-vps") +UNIT = Path("/etc/systemd/system/ndc-mission-vps.service") +USER = "ndc-mission-vps" +SOURCE = Path(__file__).resolve().parent +SERVICE = """# Managed by NODE.DC Mission VPS installer v1 +[Unit] +Description=NODE.DC Mission VPS Host +After=network-online.target +Wants=network-online.target +ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json +[Service] +Type=simple +User=ndc-mission-vps +Group=ndc-mission-vps +WorkingDirectory=/opt/nodedc-mission-vps/current +ExecStart=/usr/bin/python3 -m ndc_vps serve +Restart=on-failure +RestartSec=5 +UMask=0077 +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +ReadWritePaths=/var/lib/ndc-mission-vps +MemoryMax=192M +TasksMax=96 +LimitNOFILE=2048 +[Install] +WantedBy=multi-user.target +""" + + +def run(*args, **kwargs): + return subprocess.run(args, check=True, capture_output=True, **kwargs) + + +def digest(): + manifest = json.loads((SOURCE / "manifest.json").read_text()) + for name, expected in manifest["files"].items(): + if name.startswith("/") or ".." in Path(name).parts: + raise ValueError("invalid manifest") + if hashlib.sha256((SOURCE / name).read_bytes()).hexdigest() != expected: + raise ValueError("artifact integrity mismatch") + return hashlib.sha256((SOURCE / "manifest.json").read_bytes()).hexdigest() + + +def predecessor(): + return os.readlink(ROOT / "current") if (ROOT / "current").is_symlink() else None + + +def plan(args): + osrelease = dict( + line.split("=", 1) + for line in Path("/etc/os-release").read_text().splitlines() + if "=" in line + ) + if ( + osrelease.get("ID", "").strip('"') != "ubuntu" + or osrelease.get("VERSION_ID", "").strip('"') != "24.04" + or platform.machine() != "x86_64" + ): + raise ValueError("supported environment: Ubuntu Server 24.04 amd64 only") + if sys.version_info[:2] != (3, 12): + raise ValueError("Python 3.12 required") + for command in ("openssl", "systemctl", "useradd", "runuser"): + if not shutil.which(command): + raise ValueError("missing OS prerequisite: " + command) + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,48}", args.host): + raise ValueError("public DNS name or IPv4 required (max 49 characters for B2)") + if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text(): + raise ValueError("foreign service conflict") + if ROOT.exists() and not (ROOT / "installed.json").exists(): + raise ValueError("foreign installation root conflict") + if STATE.exists() and not (STATE / "host.json").exists(): + raise ValueError("foreign state directory conflict") + if (ROOT / "migration-fence.json").exists(): + raise ValueError("source fenced for migration; resume explicitly only with target stopped") + old = predecessor() + for port in (args.api_port, args.tracker_port): + if port < 1024 or port > 65535: + raise ValueError("ports must be 1024..65535") + if not old: + with socket.socket() as sock: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("0.0.0.0", port)) + if args.api_port == args.tracker_port: + raise ValueError("ports must differ") + configuration = { + "public_host": args.host, + "api_port": args.api_port, + "tracker": {"host": args.host, "port": args.tracker_port}, + } + if STATE.exists(): + existing = json.loads((STATE / "host.json").read_text()) + if any(existing[key] != val for key, val in configuration.items()): + raise ValueError( + "endpoint migration requires a separate planned operation; use stable DNS" + ) + data = { + "schema": "missioncore.vps-install-plan/v1", + "firewall": firewall.plan(), + "artifact": digest(), + "previous": old, + "configuration": configuration, + "unit_sha256": hashlib.sha256(UNIT.read_bytes()).hexdigest() if UNIT.exists() else None, + "environment": "ubuntu-24.04-amd64", + "service": str(UNIT), + "root": str(ROOT), + "key_file": str(ROOT / "connect.key"), + } + data["plan_sha256"] = hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest() + return data + + +def atomic(path, value, mode=0o600): + temporary = path.with_name(path.name + ".new") + temporary.write_bytes(value) + temporary.chmod(mode) + os.replace(temporary, path) + + +def select_release(release): + temporary = ROOT / ".current" + temporary.unlink(missing_ok=True) + temporary.symlink_to(release) + os.replace(temporary, ROOT / "current") + + +def healthy(): + for _ in range(20): + if subprocess.run(["systemctl", "is-active", "--quiet", "ndc-mission-vps"]).returncode == 0: + try: + config = json.loads((STATE / "host.json").read_text()) + ctx = ssl.create_default_context(cafile=str(STATE / "tls.crt")) + ctx.check_hostname = False + with ( + socket.create_connection(("127.0.0.1", config["api_port"]), 2) as sock, + ctx.wrap_socket(sock) as secure, + ): + secure.sendall(b"GET /health HTTP/1.1\r\nHost: localhost\r\n\r\n") + if b"200 Result" in secure.recv(4096): + return + except OSError: + pass + time.sleep(0.5) + raise ValueError("service health check failed") + + +def apply(args, proposal): + if os.geteuid() != 0 or args.expect != proposal["plan_sha256"]: + raise ValueError("root and exact current plan digest required") + old = proposal["previous"] + installed = ROOT / "installed.json" + if ( + old + and Path(old).name == proposal["artifact"] + and installed.exists() + and json.loads(installed.read_text()).get("status") == "healthy" + ): + healthy() + print(json.dumps({"status": "already_current", "artifact": proposal["artifact"]})) + return + release = ROOT / "releases" / proposal["artifact"] + ROOT.mkdir(mode=0o755, exist_ok=True) + (ROOT / "releases").mkdir(mode=0o755, exist_ok=True) + # mkdir's mode is filtered by the caller's umask. The unprivileged service + # must traverse these owned code directories even under root's umask 0077. + ROOT.chmod(0o755) + (ROOT / "releases").chmod(0o755) + old_unit = UNIT.read_bytes() if UNIT.exists() else None + # Pre-create the ownership record: a failed first install can be inspected/retried. + if not (ROOT / "installed.json").exists(): + atomic( + ROOT / "installed.json", + json.dumps({"schema": "missioncore.vps-install/v1", "status": "preparing"}).encode(), + ) + try: + pwd.getpwnam(USER) + except KeyError: + run("useradd", "--system", "--home-dir", str(STATE), "--shell", "/usr/sbin/nologin", USER) + user = pwd.getpwnam(USER) + if not release.exists(): + shutil.copytree(SOURCE, release, ignore=shutil.ignore_patterns("__pycache__")) + release.chmod(0o755) + for item in release.rglob("*"): + item.chmod(0o755 if item.is_dir() else 0o644) + if not STATE.exists(): + STATE.mkdir(mode=0o700) + configuration = proposal["configuration"].copy() + run( + "openssl", + "req", + "-x509", + "-newkey", + "ed25519", + "-nodes", + "-days", + "3650", + "-subj", + "/CN=NODE.DC Mission VPS Host", + "-keyout", + str(STATE / "tls.key"), + "-out", + str(STATE / "tls.crt"), + ) + certificate = ssl.PEM_cert_to_DER_cert((STATE / "tls.crt").read_text()) + fingerprint = hashlib.sha256(certificate).hexdigest() + configuration.update( + fingerprint=fingerprint, + host_id="vps_" + fingerprint, + endpoint=f"https://{args.host}:{args.api_port}", + ) + atomic(STATE / "host.json", json.dumps(configuration, indent=2).encode()) + os.chown(STATE, user.pw_uid, user.pw_gid) + for item in STATE.iterdir(): + item.chmod(0o600) + os.chown(item, user.pw_uid, user.pw_gid) + if not (ROOT / "connect.key").is_symlink(): + (ROOT / "connect.key").symlink_to(STATE / "connect.key") + firewall_added = False + try: + firewall_added = firewall.apply( + proposal["firewall"], args.api_port, args.tracker_port, atomic + ) + select_release(release) + if not (STATE / "connect.key").exists(): + run( + "runuser", + "-u", + USER, + "--", + "/usr/bin/python3", + "-m", + "ndc_vps", + "invitation", + cwd=release, + ) + atomic(UNIT, SERVICE.encode(), 0o644) + run("systemctl", "daemon-reload") + run("systemctl", "enable", "ndc-mission-vps.service") + run("systemctl", "restart", "ndc-mission-vps.service") + healthy() + atomic( + ROOT / "installed.json", + json.dumps( + { + **proposal, + "status": "healthy", + "firewall_added": firewall_added, + "installed_at": time.time(), + }, + indent=2, + ).encode(), + ) + print( + json.dumps( + { + "status": "healthy", + "artifact": proposal["artifact"], + "key_file": str(ROOT / "connect.key"), + } + ) + ) + except Exception: + if firewall_added: + firewall.rollback(atomic) + if old: + select_release(old) + if old_unit: + atomic(UNIT, old_unit, 0o644) + run("systemctl", "daemon-reload") + run("systemctl", "restart", "ndc-mission-vps.service") + healthy() + else: + subprocess.run( + ["systemctl", "disable", "--now", "ndc-mission-vps.service"], capture_output=True + ) + raise + + +def rollback(args): + record = json.loads((ROOT / "installed.json").read_text()) + if os.geteuid() != 0 or args.expect != record["artifact"]: + raise ValueError("root and installed artifact digest required") + if record.get("firewall_added"): + firewall.rollback(atomic) + previous = record["previous"] + if previous: + path = Path(previous) + if path.parent != ROOT / "releases" or not path.is_dir(): + raise ValueError("previous release unavailable") + select_release(path) + run("systemctl", "restart", "ndc-mission-vps.service") + healthy() + else: + run("systemctl", "disable", "--now", "ndc-mission-vps.service") + # Preserve state, keys and journal even when uninstalling the first release. + atomic(ROOT / "installed.json", json.dumps({**record, "status": "rolled_back"}).encode()) + print(json.dumps({"status": "rolled_back", "state_preserved": True})) + + +BACKUPS = Path("/var/backups/ndc-mission-vps") + + +def restore(backup): + if os.geteuid() != 0 or backup.parent != BACKUPS or backup.is_symlink(): + raise ValueError("root and an installer-owned backup required") + if (ROOT / "migration-fence.json").exists(): + raise ValueError("source fenced for migration") + record = json.loads((backup / "backup.json").read_text()) + if record.get("schema") != "missioncore.vps-backup/v1": + raise ValueError("invalid backup") + # Verify before stopping anything. Never overwrite a foreign service. + if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text(): + raise ValueError("foreign service conflict") + for name, expected in record["files"].items(): + file = backup / name + if ".." in Path(name).parts or file.is_symlink(): + raise ValueError("invalid backup file") + if hashlib.sha256(file.read_bytes()).hexdigest() != expected: + raise ValueError("backup integrity mismatch") + run("systemctl", "stop", "ndc-mission-vps.service") + recovery = backup / ("replaced-" + uuid.uuid4().hex) + recovery.mkdir(mode=0o700) + for name, target in (("root", ROOT), ("state", STATE), ("unit", UNIT)): + if target.exists(): + shutil.move(str(target), recovery / name) + source = backup / name + if source.is_dir(): + shutil.copytree(source, target, symlinks=True) + else: + shutil.copy2(source, target) + user = pwd.getpwnam(USER) + os.chown(STATE, user.pw_uid, user.pw_gid) + for file in STATE.iterdir(): + os.chown(file, user.pw_uid, user.pw_gid) + run("systemctl", "daemon-reload") + run("systemctl", "enable", "ndc-mission-vps.service") + run("systemctl", "restart", "ndc-mission-vps.service") + healthy() + print(json.dumps({"status": "restored", "backup": str(backup)})) + + +def fresh(args, proposal): + if os.geteuid() != 0 or args.expect != proposal["plan_sha256"] or not proposal["previous"]: + raise ValueError("fresh replacement requires an exact plan of an installed product") + BACKUPS.mkdir(mode=0o700, parents=True, exist_ok=True) + backup = BACKUPS / (time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + "-" + uuid.uuid4().hex[:8]) + backup.mkdir(mode=0o700) + run("systemctl", "stop", "ndc-mission-vps.service") + try: + for name, path in (("root", ROOT), ("state", STATE)): + shutil.copytree(path, backup / name, symlinks=True) + shutil.copy2(UNIT, backup / "unit") + files = { + str(p.relative_to(backup)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in backup.rglob("*") + if p.is_file() and not p.is_symlink() + } + atomic( + backup / "backup.json", + json.dumps( + { + "schema": "missioncore.vps-backup/v1", + "created_at": time.time(), + "monotonic": time.monotonic(), + "files": files, + } + ).encode(), + ) + except Exception: + run("systemctl", "start", "ndc-mission-vps.service") + raise + try: + # Complete verified private copy exists; move original trees too, never wildcard-delete. + shutil.move(str(ROOT), backup / "original-root") + shutil.move(str(STATE), backup / "original-state") + shutil.move(str(UNIT), backup / "original-unit") + new_plan = plan(args) + args.expect = new_plan["plan_sha256"] + apply(args, new_plan) + except Exception: + restore(backup) + raise + print(json.dumps({"status": "fresh_install", "backup": str(backup)})) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=("plan", "apply", "rollback")) + parser.add_argument("--host", required=True) + parser.add_argument("--api-port", type=int, default=19443) + parser.add_argument("--tracker-port", type=int, default=9922) + parser.add_argument("--expect") + args = parser.parse_args() + try: + if args.action == "rollback": + rollback(args) + else: + proposal = plan(args) + if args.action == "plan": + print(json.dumps(proposal, indent=2)) + else: + apply(args, proposal) + except Exception as error: + print("Installation stopped: " + str(error), file=sys.stderr) + sys.exit(1) diff --git a/apps/vps-host/ndc_vps/__init__.py b/apps/vps-host/ndc_vps/__init__.py new file mode 100644 index 00000000..3bbf8cae --- /dev/null +++ b/apps/vps-host/ndc_vps/__init__.py @@ -0,0 +1,3 @@ +"""Headless NODE.DC Mission VPS Host; Python 3.12 standard library only.""" + +VERSION = "0.1.41" diff --git a/apps/vps-host/ndc_vps/__main__.py b/apps/vps-host/ndc_vps/__main__.py new file mode 100644 index 00000000..946b67e7 --- /dev/null +++ b/apps/vps-host/ndc_vps/__main__.py @@ -0,0 +1,19 @@ +import argparse +import asyncio +import json + +from .service import Service +from .store import Store + +parser = argparse.ArgumentParser() +parser.add_argument("action", choices=("serve", "invitation", "status")) +parser.add_argument("--state", default="/var/lib/ndc-mission-vps") +args = parser.parse_args() +store = Store(args.state) +if args.action == "serve": + asyncio.run(Service(store).run()) +elif args.action == "invitation": + store.invitation() + print("Invitation ready in /opt/nodedc-mission-vps/connect.key (valid 24 hours).") +else: + print(json.dumps(store.status())) diff --git a/apps/vps-host/ndc_vps/actions.py b/apps/vps-host/ndc_vps/actions.py new file mode 100644 index 00000000..b45d98f4 --- /dev/null +++ b/apps/vps-host/ndc_vps/actions.py @@ -0,0 +1,120 @@ +"""B2 manual §10 + INTERNAL SERVER_COM token envelope; no arbitrary commands.""" + +import re +import secrets + +KINDS = { + "request-position", + "restart", + "pulse-output", + "set-output", + "upload-configuration", + "download-configuration", + "probe-diagnostic-mode", +} + + +def prepare(body): + if body.get("model") != 231 or body.get("firmware") != "0.01": + raise ValueError("unqualified action firmware") + allowed = {"id", "imei", "kind", "model", "firmware"} + if body["kind"] == "probe-diagnostic-mode": + # INTERNAL SERVER_COM 01 00. Engineering qualification only: neither + # a SIM read nor a promise about this firmware's mode/termination. + # Admission additionally requires an explicit live observation lease. + allowed.add("observation_id") + if not isinstance(body.get("observation_id"), str) or not re.fullmatch( + r"[a-f0-9]{32}", body["observation_id"] + ): + raise ValueError("diagnostic probe requires observation") + command = b"\x01\x00" + elif body["kind"] == "request-position": + command = b"\x01\x01" + elif body["kind"] == "restart": + # B2 manual §10. A token receipt is not proof of a completed restart. + command = b"\x01\x07" + elif body["kind"] == "upload-configuration" and body.get("encoding") == "binary": + # Documented read-only counterpart to SERV*1.9; no image is written. + allowed.add("encoding") + command = b"\x01\x09" + elif body["kind"] in ("upload-configuration", "download-configuration"): + allowed.add("password") + password = body.get("password") + if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password): + raise ValueError("invalid password") + if set(body) - allowed: + raise ValueError("unknown action fields") + # B2 manual §10: synchronize with the configured web endpoint. Download + # may apply settings: the endpoint owns staged data and readback checks. + number = 9 if body["kind"] == "upload-configuration" else 8 + return {"encoding": "text", "binary": f"{password}*SERV*1.{number}".encode().hex()} + elif body["kind"] == "set-output": + allowed |= {"pin", "enabled", "encoding", "password"} + pin = body.get("pin") + enabled = body.get("enabled") + if type(pin) is not int or pin not in (4, 5, 6): + raise ValueError("unsupported output") + if type(enabled) is not bool: + raise ValueError("enabled must be boolean") + if body.get("encoding", "text") != "text": + raise ValueError("set-output requires text encoding") + password = body.get("password") + if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password): + raise ValueError("invalid password") + if set(body) - allowed: + raise ValueError("unknown action fields") + # B2 manual section 10: explicit, persistent low-side output state. + # The caller must request both transitions; there is no implicit retry. + return { + "encoding": "text", + "binary": f"{password}*SERV*8.{pin}.{int(enabled)}".encode("ascii").hex(), + } + elif body["kind"] == "pulse-output": + allowed |= {"pin", "seconds", "encoding"} + pin, seconds = body["pin"], body["seconds"] + if type(pin) is not int or pin not in (4, 5, 6): + raise ValueError("unsupported output") + if type(seconds) is not int or not 1 <= seconds <= 5: + raise ValueError("pulse must be 1..5 seconds") + command = bytes((0x18, pin, 0, seconds)) + encoding = body.get("encoding", "binary") + if encoding not in ("binary", "text"): + raise ValueError("unsupported action encoding") + if encoding == "text": + allowed.add("password") + password = body.get("password") + if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password): + raise ValueError("invalid password") + if set(body) - allowed: + raise ValueError("unknown action fields") + # B2 manual §10: FC text has no token envelope. A reply to an + # unrelated command must never turn this into confirmed actuation. + return { + "encoding": "text", + "binary": f"{password}*SERV*24.{pin}.0.{seconds}".encode("ascii").hex(), + } + else: + raise ValueError("unsupported action") + if set(body) - allowed: + raise ValueError("unknown action fields") + result = {"token": secrets.randbits(32), "binary": command.hex()} + if body["kind"] == "probe-diagnostic-mode": + result["observation_id"] = body["observation_id"] + return result + + +def frame(value): + if value.get("encoding") == "text": + raw = bytes.fromhex(value["binary"]) + return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}" + raw = b"\xff" + value["token"].to_bytes(4, "little") + bytes.fromhex(value["binary"]) + return bytes((0x7B, len(raw), 0xFF, sum(raw) % 256)) + raw + b"}" + + +def confirmations(raw): + offset = 2 + while offset < len(raw) - 1: + size = int.from_bytes(raw[offset + 1 : offset + 3], "little") + if raw[offset] == 9 and size == 5: + yield raw[offset + 7], int.from_bytes(raw[offset + 8 : offset + 12], "little") + offset += size + 8 diff --git a/apps/vps-host/ndc_vps/commands.py b/apps/vps-host/ndc_vps/commands.py new file mode 100644 index 00000000..407b0cca --- /dev/null +++ b/apps/vps-host/ndc_vps/commands.py @@ -0,0 +1,585 @@ +"""Durable allowlisted B2 operations; no firmware or arbitrary text commands.""" + +import hashlib +import json +import math +import re +import time + +from . import actions, configuration, full_configuration, restart, sim_guard, sim_selection +from .delivery import MAX_DELIVERY_SECONDS +from .observation import Observation +from .transport_evidence import TransportEvidence +from .web_protocol import decode_request, numeric_id_reply, time_reply + +COMMAND_SESSION_MAX_IDLE = 5 +CONFIGURATION_KINDS = full_configuration.KINDS | { + "read-settings", + "configure-server1", + "upload-configuration", + "download-configuration", +} + + +def frame(text): + raw = text.encode("cp1251") + if not 1 <= len(raw) <= 255: + raise ValueError("command length") + return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}" + + +class Commands: + def __init__(self, store): + self.store = store + self.transport = TransportEvidence(store) + self.sim_guard = sim_guard.SimGuard(store) + self.sessions = {} + self.session_started = {} + self.session_activity = {} + self.session_peers = {} + self.session_ready = {} + with store.db() as db: + db.execute( + "CREATE TABLE IF NOT EXISTS commands(id TEXT PRIMARY KEY, imei TEXT NOT NULL, " + "digest TEXT NOT NULL, body TEXT NOT NULL)" + ) + db.execute( + "CREATE INDEX IF NOT EXISTS commands_active " + "ON commands(imei,json_extract(body,'$.state'))" + ) + # Effectful stages never replay. A committed full-image write may + # resume its independent readback within the original deadline. + for identifier, body in db.execute( + "SELECT id,body FROM commands " + "WHERE json_extract(body,'$.state') IN ('queued','dispatched')" + ).fetchall(): + value = json.loads(body) + value = self.settle(db, identifier, value) + if self.verification_recoverable(value): + self.recover_verification(value) + db.execute( + "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) + ) + elif ( + value["kind"] in actions.KINDS - {"request-position"} + and value["state"] == "queued" + ): + value.update(state="expired", reason="host_restarted") + db.execute( + "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) + ) + elif ( + value["state"] == "dispatched" + or value.get("stage") in ("write", "verify", "restart") + and value["state"] == "queued" + ): + value.update(state="uncertain", reason="host_restarted") + db.execute( + "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) + ) + + @staticmethod + def verification_recoverable(value): + return ( + value["kind"] == "configure-all" + and value.get("stage") == "verify" + and bool(value.get("write_reply_sent_at")) + and value["state"] in ("queued", "dispatched") + ) + + @staticmethod + def recover_verification(value): + value.update( + state="queued", + recovery_verification=True, + recovery_at=time.time(), + recovery_count=value.get("recovery_count", 0) + 1, + not_before=max(value.get("not_before", 0), value.get("dispatched_at", 0) + 15), + ) + value.pop("session", None) + + def submit(self, body): + # The original absolute deadline survives a lost HTTP reply and retry. + # Keep it in the idempotency digest, outside the device command payload. + original = body + body = dict(body) + not_after = body.pop("not_after", None) + if not_after is not None and ( + type(not_after) not in (int, float) or not math.isfinite(not_after) or not_after <= 0 + ): + raise ValueError("invalid command deadline") + identifier, imei = body["id"], body["imei"] + kind = body["kind"] + password = body.get("password", "") + if ( + not re.fullmatch(r"[a-f0-9]{32}", identifier) + or kind + not in actions.KINDS | full_configuration.KINDS | {"read-settings", "configure-server1"} + or not self.store.admitted(imei) + ): + raise ValueError("unsupported command") + if kind not in actions.KINDS and not re.fullmatch(r"[0-9]{6}", password): + raise ValueError("invalid password") + allowed = {"id", "imei", "password", "kind"} + details = {} + if kind in actions.KINDS: + details = actions.prepare(body) + allowed = set(body) + elif kind in full_configuration.KINDS: + details = full_configuration.prepare(body) + allowed = set(body) + elif kind == "configure-server1": + allowed |= {"expected", "target", "model", "firmware"} + if body.get("model") != 231 or body.get("firmware") != "0.01": + raise ValueError("unqualified firmware") + details = { + "expected": configuration.endpoint(body["expected"]), + "target": configuration.endpoint(body["target"]), + "stage": "preflight", + } + if set(body) - allowed: + raise ValueError("unknown command fields") + payload = password + "*GETP" + digest = hashlib.sha256(json.dumps(original, sort_keys=True).encode()).hexdigest() + with self.store.db() as db: + db.execute("BEGIN IMMEDIATE") + previous = db.execute( + "SELECT digest,body FROM commands WHERE id=?", (identifier,) + ).fetchone() + if previous: + if previous[0] != digest: + raise ValueError("idempotency conflict") + value = self.public(self.settle(db, identifier, json.loads(previous[1]))) + value["transport"] = self.transport.read(db, identifier) + return value + if not_after is not None and not_after > time.time() + 600: + raise ValueError("command deadline too distant") + expired = not_after is not None and not_after <= time.time() + if ( + not expired + and kind in (actions.KINDS | full_configuration.KINDS) - {"request-position"} + and not self.sessions.get(imei) + ): + raise ValueError("device has no active session") + last_configuration_at = 0 + for (encoded,) in db.execute("SELECT body FROM commands WHERE imei=?", (imei,)): + pending = json.loads(encoded) + if pending["kind"] in full_configuration.KINDS: + last_configuration_at = max( + last_configuration_at, + pending.get("configuration_received_at", 0), + pending.get("write_reply_sent_at", 0), + ) + if not expired and self.active(db, imei): + raise ValueError("command already pending") + value = { + "id": identifier, + "kind": kind, + **details, + "state": "queued", + "payload": payload, + "password": password, + "created_at": time.time(), + "expires_at": time.time() + 120, + "replies": [], + "response_hashes": [], + } + if kind in actions.KINDS: + value.update(expires_at=time.time() + 30, dispatch_deadline=time.time() + 3) + if kind == "request-position": + # A read may wait for reconnection until its original expiry. + # Once dispatched it is never replayed, even after a crash. + value["dispatch_deadline"] = value["expires_at"] + if kind == "restart": + value["expires_at"] = time.time() + 180 + value["allowed_sessions"] = list(self.sessions.get(imei, ())) + value.pop("payload") + value.pop("password") + elif kind in full_configuration.KINDS: + value["expires_at"] = time.time() + (360 if kind == "select-sim" else 180) + value["not_before"] = last_configuration_at + 15 + if not_after is not None: + value["expires_at"] = min(value["expires_at"], not_after) + if "dispatch_deadline" in value: + value["dispatch_deadline"] = min(value["dispatch_deadline"], not_after) + if expired: + value.update(state="expired", reason="request_deadline") + elif kind == "probe-diagnostic-mode": + lease_end = Observation.diagnostic_lease( + db, value["observation_id"], identifier, bind_imei=imei + ) + value["expires_at"] = min(value["expires_at"], lease_end) + value["dispatch_deadline"] = min(value["dispatch_deadline"], lease_end) + db.execute( + "INSERT INTO commands VALUES(?,?,?,?)", + (identifier, imei, digest, json.dumps(value)), + ) + return self.public(value) + + def settle(self, db, identifier, value): + state = self.public(value)["state"] + if state != value["state"]: + value = {**value, "state": state} + db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)) + return value + + def active(self, db, imei): + # Terminal history never enters the per-packet/per-session hot path. + rows = db.execute( + "SELECT id,body FROM commands WHERE imei=? " + "AND json_extract(body,'$.state') IN ('queued','dispatched') ORDER BY rowid", + (imei,), + ).fetchall() + result = [] + for identifier, encoded in rows: + value = self.settle(db, identifier, json.loads(encoded)) + if value["state"] in ("queued", "dispatched"): + result.append((identifier, value)) + return result + + def wait_delay(self, imei): + with self.store.db() as db: + # Idle senders sleep until admission, a packet or a new command. + # Active staged operations retain their existing bounded timers. + return 1 if self.active(db, imei) else None + + @staticmethod + def public(value): + value = dict(value) + if ( + value["state"] == "queued" + and value.get("dispatch_deadline", float("inf")) < time.time() + ): + value["state"] = "expired" + if value["expires_at"] < time.time() and value["state"] in ("queued", "dispatched"): + value["state"] = ( + "uncertain" + if value.get("write_reply_sent_at") or value.get("stage") == "restart" + else "expired" + if value["state"] == "queued" + else "unconfirmed" + ) + hidden = { + "payload", + "password", + "before", + "after", + "response_hashes", + "session", + "binary", + "token", + "allowed_sessions", + "restart_sessions", + "target_configuration", + "before_configuration", + "sim_guard", + } + return {**{k: v for k, v in value.items() if k not in hidden}, "transport": []} + + def get(self, identifier): + with self.store.db() as db: + db.execute("BEGIN IMMEDIATE") + row = db.execute("SELECT body FROM commands WHERE id=?", (identifier,)).fetchone() + if not row: + raise ValueError("unknown command") + value = self.public(self.settle(db, identifier, json.loads(row[0]))) + value["transport"] = self.transport.read(db, identifier) + return value + + def take(self, imei, session="test"): + delivery = self.take_delivery(imei, session) + return delivery[0] if delivery else None + + def take_delivery(self, imei, session, *, with_receipt=False): + # A configuration reload can leave half-open old sockets beside the new + # live ones. Never let whichever sender wakes first steal the command. + active = tuple(self.sessions.get(imei, ())) + eligible = [s for s in active if self.session_ready.get((imei, s), True)] + if active and session not in eligible: + return None + observed = [s for s in eligible if (imei, s) in self.session_activity] + if observed and session != max( + observed, key=lambda s: (self.session_activity.get((imei, s), 0), s) + ): + return None + with self.store.db() as db: + db.execute("BEGIN IMMEDIATE") + for identifier, value in self.active(db, imei): + if ( + self.verification_recoverable(value) + and value["state"] == "dispatched" + and session != value.get("session") + and self.session_started.get((imei, session), 0) > value.get("monotonic", 0) + ): + # A new B2 connection can outlive a half-open predecessor. + # Only the independent read migrates, never the image write. + self.recover_verification(value) + db.execute( + "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) + ) + if ( + value["state"] == "queued" + and value.get("dispatch_deadline", float("inf")) < time.time() + ): + value["state"] = "expired" + db.execute( + "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) + ) + continue + if ( + value["kind"] == "configure-server1" + and value.get("stage") == "write" + and value["state"] == "dispatched" + and time.time() - value["dispatched_at"] >= 15 + ): + # SETP may reconnect before its reply. Read-only verification can + # move to a new TCP session; the write itself is never resent. + value.update(stage="verify", state="queued") + value.pop("session", None) + if ( + value["state"] != "queued" + or value["expires_at"] < time.time() + or value.get("not_before", 0) > time.time() + ): + continue + if value.get("session") and value["session"] != session: + continue + if ( + value["kind"] in actions.KINDS - {"request-position"} + and session not in value["allowed_sessions"] + ): + continue + if value["kind"] == "request-position" and session not in active: + continue + if value["kind"] in CONFIGURATION_KINDS and active: + last_input = self.session_activity.get((imei, session)) + if last_input is None or not ( + 0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE + ): + # A drained but silent TCP stream may already be dead. + # Await fresh device input; retain the original deadline + # and never replay a previously dispatched stage. + continue + if not self.store.admitted(imei): + return None + if value["kind"] == "probe-diagnostic-mode": + try: + Observation.diagnostic_lease(db, value["observation_id"], identifier) + except ValueError: + value.update(state="expired", reason="observation_closed") + db.execute( + "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) + ) + continue + if value.get("sim_guard") and value.get("stage") in ("write", "restart"): + guard = self.sim_guard.check(imei, value["sim_guard"], db=db) + if guard != "matched": + if guard == "changed": + value.update(state="rejected", reason="sim_card_changed") + db.execute( + "UPDATE commands SET body=? WHERE id=?", + (json.dumps(value), identifier), + ) + continue + value.update( + state="dispatched", + dispatched_at=time.time(), + monotonic=time.monotonic(), + session=session, + ) + restarting = value["kind"] == "restart" or ( + value["kind"] == "select-sim" and value.get("stage") == "restart" + ) + if restarting: + value["restart_sessions"] = list(self.sessions.get(imei, ())) + if value["kind"] == "configure-server1": + value["payload"] = configuration.payload(value) + if value["stage"] == "write": + value["write_dispatched_at"] = time.time() + elif value["kind"] in full_configuration.KINDS and not restarting: + value["payload"] = full_configuration.payload(value) + db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)) + data = ( + actions.frame(value) + if value["kind"] in actions.KINDS or restarting + else frame(value["payload"]) + ) + deadline = value["monotonic"] + min( + MAX_DELIVERY_SECONDS, max(0, value["expires_at"] - value["dispatched_at"]) + ) + if with_receipt: + ticket = self.transport.prepare(db, identifier, value.get("stage", "execute")) + return data, deadline, ticket + return data, deadline + return None + + def web_receive(self, raw, peer, *, with_deadline=False): + """Qualified B2 HTTP channel, scoped to an admitted active modem peer.""" + expires = time.time() + 12 + + def result(reply): + if reply is None or not with_deadline: + return reply + return reply, time.monotonic() + max(0, expires - time.time()) + + imei, command, payload = decode_request(raw) + if not self.store.admitted(imei) or not any( + self.session_peers.get((imei, s)) == peer for s in tuple(self.sessions.get(imei, ())) + ): + return None + reply = bytes.fromhex("5b00030006025d") if command == 6 else None + if command == 1: + number = self.store.numeric_id(imei) + return result(numeric_id_reply(number) if number is not None else None) + if command == 7: + # A clock request is independent of a settings transaction. It + # cannot advance its stage, confirm a write or extend its deadline. + return result(time_reply(int(time.time()))) + if command == 5: + reply = bytes.fromhex("5b00030005015d") + with self.store.db() as db: + db.execute("BEGIN IMMEDIATE") + for identifier, value in self.active(db, imei): + if ( + value["kind"] not in full_configuration.KINDS + or value["state"] != "dispatched" + or value["expires_at"] <= time.time() + ): + continue + if command == 5 and value["stage"] in ("preflight", "verify"): + full_configuration.upload(value, payload) + elif command == 2 and value["stage"] == "write": + guard = self.sim_guard.check(imei, value.get("sim_guard"), db=db) + if guard != "matched": + # No image bytes leave the process for a missing/replaced card. + value.update( + state="rejected" if guard == "changed" else "unconfirmed", + reason="sim_card_changed" + if guard == "changed" + else "sim_identity_unavailable", + ) + reply = None + else: + reply = full_configuration.download(value) + else: + continue + expires = min(expires, value["expires_at"]) + db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)) + break + return result(reply) + + def receive(self, imei, raw, session="test"): + self.sim_guard.observe(imei, raw) + self.receive_actions(imei, raw, session) + started = self.session_started.get((imei, session)) + if started is not None: + with self.store.db(write=True) as db: + for identifier, value in self.active(db, imei): + matched = ( + self.sim_guard.check( + imei, value.get("sim_guard"), after=value.get("dispatched_at"), db=db + ) + == "matched" + ) + if ( + restart.observe(value, raw, session, started) + or matched + and sim_selection.observe(value, raw, session, started) + ): + if value.get("sim_guard") and value["state"] == "sim_selected": + value["sim_guard_verified"] = True + db.execute( + "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) + ) + # Preserve text response evidence privately, never interpret receipt as settings applied. + offset, replies = 2, [] + while offset < len(raw) - 1: + size = int.from_bytes(raw[offset + 1 : offset + 3], "little") + if raw[offset] == 3: + replies.append( + ( + int.from_bytes(raw[offset + 3 : offset + 7], "little"), + raw[offset + 7 : offset + 7 + size].decode("cp1251", errors="replace"), + ) + ) + offset += size + 8 + if not replies: + return + with self.store.db(write=True) as db: + for identifier, value in self.active(db, imei): + if ( + value["kind"] in actions.KINDS | full_configuration.KINDS + or value["state"] != "dispatched" + or value["expires_at"] < time.time() + or value.get("session") != session + ): + continue + accepted = [] + for measured, reply in replies: + digest = hashlib.sha256(f"{measured}:{reply}".encode()).hexdigest() + if ( + # This B2 timestamps text about 4 s behind the VPS clock. + # Bound skew and require strictly newer evidence at every stage. + measured < int(value["dispatched_at"]) - 10 + or measured > time.time() + 5 + or measured <= value.get("last_response_measured", 0) + or digest in value.get("response_hashes", []) + ): + continue + value.setdefault("response_hashes", []).append(digest) + if value["kind"] == "configure-server1": + if configuration.response(value, reply, self.store.config["tracker"]): + accepted.append(reply) + break # Never use two messages from one packet for separate stages. + elif reply.startswith("#1="): + accepted.append(reply) + if not accepted: + continue + value["last_response_measured"] = measured + if value["kind"] == "read-settings": + value.update(state="reply_received", replies=accepted) + elif value["stage"] == "verify" and value["state"] == "queued": + value.pop("session", None) + value["not_before"] = max( + value.get("not_before", 0), value["write_dispatched_at"] + 15 + ) + value.update(received_at=time.time()) + db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)) + + def receive_actions(self, imei, raw, session): + replies = list(actions.confirmations(raw)) + # B2 publishes the same token receipt through both monitoring streams. + # Correlate the device and token, not the socket that carried the request. + # Text commands still have no such correlation and are excluded below. + if ( + not replies + or session not in self.sessions.get(imei, ()) + or not self.store.admitted(imei) + ): + return + with self.store.db(write=True) as db: + for identifier, value in self.active(db, imei): + if ( + value["kind"] not in actions.KINDS + or value.get("encoding") == "text" + or value["state"] != "dispatched" + or value["expires_at"] < time.time() + ): + continue + for code, token in replies: + if token != value["token"] or code > 9: + continue + value.update( + received_at=time.time(), + roundtrip_seconds=time.monotonic() - value["monotonic"], + device_code=code, + reply_via_alternate_session=session != value.get("session"), + ) + if code == 6 or value["kind"] == "restart" and code == 0: + value.setdefault("device_accepted_at", time.time()) + else: + value["state"] = "device_confirmed" if code == 0 else "device_rejected" + db.execute( + "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) + ) + break diff --git a/apps/vps-host/ndc_vps/configuration.py b/apps/vps-host/ndc_vps/configuration.py new file mode 100644 index 00000000..47688af5 --- /dev/null +++ b/apps/vps-host/ndc_vps/configuration.py @@ -0,0 +1,85 @@ +"""B2 231 / 0.01: documented SETP #1 only, with a surviving secondary uplink. + +Never translate USB field numbers into SETP groups. No generic command escape. +GETP contains secrets; only the explicit endpoint projection may reach Core UI. +""" + +import re +import time + + +def endpoint(value): + if not isinstance(value, dict) or set(value) != {"host", "port"}: + raise ValueError("invalid endpoint") + host, port = value["host"], value["port"] + if ( + not isinstance(host, str) + or not 1 <= len(host) <= 32 + or not re.fullmatch(r"[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*", host) + or type(port) is not int + or not 1 <= port <= 65535 + ): + raise ValueError("invalid endpoint") + return {"host": host, "port": port} + + +def groups(reply): + if not isinstance(reply, str) or not reply.startswith("#") or len(reply) > 4096: + raise ValueError("invalid GETP") + result = {} + for part in reply.split("#")[1:]: + key, sep, value = part.partition("=") + if not sep or not key.isdecimal() or key in result: + raise ValueError("invalid GETP group") + result[key] = value + if not {"1", "2", "5", "7", "26"} <= result.keys(): + raise ValueError("incomplete GETP") + return result + + +def server(value): + parts = value.split(",") + # Preserve the undocumented fifth value, accept only the qualified empty form. + if len(parts) != 5 or parts[2:] != ["0", "0", ""]: + raise ValueError("unsupported server settings") + return endpoint({"host": parts[0], "port": int(parts[1])}) + + +def response(operation, reply, tracker): + """Advance only from complete, scoped read evidence. Caller persists atomically.""" + try: + actual = groups(reply) + primary, secondary = server(actual["1"]), server(actual["26"]) + except (ValueError, KeyError): + return False + stage = operation["stage"] + if stage == "preflight": + if primary != operation["expected"] or secondary != endpoint(tracker): + operation.update(state="rejected", reason="configuration_changed") + elif primary == operation["target"]: + operation.update(state="verified", verified_at=time.time(), server1=primary) + else: + operation.update(before=actual, stage="write", state="queued") + elif stage == "write": + # SETP acknowledgement is never enough: issue a separate GETP after a drain interval. + operation.update(stage="verify", state="queued", not_before=time.time() + 3) + elif stage == "verify": + before = operation["before"] + preserved = {k: v for k, v in actual.items() if k != "1"} == { + k: v for k, v in before.items() if k != "1" + } + operation["after"] = actual + if primary == operation["target"] and preserved: + operation.update(state="verified", verified_at=time.time(), server1=primary) + elif actual == before: + operation.update(state="not_applied", reason="settings_unchanged") + else: + operation.update(state="uncertain", reason="readback_mismatch") + return True + + +def payload(operation): + if operation["stage"] == "write": + target = operation["target"] + return f"{operation['password']}*SETP*#1={target['host']},{target['port']}" + return operation["password"] + "*GETP" diff --git a/apps/vps-host/ndc_vps/delivery.py b/apps/vps-host/ndc_vps/delivery.py new file mode 100644 index 00000000..d0b15ea1 --- /dev/null +++ b/apps/vps-host/ndc_vps/delivery.py @@ -0,0 +1,109 @@ +"""Bound the lifetime of command bytes in a Linux TCP send queue. + +TCP acknowledgement is transport evidence only, never command confirmation. +All writes on the guarded stream must pass through write(), including ACKs. +""" + +import asyncio +import fcntl +import socket +import struct +import sys +import termios +import time +from collections import deque + +MAX_DELIVERY_SECONDS = 30 + + +def queued_bytes(sock): + if sys.platform != "linux": + # Production is qualified on Ubuntu only. Other platforms conservatively + # retain the deadline, without claiming TCP acknowledgement evidence. + return None + return struct.unpack("i", fcntl.ioctl(sock, termios.TIOCOUTQ, struct.pack("i", 0)))[0] + + +class Delivery: + def __init__(self, writer): + self.writer = writer + self.sock = writer.get_extra_info("socket") + # Also abort queued kernel data on EOF, task cancellation and shutdown. + # transport.abort() alone discards only asyncio's own write buffer. + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) + if sys.platform == "linux": + self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 30000) + self.written = 0 + self.pending = deque() + self.timer = None + + def ready(self): + """Do not enqueue a new command behind an unacknowledged stream prefix. + + This is Linux transport admission, not device execution confirmation. + Non-Linux engineering tests retain their conservative expiry watchdog. + """ + if self.writer.is_closing() or self.writer.transport.get_write_buffer_size(): + return False + try: + queued = queued_bytes(self.sock) + return queued is None or queued == 0 + except OSError: + return False + + def write(self, data, deadline=None, observe=None): + started = time.monotonic() + + def note(phase, reason=None): + if observe is not None: + observe(phase, time.time(), time.monotonic() - started, reason) + + if deadline is not None and deadline <= time.monotonic(): + note("unconfirmed", "expired_before_write") + self.abort() + raise TimeoutError("command delivery expired before write") + try: + self.writer.write(data) + except (OSError, RuntimeError): + note("unconfirmed", "write_failed") + raise + note("written") + self.written += len(data) + if deadline is not None: + self.pending.append((self.written, deadline, note)) + self.check() + + def check(self): + self.cancel_timer() + if not self.pending: + return + if self.writer.is_closing(): + self.abort() + return + try: + queued = queued_bytes(self.sock) + if queued is not None: + acknowledged = self.written - queued - self.writer.transport.get_write_buffer_size() + while self.pending and self.pending[0][0] <= acknowledged: + self.pending.popleft()[2]("tcp_acknowledged") + if self.pending: + remaining = min(deadline for _, deadline, _ in self.pending) - time.monotonic() + if remaining <= 0: + self.abort("delivery_deadline") + else: + self.timer = asyncio.get_running_loop().call_later( + min(0.25, remaining), self.check + ) + except OSError: + self.abort("socket_error") + + def cancel_timer(self): + if self.timer is not None: + self.timer.cancel() + self.timer = None + + def abort(self, reason="connection_closed"): + self.cancel_timer() + while self.pending: + self.pending.popleft()[2]("unconfirmed", reason) + self.writer.transport.abort() diff --git a/apps/vps-host/ndc_vps/full_configuration.py b/apps/vps-host/ndc_vps/full_configuration.py new file mode 100644 index 00000000..e6bc80b1 --- /dev/null +++ b/apps/vps-host/ndc_vps/full_configuration.py @@ -0,0 +1,113 @@ +"""Whole-image B2 transactions: fresh preflight, one write, independent readback.""" + +import hashlib +import re +import time + +from . import sim_guard, sim_selection +from .usb_protocol import decode_configuration +from .web_protocol import settings_reply + +KINDS = {"read-configuration", "configure-all", "select-sim"} + + +def prepare(body): + allowed = {"id", "imei", "kind", "password", "model", "firmware"} + if body.get("model") != 231 or body.get("firmware") != "0.01": + raise ValueError("unqualified configuration firmware") + result = {"stage": "preflight"} + if body["kind"] in ("configure-all", "select-sim"): + allowed |= {"expected_sha256", "target_configuration"} + if not re.fullmatch(r"[a-f0-9]{64}", body["expected_sha256"]): + raise ValueError("invalid predecessor") + raw = bytes.fromhex(body["target_configuration"]) + config = decode_configuration(raw) + settings_reply(config) # transport-size admission, without a write + result.update(expected_sha256=body["expected_sha256"], target_configuration=raw.hex()) + if "sim_guard" in body: + allowed.add("sim_guard") + result["sim_guard"] = sim_guard.prepare(body["sim_guard"]) + if body["kind"] != "select-sim" or body.get("sim_slot") != result["sim_guard"]["slot"]: + raise ValueError("SIM guard requires exclusive selection of the same slot") + if body["kind"] == "select-sim": + allowed |= {"sim_slot", "sim_policy"} + mask = (1 << 10) | (1 << 20) + policy = body.get("sim_policy", "exclusive") + if policy == "both": + if "sim_slot" in body or config.integer(72, 4) & mask: + raise ValueError("both SIMs must be permitted without an exclusive slot") + result["sim_policy"] = policy + elif policy == "exclusive": + slot = body.get("sim_slot") + if type(slot) is not int or slot not in (1, 2): + raise ValueError("invalid SIM slot") + if config.integer(72, 4) & mask != 1 << (20 if slot == 1 else 10): + raise ValueError("SIM flags do not match requested slot") + result["sim_slot"] = slot + else: + raise ValueError("invalid SIM policy") + if set(body) - allowed: + raise ValueError("unknown configuration fields") + return result + + +def payload(value): + number = 8 if value["stage"] == "write" else 9 + return value["password"] + f"*SERV*1.{number}" + + +def upload(value, raw): + config = decode_configuration(raw) + digest = hashlib.sha256(raw).hexdigest() + value.update( + configuration=raw.hex(), configuration_sha256=digest, configuration_received_at=time.time() + ) + if value["kind"] == "read-configuration": + value.update(state="observed", verified_at=time.time()) + elif value["stage"] == "preflight": + value["before_configuration"] = raw.hex() + target = decode_configuration(bytes.fromhex(value["target_configuration"])) + # Preserve every unknown field and the recovery channels. Core controls + # the reviewed profile fields; network migration of these requires its + # own destination-admission transaction, not a blind full-image write. + critical = (3, 4, 5, 8, 70, 71) + if ( + digest != value["expected_sha256"] + or [r.number for r in config.records] != [r.number for r in target.records] + or any(config.value(n) != target.value(n) for n in critical) + ): + value.update(state="rejected", reason="configuration_predecessor_mismatch") + elif raw.hex() == value["target_configuration"]: + value.update(state="verified", verified_at=time.time(), unchanged=True) + if value["kind"] == "select-sim": + sim_selection.queue_restart(value) + else: + value.update(state="queued", stage="write", not_before=time.time() + 15) + value.pop("session", None) + elif value["stage"] == "verify": + state = ( + "verified" + if raw.hex() == value["target_configuration"] + else "not_applied" + if raw.hex() == value["before_configuration"] + else "uncertain" + ) + value.update(state=state, verified_at=time.time()) + if state == "verified" and value["kind"] == "select-sim": + sim_selection.queue_restart(value) + + +def download(value): + """Call only inside the durable transaction, before writing the HTTP socket.""" + if value.get("write_reply_sent_at"): + return None + raw = settings_reply(decode_configuration(bytes.fromhex(value["target_configuration"]))) + value.update( + write_reply_sent_at=time.time(), + write_reply_sha256=hashlib.sha256(raw).hexdigest(), + stage="verify", + state="queued", + not_before=time.time() + 15, + ) + value.pop("session", None) + return raw diff --git a/apps/vps-host/ndc_vps/observation.py b/apps/vps-host/ndc_vps/observation.py new file mode 100644 index 00000000..cb46feb2 --- /dev/null +++ b/apps/vps-host/ndc_vps/observation.py @@ -0,0 +1,246 @@ +"""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]) diff --git a/apps/vps-host/ndc_vps/operations.py b/apps/vps-host/ndc_vps/operations.py new file mode 100644 index 00000000..85a4f8c1 --- /dev/null +++ b/apps/vps-host/ndc_vps/operations.py @@ -0,0 +1,492 @@ +"""Durable tracker-maintenance intents; bounded attempts belong to Commands. + +An outage ends an attempt, not its owning intent. No downstream output action +is admitted here. State changes reconcile the actual B2 image before retrying. +""" + +import hashlib +import json +import re +import threading +import time +import uuid + +from . import actions, full_configuration, sim_selection + +KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"} +PENDING = {"queued", "dispatched"} +RETRY = {"expired", "unconfirmed", "uncertain", "not_applied"} +FACTS = { + "transport", + "stage", + "dispatched_at", + "received_at", + "device_accepted_at", + "device_code", + "roundtrip_seconds", + "reconnected_at", + "reconnect_seconds", + "verified_at", + "configuration", + "configuration_sha256", + "configuration_received_at", + "write_reply_sent_at", + "active_sim", + "telemetry_measured_at", + "unchanged", + "sim_guard_verified", +} + + +class Operations: + def __init__(self, store, commands): + self.store, self.commands = store, commands + # Only local SQLite work under this lock; never sockets, sleeps or device I/O. + self.lock = threading.RLock() + with store.db() as db: + db.executescript(""" + CREATE TABLE IF NOT EXISTS operations( + seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL, + imei TEXT NOT NULL,state TEXT NOT NULL,digest TEXT NOT NULL,body TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS operations_pending ON operations(imei,state,seq); + CREATE TABLE IF NOT EXISTS operation_attempts( + operation TEXT NOT NULL,number INTEGER NOT NULL,id TEXT UNIQUE NOT NULL, + body TEXT NOT NULL,PRIMARY KEY(operation,number)); + CREATE TABLE IF NOT EXISTS operation_modem( + imei TEXT PRIMARY KEY,body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS operation_stops(id TEXT PRIMARY KEY,kind TEXT NOT NULL); + """) + + def save(self, value): + with self.store.db() as db: + encoded = json.dumps(value) + db.execute( + "UPDATE operations SET state=?,body=? WHERE id=? AND body<>?", + (value["state"], encoded, value["id"], encoded), + ) + + def submit(self, body): + body = dict(body) + if ( + not re.fullmatch(r"[a-f0-9]{32}", body.get("id", "")) + or body.get("kind") not in KINDS + or not self.store.admitted(body.get("imei")) + ): + raise ValueError("unsupported operation") + if body["kind"] in full_configuration.KINDS: + if not re.fullmatch(r"[0-9]{6}", body.get("password", "")): + raise ValueError("invalid password") + full_configuration.prepare(body) + else: + actions.prepare(body) + digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() + with self.lock, self.store.db() as db: + db.execute("BEGIN IMMEDIATE") + stopped = db.execute( + "SELECT kind FROM operation_stops WHERE id=?", (body["id"],) + ).fetchone() + if stopped: + return { + "id": body["id"], + "kind": stopped[0], + "state": "stopped", + "durable": True, + "runtime_phase": "stopped", + "stop_requested": True, + "attempt_count": 0, + } + old = db.execute( + "SELECT digest,body FROM operations WHERE id=?", (body["id"],) + ).fetchone() + if old: + if old[0] != digest: + raise ValueError("idempotency conflict") + return self.public(json.loads(old[1])) + count = db.execute( + "SELECT count(*) FROM operations WHERE imei=? AND state IN ('queued','dispatched')", + (body["imei"],), + ).fetchone()[0] + if count >= 32: + raise ValueError("operation queue full") + value = { + "id": body["id"], + "imei": body["imei"], + "kind": body["kind"], + "request": body, + "created_at": time.time(), + "state": "queued", + "runtime_phase": "waiting-link", + "attempt_count": 0, + "next_attempt_at": 0, + "phase": "execute", + "result": {}, + } + db.execute( + "INSERT INTO operations(id,imei,state,digest,body) VALUES(?,?,?,?,?)", + (body["id"], body["imei"], value["state"], digest, json.dumps(value)), + ) + return self.public(value) + + @staticmethod + def public(value): + result = {k: v for k, v in value.get("result", {}).items() if k in FACTS} + result.update( + { + k: value[k] + for k in ( + "id", + "kind", + "state", + "created_at", + "attempt_count", + "runtime_phase", + "next_attempt_at", + "stop_requested", + "reason", + ) + if k in value + } + ) + result["durable"] = True + if value.get("attempt"): + result["attempt_id"] = value["attempt"]["id"] + result["attempt_expires_at"] = value["attempt"]["not_after"] + return result + + def pending(self, imei): + with self.store.db() as db: + return ( + db.execute( + "SELECT 1 FROM operations WHERE imei=? AND state IN " + "('queued','dispatched') LIMIT 1", + (imei,), + ).fetchone() + is not None + ) + + def fresh(self, imei): + return any( + 0 <= time.monotonic() - self.commands.session_activity.get((imei, s), 0) <= 30 + for s in tuple(self.commands.sessions.get(imei, ())) + ) + + def wait_delay(self, imei): + with self.store.db() as db: + row = db.execute( + "SELECT body FROM operations WHERE imei=? AND state IN " + "('queued','dispatched') ORDER BY seq LIMIT 1", + (imei,), + ).fetchone() + if not row: + return None + value = json.loads(row[0]) + if value.get("attempt"): + return 1 + return max(1, value["next_attempt_at"] - time.time()) if self.fresh(imei) else None + + def get(self, identifier): + with self.store.db() as db: + row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone() + if not row: + with self.store.db() as db: + stopped = db.execute( + "SELECT kind FROM operation_stops WHERE id=?", (identifier,) + ).fetchone() + if stopped: + return { + "id": identifier, + "kind": stopped[0], + "state": "stopped", + "durable": True, + "runtime_phase": "stopped", + "stop_requested": True, + "attempt_count": 0, + } + raise ValueError("unknown operation") + self.advance(json.loads(row[0])["imei"]) + with self.store.db() as db: + value = json.loads( + db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()[0] + ) + result = self.public(value) + attempt = value.get("attempt", value.get("result", {})).get("id") + if attempt: + result["transport"] = self.commands.transport.read(db, attempt) + return result + + def cancel(self, identifier, kind=None): + if not re.fullmatch(r"[a-f0-9]{32}", identifier): + raise ValueError("invalid operation identity") + with self.lock, self.store.db() as db: + db.execute("BEGIN IMMEDIATE") + row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone() + if not row: + if kind not in KINDS: + raise ValueError("unknown operation") + db.execute("INSERT OR IGNORE INTO operation_stops VALUES(?,?)", (identifier, kind)) + return { + "id": identifier, + "kind": kind, + "state": "stopped", + "durable": True, + "runtime_phase": "stopped", + "stop_requested": True, + "attempt_count": 0, + } + value = json.loads(row[0]) + if value["state"] in PENDING: + value["stop_requested"] = True + if not value.get("attempt"): + value.update(state="stopped", runtime_phase="stopped") + db.execute( + "UPDATE operations SET state=?,body=? WHERE id=?", + (value["state"], json.dumps(value), identifier), + ) + return self.get(identifier) + + def history(self, identifier, before=2**63 - 1): + with self.store.db() as db: + rows = db.execute( + "SELECT number,body FROM operation_attempts WHERE operation=? " + "AND number 20 else None, + } + + def note_attempt(self, value, result): + item = {k: result[k] for k in FACTS - {"configuration"} if k in result} + item.update( + id=value["attempt"]["id"], + number=value["attempt_count"], + phase=value["phase"], + state=result["state"], + ) + with self.store.db() as db: + old = db.execute( + "SELECT body FROM operation_attempts WHERE id=?", (item["id"],) + ).fetchone() + if old: + previous = json.loads(old[0]) + previous.pop("observed_at", None) + if previous == item: + return + item["observed_at"] = time.time() + db.execute( + "INSERT INTO operation_attempts VALUES(?,?,?,?) ON CONFLICT(operation,number) " + "DO UPDATE SET body=excluded.body", + (value["id"], value["attempt_count"], item["id"], json.dumps(item)), + ) + + def observe(self, imei, raw): + offset = 2 + while offset < len(raw) - 1: + size = int.from_bytes(raw[offset + 1 : offset + 3], "little") + measured = int.from_bytes(raw[offset + 3 : offset + 7], "little") + payload = raw[offset + 7 : offset + 7 + size] + if raw[offset] == 1 and 0 <= time.time() - measured <= 30: + for index in range(0, len(payload) - 4, 5): + if payload[index] != 99: + continue + ds2 = int.from_bytes(payload[index + 1 : index + 5], "little") + value = { + "active_sim": 1 + ((ds2 >> 5) & 1), + "gprs": (ds2 >> 2) & 7, + "measured_at": measured, + } + with self.store.db() as db: + db.execute( + "INSERT INTO operation_modem VALUES(?,?) ON CONFLICT(imei) " + "DO UPDATE SET body=excluded.body WHERE " + "json_extract(excluded.body, '$.measured_at') >= " + "json_extract(operation_modem.body, '$.measured_at')", + (imei, json.dumps(value)), + ) + offset += size + 8 + + def selected(self, value): + if ( + self.commands.sim_guard.check( + value["imei"], value["request"].get("sim_guard"), after=value["created_at"] + ) + != "matched" + ): + return None + with self.store.db() as db: + row = db.execute( + "SELECT body FROM operation_modem WHERE imei=?", (value["imei"],) + ).fetchone() + data = json.loads(row[0]) if row else {} + return ( + data + if sim_selection.matches(value["request"], data.get("active_sim")) + and data.get("gprs") == 4 + and data.get("measured_at", 0) > value["created_at"] + and 0 <= time.time() - data["measured_at"] <= 30 + else None + ) + + def reconcile(self, value, result): + request = value["request"] + digest = result.get("configuration_sha256") + target = hashlib.sha256(bytes.fromhex(request["target_configuration"])).hexdigest() + if digest == target: + if value["kind"] == "configure-all": + value.update(state="verified", runtime_phase="complete", result=result) + elif selected := self.selected(value): + value.update( + state="sim_selected", + runtime_phase="complete", + result={ + **result, + "active_sim": selected["active_sim"], + "telemetry_measured_at": selected["measured_at"], + "sim_guard_verified": bool(request.get("sim_guard")), + }, + ) + else: + value.update(phase="execute", retry_predecessor=target) + elif digest == request["expected_sha256"]: + value.update(phase="execute", retry_predecessor=digest) + else: + value.update( + state="rejected", + reason="configuration_conflict", + runtime_phase="complete", + result=result, + ) + + def advance(self, imei): + with self.lock: + with self.store.db() as db: + row = db.execute( + "SELECT body FROM operations WHERE imei=? AND state IN " + "('queued','dispatched') ORDER BY seq LIMIT 1", + (imei,), + ).fetchone() + if not row: + return + value = json.loads(row[0]) + if not self.store.admitted(imei): + value.update(state="rejected", reason="device_revoked", runtime_phase="complete") + self.save(value) + return + if value.get("attempt"): + # Idempotent submission covers a crash before/after attempt admission. + # Read first: the accepted attempt may have completed while Core was away. + try: + result = self.commands.get(value["attempt"]["id"]) + except ValueError: + if value.get("stop_requested"): + value.pop("attempt", None) + value.update(state="stopped", runtime_phase="stopped") + self.save(value) + return + try: + result = self.commands.submit(value["attempt"]) + except ValueError: + return # A legacy operation/session admission still owns the channel. + value["result"] = result + self.note_attempt(value, result) + if result["state"] in PENDING: + value.update( + state=result["state"], + runtime_phase="checking-result" + if value["phase"] == "inspect" + else "executing", + ) + self.save(value) + return + if value["phase"] == "inspect" and result["state"] == "observed": + self.reconcile(value, result) + elif result["state"] in { + "device_confirmed", + "observed", + "verified", + "sim_selected", + "reconnected", + }: + value.update(state=result["state"], runtime_phase="complete") + elif ( + value["kind"] == "restart" + and result.get("device_code") == 0 + and result.get("device_accepted_at") + ): + value.update(state="accepted", runtime_phase="complete") + elif ( + result["state"] in RETRY + or result.get("device_code") == 7 + or result.get("reason") == "configuration_predecessor_mismatch" + ): + if value["kind"] in {"configure-all", "select-sim"}: + value["phase"] = "inspect" + else: + value.update(state=result["state"], runtime_phase="complete") + if result.get("reason") == "sim_card_changed": + value["reason"] = "sim_card_changed" + value.pop("attempt", None) + if value["state"] in PENDING: + value.update( + state="stopped" if value.get("stop_requested") else "queued", + runtime_phase="stopped" if value.get("stop_requested") else "retry-wait", + next_attempt_at=time.time() + + min(300, 5 * 2 ** min(value["attempt_count"] - 1, 6)), + ) + self.save(value) + return + if value.get("stop_requested"): + value.update(state="stopped", runtime_phase="stopped") + self.save(value) + return + if value["next_attempt_at"] > time.time(): + return + if not self.fresh(imei): + if value["runtime_phase"] != "waiting-link": + value.update(runtime_phase="waiting-link") + self.save(value) + return + if value["phase"] == "execute" and value["request"].get("sim_guard"): + guard = self.commands.sim_guard.check(imei, value["request"]["sim_guard"]) + if guard != "matched": + if guard == "changed": + value.update( + state="rejected", runtime_phase="complete", reason="sim_card_changed" + ) + else: + value.update(runtime_phase="waiting-identity") + self.save(value) + return + attempt = {**value["request"], "id": uuid.uuid4().hex} + if value["phase"] == "inspect": + attempt = { + k: v + for k, v in attempt.items() + if k in {"id", "imei", "password", "model", "firmware"} + } + attempt["kind"] = "read-configuration" + elif value.get("retry_predecessor"): + attempt["expected_sha256"] = value["retry_predecessor"] + lifetime = ( + 360 + if attempt["kind"] == "select-sim" + else 30 + if attempt["kind"] == "request-position" + else 180 + ) + attempt["not_after"] = time.time() + lifetime + value.update( + attempt=attempt, + attempt_count=value["attempt_count"] + 1, + result={}, + runtime_phase="checking-result" if value["phase"] == "inspect" else "executing", + ) + # The plan is durable before the attempt's separate transaction. + self.save(value) + self.advance(imei) diff --git a/apps/vps-host/ndc_vps/restart.py b/apps/vps-host/ndc_vps/restart.py new file mode 100644 index 00000000..e3547157 --- /dev/null +++ b/apps/vps-host/ndc_vps/restart.py @@ -0,0 +1,30 @@ +"""Observe return after a restart request without claiming CPU/power-cycle proof.""" + +import time + + +def observe(value, raw, session, started): + if ( + value.get("kind") != "restart" + or value["state"] != "dispatched" + or value["expires_at"] < time.time() + or session in value["restart_sessions"] + or started <= value["monotonic"] + ): + return False + # Only type-1 telemetry measured after dispatch establishes fresh return. + # A new header, old archive, text reply or token ACK cannot complete this. + offset = 2 + while offset < len(raw) - 1: + size = int.from_bytes(raw[offset + 1 : offset + 3], "little") + measured = int.from_bytes(raw[offset + 3 : offset + 7], "little") + if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5: + value.update( + state="reconnected", + reconnected_at=time.time(), + reconnect_seconds=time.monotonic() - value["monotonic"], + telemetry_measured_at=measured, + ) + return True + offset += size + 8 + return False diff --git a/apps/vps-host/ndc_vps/service.py b/apps/vps-host/ndc_vps/service.py new file mode 100644 index 00000000..c3a9622d --- /dev/null +++ b/apps/vps-host/ndc_vps/service.py @@ -0,0 +1,402 @@ +"""Bounded asyncio TCP receiver and pinned-TLS API; no shell/device control API.""" + +import asyncio +import json +import sqlite3 +import ssl +import time +import uuid +from contextlib import suppress +from urllib.parse import parse_qs, urlsplit + +from . import arnavi +from .commands import COMMAND_SESSION_MAX_IDLE, Commands +from .delivery import Delivery +from .observation import Observation, http_body +from .operations import Operations + + +class Service: + def __init__(self, store): + self.store = store + self.connections = 0 + self.commands = Commands(store) + self.operations = Operations(store, self.commands) + self.observation = Observation(store) + self.wake = {} + + async def tracker(self, reader, writer): + self.connections += 1 + session = uuid.uuid4().hex + sender = None + delivery = None + imei = None + try: + if self.connections > 256: + return + async with asyncio.timeout(10): + header = await reader.readexactly(10) + if header[:2] != b"\xff\x23": + if ( + not await self.observe_configuration(reader, header, writer) + and header == b"POST /c/in" + ): + delivery = Delivery(writer) + await self.configuration_http(reader, writer, header, delivery) + return + imei = arnavi.identity(header) + if not await asyncio.to_thread(self.store.admitted, imei): + return + delivery = Delivery(writer) + self.commands.sessions.setdefault(imei, set()).add(session) + self.commands.session_started[imei, session] = time.monotonic() + self.commands.session_activity[imei, session] = time.monotonic() + self.commands.session_peers[imei, session] = writer.get_extra_info("peername")[0] + self.commands.session_ready[imei, session] = False + delivery.write(arnavi.header_ack(int(time.time()))) + await writer.drain() + sender = asyncio.create_task(self.send_commands(imei, writer, session, delivery)) + buffer = b"" + while True: + async with asyncio.timeout(180): + chunk = await reader.read(min(4096, arnavi.MAX_PACKAGE - len(buffer))) + if not chunk: + return + buffer += chunk + while buffer: + parsed = arnavi.parse_package(buffer) + if parsed is None: + break + length, packets = parsed + self.commands.session_activity[imei, session] = time.monotonic() + await asyncio.to_thread( + self.accept_package, imei, buffer[:length], packets, session + ) + self.notify(imei) + delivery.write(arnavi.package_ack(buffer[1])) + await writer.drain() + buffer = buffer[length:] + except ( + ValueError, + KeyError, + OSError, + sqlite3.Error, + TimeoutError, + asyncio.IncompleteReadError, + asyncio.LimitOverrunError, + ): + pass # Deliberately no raw identity/data/credentials in logs. + finally: + if imei: + self.commands.sessions.get(imei, set()).discard(session) + self.commands.session_started.pop((imei, session), None) + self.commands.session_activity.pop((imei, session), None) + self.commands.session_peers.pop((imei, session), None) + self.commands.session_ready.pop((imei, session), None) + if not self.commands.sessions.get(imei): + self.commands.sessions.pop(imei, None) + if sender: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + self.connections -= 1 + if delivery: + delivery.abort() + else: + writer.close() + + def accept_package(self, imei, raw, packets, session): + # Core may fetch/ack packages concurrently. Publish the packet and its + # command evidence together before either Core or B2 can consume it. + with self.store.packet_transaction(): + self.store.append(imei, raw, packets) + self.commands.receive(imei, raw, session) + self.operations.observe(imei, raw) + + async def observe_configuration(self, reader, header, writer=None): + ticket = await asyncio.to_thread(self.observation.claim) + if ticket is None: + return False + raw = bytearray(header) + events = [ + {"offset": 0, "bytes": len(header), "at": time.time(), "monotonic": time.monotonic()} + ] + try: + async with asyncio.timeout(8): + while len(raw) < 16384: + chunk = await reader.read(min(4096, 16384 - len(raw))) + if not chunk: + break + events.append( + { + "offset": len(raw), + "bytes": len(chunk), + "at": time.time(), + "monotonic": time.monotonic(), + } + ) + raw.extend(chunk) + if writer is not None: + reply = await asyncio.to_thread(self.observation.reply, ticket, bytes(raw)) + if reply is not None: + writer.write( + b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n" + + f"Content-Length: {len(reply)}\r\n".encode() + + b"Connection: keep-alive\r\n\r\n" + + reply + ) + await writer.drain() + except (TimeoutError, OSError): + pass + finally: + await asyncio.to_thread(self.observation.finish, ticket, bytes(raw), events) + return True + + async def configuration_http(self, reader, writer, initial, delivery): + if initial != b"POST /c/in": + return + peer = writer.get_extra_info("peername")[0] + for _ in range(8): + async with asyncio.timeout(12): + header = initial + await reader.readuntil(b"\r\n\r\n") + initial = b"" + if len(header) > 2048: + return + lengths = [ + line.split(b":", 1)[1].strip() + for line in header.split(b"\r\n") + if line.lower().startswith(b"content-length:") + ] + if len(lengths) != 1 or not lengths[0].isdigit(): + return + size = int(lengths[0]) + if not 20 <= size <= 16384: + return + body = http_body(header + await reader.readexactly(size)) + if body is None: + return + response = await asyncio.to_thread( + self.commands.web_receive, body, peer, with_deadline=True + ) + self.notify(str(int.from_bytes(body[4:12], "little"))) + if response is None: + return + reply, deadline = response + delivery.write( + b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n" + + f"Content-Length: {len(reply)}\r\n".encode() + + b"Connection: keep-alive\r\n\r\n" + + reply, + deadline, + ) + await writer.drain() + + async def send_commands(self, imei, writer, session, delivery): + event = asyncio.Event() + observations = [] + + def observe(ticket, phase, at, elapsed, reason): + # The socket timer never opens SQLite or waits for filesystem I/O. + observations.append((ticket, phase, at, elapsed, reason)) + event.set() + + async def persist(): + if observations: + batch = observations[:] + observations.clear() + commit = asyncio.create_task( + asyncio.to_thread(self.commands.transport.record, batch) + ) + try: + await asyncio.shield(commit) + except asyncio.CancelledError: + # EOF cancels this sender. Finish the extracted batch before + # the finally block records closure of its remaining bytes. + await commit + raise + + self.wake.setdefault(imei, set()).add(event) + try: + while not writer.is_closing(): + event.clear() + await persist() + last_input = self.commands.session_activity.get((imei, session)) + self.commands.session_ready[imei, session] = ( + delivery.ready() + and last_input is not None + and 0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE + ) + await asyncio.to_thread(self.operations.advance, imei) + dispatch = await asyncio.to_thread( + self.commands.take_delivery, imei, session, with_receipt=True + ) + if dispatch: + data, deadline, ticket = dispatch + delivery.write( + data, + deadline, + lambda phase, at, elapsed, reason, ticket=ticket: observe( + ticket, phase, at, elapsed, reason + ), + ) + await writer.drain() + await persist() + delay = await asyncio.to_thread(self.commands.wait_delay, imei) + operation_delay = await asyncio.to_thread(self.operations.wait_delay, imei) + delay = ( + min(d for d in (delay, operation_delay) if d is not None) + if (delay is not None or operation_delay is not None) + else None + ) + with suppress(TimeoutError): + await asyncio.wait_for(event.wait(), delay) + finally: + self.wake.get(imei, set()).discard(event) + if not self.wake.get(imei): + self.wake.pop(imei, None) + delivery.abort() + await persist() + + def notify(self, imei): + for event in self.wake.get(imei, ()): + event.set() + + async def api(self, reader, writer): + status, value = 400, {"error": "invalid_request"} + try: + async with asyncio.timeout(15): + header = await reader.readuntil(b"\r\n\r\n") + if len(header) > 8192: + raise ValueError + lines = header.decode("ascii").split("\r\n") + method, target, _ = lines[0].split(" ") + headers = dict(line.lower().split(": ", 1) for line in lines[1:] if line) + size = int(headers.get("content-length", "0")) + if not 0 <= size <= 1024 * 1024 or "transfer-encoding" in headers: + raise ValueError + payload = await reader.readexactly(size) if size else b"{}" + body = json.loads(payload) + route = urlsplit(target) + token = headers.get("authorization", "").removeprefix("bearer ") + # Header values must retain case for bearer credentials. + for line in lines[1:]: + if line.lower().startswith("authorization: bearer "): + token = line[len("authorization: bearer ") :] + if method == "GET" and route.path == "/health": + value = {"ok": True, "service": "ndc-mission-vps-host"} + elif method == "POST" and route.path == "/v1/pair": + value = await asyncio.to_thread(self.store.pair, body) + else: + if not await asyncio.to_thread(self.store.authorize, token): + raise PermissionError + if method == "GET" and route.path == "/v1/status": + value = await asyncio.to_thread(self.store.status) + elif method == "PUT" and route.path == "/v1/devices": + await asyncio.to_thread(self.store.set_devices, body["items"]) + value = {"ok": True} + elif method == "GET" and route.path == "/v1/packets": + after = int(parse_qs(route.query).get("after", ["0"])[0]) + value = await asyncio.to_thread(self.store.fetch, max(0, after)) + elif method == "POST" and route.path == "/v1/commands": + if await asyncio.to_thread(self.operations.pending, body["imei"]): + raise ValueError("durable operation owns device queue") + value = await asyncio.to_thread(self.commands.submit, body) + self.notify(body["imei"]) + elif method == "POST" and route.path == "/v1/operations": + value = await asyncio.to_thread(self.operations.submit, body) + self.notify(body["imei"]) + elif ( + method == "POST" + and route.path.startswith("/v1/operations/") + and route.path.endswith("/cancel") + ): + value = await asyncio.to_thread( + self.operations.cancel, route.path.split("/")[-2], body.get("kind") + ) + elif ( + method == "GET" + and route.path.startswith("/v1/operations/") + and route.path.endswith("/attempts") + ): + before = int(parse_qs(route.query).get("before", [str(2**63 - 1)])[0]) + value = await asyncio.to_thread( + self.operations.history, route.path.split("/")[-2], before + ) + elif method == "GET" and route.path.startswith("/v1/operations/"): + value = await asyncio.to_thread( + self.operations.get, route.path.rsplit("/", 1)[1] + ) + elif method == "POST" and route.path == "/v1/configuration-observations": + value = await asyncio.to_thread(self.observation.arm, body) + elif ( + method == "POST" + and route.path.startswith("/v1/configuration-observations/") + and route.path.endswith("/close") + ): + value = await asyncio.to_thread( + self.observation.close, route.path.split("/")[-2] + ) + elif method == "GET" and route.path.startswith( + "/v1/configuration-observations/" + ): + value = await asyncio.to_thread( + self.observation.get, route.path.rsplit("/", 1)[1] + ) + elif method == "GET" and route.path.startswith("/v1/commands/"): + value = await asyncio.to_thread( + self.commands.get, route.path.rsplit("/", 1)[1] + ) + elif method == "POST" and route.path == "/v1/ack": + if type(body["through"]) is not int or body["through"] < 0: + raise ValueError + await asyncio.to_thread(self.store.acknowledge, body["through"]) + value = {"ok": True} + else: + raise ValueError + status = 200 + except PermissionError: + status, value = 403, {"error": "not_authorized"} + except ( + ValueError, + KeyError, + TypeError, + UnicodeError, + asyncio.IncompleteReadError, + asyncio.LimitOverrunError, + TimeoutError, + ): + pass + except (OSError, sqlite3.Error): + status, value = 503, {"error": "storage_unavailable"} + try: + payload = json.dumps(value).encode() + writer.write( + ( + f"HTTP/1.1 {status} Result\r\nContent-Type: application/json\r\n" + f"Content-Length: {len(payload)}\r\nConnection: close\r\n" + "Cache-Control: no-store\r\n\r\n" + ).encode() + + payload + ) + await writer.drain() + except OSError: + pass + finally: + writer.close() + + async def run(self): + tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + tls.minimum_version = ssl.TLSVersion.TLSv1_3 + tls.load_cert_chain(self.store.root / "tls.crt", self.store.root / "tls.key") + api = await asyncio.start_server( + self.api, + "0.0.0.0", + self.store.config["api_port"], + ssl=tls, + ssl_handshake_timeout=8, + limit=8192, + ) + tracker = await asyncio.start_server( + self.tracker, "0.0.0.0", self.store.config["tracker"]["port"] + ) + async with api, tracker: + await asyncio.gather(api.serve_forever(), tracker.serve_forever()) diff --git a/apps/vps-host/ndc_vps/sim_guard.py b/apps/vps-host/ndc_vps/sim_guard.py new file mode 100644 index 00000000..e7b9f727 --- /dev/null +++ b/apps/vps-host/ndc_vps/sim_guard.py @@ -0,0 +1,83 @@ +"""Durable firmware SID bindings, checked at the last configuration write boundary.""" + +import json +import re +import time + +from .sim_network import binding, decode_pairs, merge + + +def prepare(value): + if ( + not isinstance(value, dict) + or set(value) != {"slot", "sid"} + or type(value["slot"]) is not int + or value["slot"] not in (1, 2) + or not isinstance(value["sid"], str) + or not re.fullmatch(r"89[0-9]{18}", value["sid"]) + ): + raise ValueError("invalid SIM identity guard") + return dict(value) + + +class SimGuard: + def __init__(self, store): + self.store = store + with store.db() as db: + db.execute( + "CREATE TABLE IF NOT EXISTS sim_bindings(imei TEXT PRIMARY KEY,body TEXT NOT NULL)" + ) + + def observe(self, imei, raw): + # Called only for validated INTERNAL frames in the packet commit transaction. + with self.store.db(write=True) as db: + old = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone() + value = json.loads(old[0]) if old else None + offset, now = 2, time.time() + while offset < len(raw) - 1: + size = int.from_bytes(raw[offset + 1 : offset + 3], "little") + measured = int.from_bytes(raw[offset + 3 : offset + 7], "little") + payload = raw[offset + 7 : offset + 7 + size] + if raw[offset] == 1: + tags = {} + for i in range(0, len(payload) - 4, 5): + tags.setdefault(payload[i], set()).add(payload[i + 1 : i + 5]) + status = {} + if len(tags.get(99, ())) == 1: + ds = int.from_bytes(next(iter(tags[99])), "little") + status = {"sim_states": {"1": (ds >> 6) & 7, "2": (ds >> 9) & 7}} + value = merge( + value, + { + "measured_at": measured, + "cellular": {"status": status}, + "sim_identifiers": decode_pairs(tags), + }, + host_id="local", + sequence=0, + received=now, + tracker=imei, + ) + offset += size + 8 + if value: + db.execute( + "INSERT OR REPLACE INTO sim_bindings VALUES(?,?)", (imei, json.dumps(value)) + ) + + def check(self, imei, guard, *, after=None, db=None): + if guard is None: + return "matched" + if db is None: + with self.store.db() as connection: + return self.check(imei, guard, after=after, db=connection) + row = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone() + value = json.loads(row[0]) if row else None + sid = binding(value, str(guard["slot"]), now=time.time()) + if sid is None: + return "waiting" + if sid != guard["sid"]: + return "changed" + observed = value["slots"][str(guard["slot"])]["observation"] + if after is not None and observed["measured_at"] <= after: + return "waiting" + return "matched" diff --git a/apps/vps-host/ndc_vps/sim_selection.py b/apps/vps-host/ndc_vps/sim_selection.py new file mode 100644 index 00000000..457e39f3 --- /dev/null +++ b/apps/vps-host/ndc_vps/sim_selection.py @@ -0,0 +1,55 @@ +"""SIM permissions: verified flags, one restart, fresh modem evidence.""" + +import time + +from . import actions + + +def matches(value, slot): + return ( + type(slot) is int + and slot in (1, 2) + and (value.get("sim_policy") == "both" or slot == value.get("sim_slot")) + ) + + +def queue_restart(value): + value.update(actions.prepare({"kind": "restart", "model": 231, "firmware": "0.01"})) + value.update(stage="restart", state="queued", not_before=time.time()) + value.pop("session", None) + + +def observe(value, raw, session, started): + if ( + value.get("kind") != "select-sim" + or value.get("stage") != "restart" + or value["state"] != "dispatched" + or value["expires_at"] <= time.time() + or session in value["restart_sessions"] + or started <= value["monotonic"] + ): + return False + # Validated INTERNAL packages only. ACKs, archives, old sockets, old and + # future measurements, and GPRS on the wrong SIM cannot confirm selection. + offset = 2 + while offset < len(raw) - 1: + size = int.from_bytes(raw[offset + 1 : offset + 3], "little") + measured = int.from_bytes(raw[offset + 3 : offset + 7], "little") + payload = raw[offset + 7 : offset + 7 + size] + if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5: + for index in range(0, len(payload) - 4, 5): + if payload[index] != 99: + continue + ds2 = int.from_bytes(payload[index + 1 : index + 5], "little") + slot = 1 + ((ds2 >> 5) & 1) + if matches(value, slot) and (ds2 >> 2) & 7 == 4: + value.update( + state="sim_selected", + active_sim=slot, + verified_at=time.time(), + telemetry_measured_at=measured, + reconnect_seconds=time.monotonic() - value["monotonic"], + ) + return True + offset += size + 8 + return False diff --git a/apps/vps-host/ndc_vps/store.py b/apps/vps-host/ndc_vps/store.py new file mode 100644 index 00000000..a059c31e --- /dev/null +++ b/apps/vps-host/ndc_vps/store.py @@ -0,0 +1,262 @@ +"""Durable receiver journal. Acknowledgements follow SQLite FULL commits.""" + +import base64 +import hashlib +import hmac +import json +import os +import secrets +import sqlite3 +import threading +import time +from contextlib import contextmanager +from pathlib import Path + + +def private_write(path, data): + temporary = path.with_name(path.name + ".new") + with open(temporary, "wb") as stream: + os.chmod(temporary, 0o600) + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + fd = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +class Store: + def __init__(self, root): + self.root = Path(root) + self.config = json.loads((self.root / "host.json").read_text()) + self.path = self.root / "journal.sqlite3" + self._packet = threading.local() + with self.db() as db: + db.executescript(""" + CREATE TABLE IF NOT EXISTS state(key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS devices(imei TEXT PRIMARY KEY, instance TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS device_ids( + imei TEXT PRIMARY KEY, number INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS packages(id INTEGER PRIMARY KEY AUTOINCREMENT, + imei TEXT NOT NULL, instance TEXT NOT NULL, digest TEXT UNIQUE NOT NULL, + received REAL NOT NULL, raw BLOB NOT NULL, packets TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS receipts(digest TEXT PRIMARY KEY, at REAL NOT NULL); + """) + self.path.chmod(0o600) + + @contextmanager + def db(self, *, write=False): + # Packet consumers run together on one worker thread. No partial + # receipt or modem state may become visible to Core or the sender. + current = getattr(self._packet, "connection", None) + if current is not None: + yield current + return + connection = sqlite3.connect(self.path, timeout=10) + try: + connection.execute("PRAGMA synchronous=FULL") + with connection: + if write: + connection.execute("BEGIN IMMEDIATE") + yield connection + finally: + connection.close() + + @contextmanager + def packet_transaction(self): + """Synchronous packet ingestion only: no sockets, awaits or API work.""" + if getattr(self._packet, "connection", None) is not None: + raise RuntimeError("nested packet transaction") + with self.db(write=True) as connection: + self._packet.connection = connection + try: + yield + finally: + del self._packet.connection + + def invitation(self): + secret = secrets.token_urlsafe(32) + expires = int(time.time()) + 86400 + with self.db() as db: + if db.execute("SELECT 1 FROM state WHERE key='owner'").fetchone(): + raise ValueError("host already paired; restore its Core identity instead") + db.execute( + "INSERT OR REPLACE INTO state VALUES('invitation',?)", + ( + json.dumps( + {"hash": hashlib.sha256(secret.encode()).hexdigest(), "expires_at": expires} + ), + ), + ) + code = { + "schema": "missioncore.vps-pairing/v1", + "host_id": self.config["host_id"], + "endpoint": self.config["endpoint"], + "fingerprint": self.config["fingerprint"], + "secret": secret, + "expires_at": expires, + } + encoded = "MCV1." + base64.urlsafe_b64encode(json.dumps(code).encode()).decode().rstrip("=") + private_write(self.root / "connect.key", (encoded + "\n").encode()) + + def pair(self, body): + core, token, secret = body["core_id"], body["token"], body["secret"] + if not all(isinstance(v, str) and 32 <= len(v) <= 100 for v in (core, token, secret)): + raise ValueError("invalid pairing") + digest = hashlib.sha256(token.encode()).hexdigest() + with self.db() as db: + db.execute("BEGIN IMMEDIATE") + current = db.execute("SELECT value FROM state WHERE key='owner'").fetchone() + if current: + owner = json.loads(current[0]) + if owner["core_id"] != core or not hmac.compare_digest(owner["token"], digest): + raise PermissionError("already paired") + else: + row = db.execute("SELECT value FROM state WHERE key='invitation'").fetchone() + invite = json.loads(row[0]) if row else {} + if invite.get("expires_at", 0) <= time.time() or not hmac.compare_digest( + invite.get("hash", ""), hashlib.sha256(secret.encode()).hexdigest() + ): + raise PermissionError("invalid invitation") + db.execute( + "INSERT INTO state VALUES('owner',?)", + (json.dumps({"core_id": core, "token": digest}),), + ) + db.execute("DELETE FROM state WHERE key='invitation'") + private_write( + self.root / "connect.key", b"PAIRED: key consumed; use the connected Mission Core.\n" + ) + return self.status() + + def authorize(self, token): + with self.db() as db: + row = db.execute("SELECT value FROM state WHERE key='owner'").fetchone() + return bool( + row + and hmac.compare_digest( + json.loads(row[0])["token"], hashlib.sha256(token.encode()).hexdigest() + ) + ) + + def status(self): + from . import VERSION + + with self.db() as db: + count, latest = db.execute("SELECT COUNT(*),MAX(received) FROM packages").fetchone() + devices = db.execute("SELECT COUNT(*) FROM devices").fetchone()[0] + return { + "schema": "missioncore.vps-host/v1", + "host_id": self.config["host_id"], + "version": VERSION, + "tracker": self.config["tracker"], + "pending_packages": count, + "last_packet_at": latest, + "devices": devices, + "capabilities": [ + "arnavi-b2-internal", + "arnavi-b2-durable-operations-v1", + "arnavi-b2-sim-guard-v1", + ], + } + + def set_devices(self, items): + if not isinstance(items, list) or len(items) > 10000: + raise ValueError("invalid devices") + rows, identities = [], [] + for item in items: + imei, instance = item["imei"], item["instance_id"] + if ( + not isinstance(imei, str) + or not imei.isascii() + or not imei.isdigit() + or len(imei) != 15 + ): + raise ValueError("invalid identity") + if not isinstance(instance, str) or len(instance) != 32: + raise ValueError("invalid instance") + rows.append((imei, instance)) + if "device_id" in item: + number = item["device_id"] + if type(number) is not int or not 1 <= number <= 0xFFFFFFFF: + raise ValueError("invalid numeric device identity") + identities.append((imei, number)) + if len({r[0] for r in rows}) != len(rows): + raise ValueError("duplicate identity") + with self.db() as db: + db.execute("BEGIN IMMEDIATE") + for imei, number in identities: + previous = db.execute( + "SELECT number FROM device_ids WHERE imei=?", (imei,) + ).fetchone() + if previous and previous[0] != number: + raise ValueError("numeric device identity conflict") + db.execute("INSERT OR IGNORE INTO device_ids VALUES(?,?)", (imei, number)) + db.execute("DELETE FROM devices") + db.executemany("INSERT INTO devices VALUES(?,?)", rows) + + def numeric_id(self, imei): + with self.db() as db: + row = db.execute( + "SELECT number FROM device_ids JOIN devices USING(imei) WHERE imei=?", (imei,) + ).fetchone() + return row[0] if row else None + + def admitted(self, imei): + with self.db() as db: + row = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone() + return row[0] if row else None + + def append(self, imei, raw, packets): + # Reserve disk for system services. Refuse ACK when durable storage cannot accept data. + if os.statvfs(self.root).f_bavail * os.statvfs(self.root).f_frsize < 256 * 1024**2: + raise OSError("journal storage reserve") + digest = hashlib.sha256(imei.encode() + raw).hexdigest() + with self.db(write=True) as db: + device = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone() + if not device: + raise PermissionError("device not admitted") + if db.execute("SELECT 1 FROM receipts WHERE digest=?", (digest,)).fetchone(): + return + # Fixed 512 MiB journal budget; backpressure, never drop unacknowledged data. + pages = db.execute("PRAGMA page_count").fetchone()[0] + free = db.execute("PRAGMA freelist_count").fetchone()[0] + page_size = db.execute("PRAGMA page_size").fetchone()[0] + if (pages - free) * page_size > 512 * 1024**2: + raise OSError("journal full") + db.execute( + "INSERT OR IGNORE INTO packages(imei,instance,digest,received,raw,packets) " + "VALUES(?,?,?,?,?,?)", + (imei, device[0], digest, time.time(), raw, json.dumps(packets)), + ) + + def fetch(self, after): + with self.db() as db: + rows = db.execute( + "SELECT id,instance,digest,received,raw,packets FROM packages " + "WHERE id>? ORDER BY id LIMIT 20", + (after,), + ).fetchall() + return { + "items": [ + { + "id": r[0], + "instance_id": r[1], + "digest": r[2], + "received_at": r[3], + "raw": base64.b64encode(r[4]).decode(), + } + for r in rows + ] + } + + def acknowledge(self, through): + with self.db() as db: + db.execute( + "INSERT OR IGNORE INTO receipts SELECT digest,received FROM packages WHERE id<=?", + (through,), + ) + db.execute("DELETE FROM packages WHERE id<=?", (through,)) + db.execute("DELETE FROM receipts WHERE at MAX_BYTES + or shutil.disk_usage(destination.parent).free < required * 2 + 256 * 1024**2 + ): + raise ValueError("insufficient archive space or state exceeds portable limit") + fence = engine.ROOT / "migration-fence.json" + record = { + "schema": SCHEMA, + "migration_id": uuid.uuid4().hex, + "created_at": time.time(), + "monotonic": time.monotonic(), + "artifact": proposal["artifact"], + "status": "quiescing", + } + # Persistent unit condition blocks manual/automatic starts and host reboots. + # Failure after this point stays fenced; the operator can explicitly resume. + durable_json(fence, record) + engine.run("systemctl", "stop", SERVICE) + active = subprocess.run(["systemctl", "is-active", SERVICE], capture_output=True).stdout.strip() + if active not in (b"inactive", b"failed"): + raise ValueError("source did not stop; migration remains fenced") + with tempfile.TemporaryDirectory(prefix=".ndc-vps-export-", dir=destination.parent) as work: + work = Path(work) + state = work / "state" + state.mkdir(mode=0o700) + for name in FILES - {"journal.sqlite3"}: + shutil.copyfile(engine.STATE / name, state / name) + (state / name).chmod(0o600) + with ( + sqlite3.connect( + (engine.STATE / "journal.sqlite3").as_uri() + "?mode=ro", uri=True + ) as src, + sqlite3.connect(state / "journal.sqlite3") as dst, + ): + src.backup(dst) + (state / "journal.sqlite3").chmod(0o600) + check_state(state) + record.update( + status="source_fenced", + files={ + "state/" + name: { + "sha256": sha(state / name), + "size": (state / name).stat().st_size, + } + for name in sorted(FILES) + }, + ) + durable_json(work / "manifest.json", record) + archive = work / "state.tar.gz" + with tarfile.open(archive, "w:gz", format=tarfile.USTAR_FORMAT) as tar: + for name in ["manifest.json", *record["files"]]: + info = tar.gettarinfo(work / name, arcname=name) + info.mode = 0o600 + info.mtime = int(info.mtime) + info.uid = info.gid = 0 + info.uname = info.gname = "" + with (work / name).open("rb") as stream: + tar.addfile(info, stream) + archive.chmod(0o600) + with archive.open("rb") as stream: + os.fsync(stream.fileno()) + # Atomic publication without ever overwriting an existing backup. + os.link(archive, destination) + sync_directory(destination.parent) + digest = sha(destination) + durable_json(fence, {**record, "archive_sha256": digest}) + print( + json.dumps( + { + "status": "source_fenced", + "archive": str(destination), + "sha256": digest, + "migration_id": record["migration_id"], + } + ) + ) + + +def unpack(archive, expected, directory, artifact): + if not re.fullmatch(r"[a-f0-9]{64}", expected) or archive.is_symlink() or not archive.is_file(): + raise ValueError("regular archive and exact SHA-256 required") + if archive.stat().st_size > MAX_BYTES or sha(archive) != expected: + raise ValueError("archive digest or size mismatch") + expected_names = {"manifest.json"} | {"state/" + name for name in FILES} + seen, total = set(), 0 + # Never extract paths/links/modes supplied by an archive or deserialize code. + with tarfile.open(archive, "r:gz") as tar: + for member in tar: + if ( + member.name not in expected_names + or member.name in seen + or not member.isfile() + or member.pax_headers + ): + raise ValueError("invalid portable archive member") + total += member.size + limit = MAX_BYTES if member.name == "state/journal.sqlite3" else 1024 * 1024 + if member.size > limit or total > MAX_BYTES: + raise ValueError("portable archive size limit") + seen.add(member.name) + target = directory / member.name + target.parent.mkdir(mode=0o700, exist_ok=True) + with target.open("xb") as stream, tar.extractfile(member) as source: + target.chmod(0o600) + shutil.copyfileobj(source, stream, 1024 * 1024) + if seen != expected_names: + raise ValueError("incomplete portable archive") + record = json.loads((directory / "manifest.json").read_text()) + if ( + record.get("schema") != SCHEMA + or record.get("status") != "source_fenced" + or record.get("artifact") != artifact + or set(record.get("files", {})) != expected_names - {"manifest.json"} + ): + raise ValueError("archive requires its exact installer release and complete manifest") + for name, item in record["files"].items(): + if item != {"sha256": sha(directory / name), "size": (directory / name).stat().st_size}: + raise ValueError("state integrity mismatch") + return record, check_state(directory / "state") + + +def import_state(engine, archive, expected): + if os.geteuid() != 0: + raise ValueError("root required") + for path in (engine.ROOT, engine.STATE, engine.UNIT): + if path.exists() or path.is_symlink(): + raise ValueError("portable import requires an empty product installation") + if shutil.disk_usage(engine.STATE.parent).free < MAX_BYTES + 256 * 1024**2: + raise ValueError("portable import requires 2.25 GiB free staging space") + with tempfile.TemporaryDirectory(prefix=".ndc-vps-import-", dir=engine.STATE.parent) as work: + work = Path(work) + record, config = unpack(archive, expected, work, engine.digest()) + args = options(config) + proposal = engine.plan(args) # OS, prerequisites, ports and firewall, before mutation. + args.expect = proposal["plan_sha256"] + # Install this shipped code and unit, creating the target's system account. + # Only identity/journal state crosses hosts; no old executable/unit/firewall does. + staged_state = work / "state" + staged_state.chmod(0o700) + for path in staged_state.iterdir(): + with path.open("rb") as stream: + os.fsync(stream.fileno()) + sync_directory(staged_state) + # Same-filesystem rename publishes all state at once. A failed copy + # must not leave a partial identity or require twice the journal space. + os.rename(staged_state, engine.STATE) + sync_directory(engine.STATE.parent) + engine.apply(args, proposal) + durable_json( + engine.ROOT / "imported-state.json", + { + "schema": SCHEMA, + "migration_id": record["migration_id"], + "archive_sha256": expected, + "imported_at": time.time(), + "endpoint_preserved": True, + }, + ) + print( + json.dumps( + { + "status": "imported", + "identity_preserved": True, + "migration_id": record["migration_id"], + "endpoint_preserved": True, + } + ) + ) + + +def resume_source(engine): + if os.geteuid() != 0: + raise ValueError("root required") + fence = engine.ROOT / "migration-fence.json" + record = json.loads(fence.read_text()) + if record.get("schema") != SCHEMA or record.get("artifact") != engine.digest(): + raise ValueError("source fence requires the same installer") + fence.unlink() + sync_directory(fence.parent) + try: + engine.run("systemctl", "start", SERVICE) + engine.healthy() + except Exception: + durable_json(fence, record) + engine.run("systemctl", "stop", SERVICE) + raise + durable_json( + engine.ROOT / "migration-cancelled.json", + {"migration_id": record["migration_id"], "resumed_at": time.time()}, + ) + print(json.dumps({"status": "source_resumed", "migration_id": record["migration_id"]})) diff --git a/apps/vps-host/qualify_configuration.py b/apps/vps-host/qualify_configuration.py new file mode 100644 index 00000000..aebd6ba0 --- /dev/null +++ b/apps/vps-host/qualify_configuration.py @@ -0,0 +1,100 @@ +"""Bounded HTTP clock exchange over real loopback streams; no physical B2.""" + +import asyncio +import json +import tempfile +import time +from pathlib import Path + +from ndc_vps.commands import frame +from ndc_vps.service import Service +from ndc_vps.store import Store +from ndc_vps.web_protocol import time_reply + + +async def qualify(): + with tempfile.TemporaryDirectory(prefix="ndc-vps-clock-") as directory: + root = Path(directory) + (root / "host.json").write_text( + json.dumps( + {"host_id": "vps_" + "a" * 64, "tracker": {"host": "example.org", "port": 9922}} + ) + ) + store = Store(root) + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + service = Service(store) + server = await asyncio.start_server(service.tracker, "127.0.0.1", 0) + writers = [] + try: + port = server.sockets[0].getsockname()[1] + monitor, writer = await asyncio.open_connection("127.0.0.1", port) + writers.append(writer) + writer.write(b"\xff\x23" + int(imei).to_bytes(8, "little")) + await writer.drain() + assert (await monitor.readexactly(9))[0] == 0x7B + reader, writer = await asyncio.open_connection("127.0.0.1", port) + writers.append(writer) + request = ( + b"[\x01\x00\x0f" + + int(imei).to_bytes(8, "little") + + bytes.fromhex("0001e7020000075d") + ) + for _ in range(2): + before = int(time.time()) + writer.write(b"POST /c/index.php HTTP/1.1\r\nContent-Length: 20\r\n\r\n" + request) + await writer.drain() + header = await reader.readuntil(b"\r\n\r\n") + assert header.startswith(b"HTTP/1.1 200 OK\r\n") + assert b"Content-Length: 10\r\n" in header + body = await reader.readexactly(10) + seconds = int.from_bytes(body[5:9], "big") + assert before <= seconds <= int(time.time()) + assert body == time_reply(seconds) + with store.db() as db: + assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 0 + session = next(iter(service.commands.sessions[imei])) + service.commands.session_activity[imei, session] = time.monotonic() - 20 + original = service.commands.submit( + {"id": "d" * 32, "imei": imei, "kind": "read-settings", "password": "123456"} + ) + service.notify(imei) + await asyncio.sleep(0.1) + assert service.commands.get("d" * 32)["state"] == "queued" + # A real incoming telemetry frame wakes the waiting sender. + data = int(time.time()).to_bytes(4, "little") + b"\x63\0\0\0\0" + writers[0].write(b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]") + await writers[0].drain() + expected = frame("123456*GETP") + received = await monitor.readexactly(len(expected) + 4) + assert received in (b"{\x00\x01}" + expected, expected + b"{\x00\x01}") + receipt = service.commands.get("d" * 32) + assert receipt["state"] == "dispatched" + assert receipt["expires_at"] == original["expires_at"] + assert service.commands.take(imei, session) is None + finally: + server.close() + for writer in writers: + writer.close() + await asyncio.gather( + *(writer.wait_closed() for writer in writers), return_exceptions=True + ) + for _ in range(30): + if service.connections == 0: + break + await asyncio.sleep(0.01) + assert service.connections == 0 and not service.wake + await server.wait_closed() + return { + "ok": True, + "clock_replies": 2, + "same_http_connection": True, + "clock_commands_created": 0, + "stale_configuration_deferred": True, + "fresh_packet_dispatched_once": True, + "physical_devices_used": False, + } + + +if __name__ == "__main__": + print(json.dumps(asyncio.run(asyncio.wait_for(qualify(), 8)), sort_keys=True)) diff --git a/apps/vps-host/qualify_delivery.py b/apps/vps-host/qualify_delivery.py new file mode 100644 index 00000000..a003808f --- /dev/null +++ b/apps/vps-host/qualify_delivery.py @@ -0,0 +1,117 @@ +"""Bounded Linux loopback qualification; no tracker, firewall or service changes. + +Run with the unpacked release's Python. Two ephemeral local TCP connections, +at most 64 KiB synthetic data, no dependencies or persistent state. +""" + +import asyncio +import json +import socket +import sys +import time +import uuid +from datetime import UTC, datetime + +from ndc_vps import VERSION +from ndc_vps.delivery import Delivery, queued_bytes + + +async def qualify(blocked): + loop = asyncio.get_running_loop() + accepted = loop.create_future() + finished = asyncio.Event() + handler_done = asyncio.Event() + + async def handler(reader, writer): + accepted.set_result(writer) + try: + await finished.wait() + finally: + writer.transport.abort() + handler_done.set() + + server = await asyncio.start_server(handler, "127.0.0.1", 0) + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024) + client.setblocking(False) + guard = None + try: + await loop.sock_connect(client, server.sockets[0].getsockname()) + writer = await asyncio.wait_for(accepted, 2) + sock = writer.get_extra_info("socket") + sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096) + aborted = [] + + class ObservedDelivery(Delivery): + def abort(self, reason="connection_closed"): + aborted.append(time.monotonic()) + super().abort(reason) + + guard = ObservedDelivery(writer) + assert guard.ready() + started = time.monotonic() + deadline = started + 0.75 + payload = b"x" * (65536 if blocked else 12) + guard.write(payload, deadline) + if not blocked: + assert await asyncio.wait_for(loop.sock_recv(client, 12), 1) == payload + await asyncio.sleep(0.15) + kernel = queued_bytes(sock) + buffered = writer.transport.get_write_buffer_size() + if blocked: + assert kernel > 0, "The peer did not actually block TCP delivery" + assert not guard.ready(), "An unacknowledged prefix must block a new command" + else: + assert guard.ready(), "A fully acknowledged stream should accept a new command" + await asyncio.sleep(0.85) + if blocked: + assert writer.is_closing() and sock.fileno() == -1 + assert aborted and 0 <= aborted[0] - deadline < 0.25 + reset = False + async with asyncio.timeout(2): + try: + while await loop.sock_recv(client, 4096): + pass + except ConnectionResetError: + reset = True + assert reset, "Expected abortive close, not graceful buffered delivery" + else: + assert not writer.is_closing() and not aborted and not guard.pending + return { + "case": "blocked-receiver" if blocked else "transport-ack-without-device-reply", + "bytes": len(payload), + "kernel_queued_before_deadline": kernel, + "asyncio_queued_before_deadline": buffered, + "deadline_seconds": deadline - started, + "abort_seconds": aborted[0] - started if aborted else None, + "peer_reset": reset if blocked else False, + "passed": True, + } + finally: + if guard: + guard.abort() + client.close() + finished.set() + if accepted.done(): + await asyncio.wait_for(handler_done.wait(), 2) + server.close() + await server.wait_closed() + + +async def main(): + assert sys.platform == "linux", "Qualify on the supported Linux host" + result = { + "session_id": str(uuid.uuid4()), + "version": VERSION, + "started_utc": datetime.now(UTC).isoformat(), + "monotonic": time.monotonic(), + "cases": [], + } + for blocked in (False, True): + result["cases"].append(await qualify(blocked)) + result["completed_utc"] = datetime.now(UTC).isoformat() + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/apps/vps-host/qualify_faults.py b/apps/vps-host/qualify_faults.py new file mode 100644 index 00000000..e2072c53 --- /dev/null +++ b/apps/vps-host/qualify_faults.py @@ -0,0 +1,286 @@ +"""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("