Add independent one-second host WAN telemetry MIT source; preserve existing platform/history

This commit is contained in:
2026-11-06 13:09:12 +00:00
parent 7f7d4f6d35
commit 23a87387b8
21 changed files with 2064 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 UCVL (Youchuang Future)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+28
View File
@@ -0,0 +1,28 @@
# 独立服务器 WAN 秒级采样
该进程与原有 `toplc-node-agent/1.1.0` 分开运行。它不修改 Xray、用户计费、代理配置、Tailscale、系统路由、防火墙或账号限速。
- 每 1 秒依据 monotonic 时钟读取 Linux `/proc/net/dev`。接口取主路由表的默认物理 WAN(先 IPv4,后 IPv6),排除 loopback、Tailscale、Docker、bridge、veth、tun/tap、WireGuard 等逻辑接口。
- `rx_bytes` 为服务器 WAN 入站;`tx_bytes` 为服务器 WAN 出站。语义为 `server_host_interface` / `linux_proc_net_dev_interface_bytes`。这包括该网口上的主机流量和协议开销,不能当作个人代理计费流量,也不能与 Tailscale 逻辑流量相加。
- 用原始 counter 差值除以实际 monotonic 时间间隔计算 B/s。首点、boot/接口变更、counter 复位、过长或无效间隔使用 `null`,不会伪造 0。真实零增量仍为 0。
- 单独上传线程每 5 秒把最多 60 条样本 POST 到固定 HTTPS `https://vpn.example.invalid/api/v1/node/host-traffic/`。TLS 验证始终开启,不跟随重定向、不使用环境代理。请求超时不阻塞采样。
- 内存队列最多 60 条;满时丢旧,在新样本标明 gap 和丢失数量。已排队样本不被修改,确保超时后重试数据仍幂等。丢失/延迟不是连续假曲线。
- 每次进程启动生成新 UUID counter epoch;boot/接口/计数器复位亦生成新 epoch,避免进程崩溃重启后 sequence 唯一键冲突。没有凭证缓存或持久化队列。
- 仅解析原 `node.env` 中 `NODE_SLUG`、`NODE_TOKEN` 两项,不执行该文件、不导出或记录其它密钥。上传凭证只保留内存。系统服务需要 root 读取原来的 0600 文件,capabilities 全部去除并启用只读系统沙箱。
输入契约 `contract: 1`:顶层 `node_slug/boot_id/interface/kind/counter_semantics/samples`;每样本 `sequence/observed_at/monotonic_ns/counter_epoch/interval_seconds/rx_bytes/tx_bytes/rx_bytes_per_second/tx_bytes_per_second/quality/gap_before/dropped_samples_before`。原始字节计数限制在 SQLite signed int64 范围。成功 2xx 表示整批持久化,失败不确认队列。后端未提供此端点时上传会安全失败,队列保持有界。
## 审核和安装
安装前必须先完成中央 ingest 端点。部署包仅包含本独立服务,可先执行:
```sh
python3 -B host_traffic_sampler.py --node-env /opt/toplc-vpn-node/node.env --check-config
```
`--check-config` 只读取本机接口和配置,既不发送网络请求,也不打印 token。由 root 审核冻结包 SHA256 后执行同包 `deploy_host_traffic_sampler.sh --install EXPECTED_NODE_SLUG`;该脚本会拒绝既有 sampler 安装及目标 slug 不一致,校验原主 agent/compose/env/service 文件前后 hash 相同,不修改原服务。安装过程失败时保留现场以供检查,不应盲目重试或删除旧现场。
离线测试:`python3 -m unittest discover -s . -p test_host_traffic_sampler.py -v`。测试不连接网络、不读生产凭证。
MIT source supplement: these files are published as a separate directory only. They do not replace the platform root, existing routes, source history or other licenses. Integration tests use an existing Django platform model fixture; production model snapshots, accounts, tokens, SQLite state and local output evidence are not included. Configure example endpoints for your deployment. Source publication does not assert production acceptance.
@@ -0,0 +1,63 @@
#!/bin/sh
# Installs only this new sampler. Does not alter agent/Xray/env/network rules.
set -eu
umask 077
if [ "$#" -ne 2 ] || [ "$1" != "--install" ]; then
echo 'Usage: deploy_host_traffic_sampler.sh --install EXPECTED_NODE_SLUG' >&2
exit 2
fi
test "$(id -u)" = 0
BUNDLE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
export PYTHONDONTWRITEBYTECODE=1
python3 - "$BUNDLE" "$2" <<'PY'
import hashlib,json,os,pathlib,re,shutil,stat,subprocess,sys
from datetime import datetime,timezone
bundle=pathlib.Path(sys.argv[1]);expected=sys.argv[2]
assert re.fullmatch(r'[A-Za-z0-9_-]{1,120}',expected),'Invalid expected node slug'
destination=pathlib.Path('/opt/toplc-vpn-host-traffic')
unit=pathlib.Path('/etc/systemd/system/toplc-vpn-host-traffic.service')
for path in (destination,unit):
assert not path.exists() and not path.is_symlink(),'Sampler already exists; review prior attempt before changing it'
for ancestor in path.parents:
assert not ancestor.is_symlink(),'Linked installation parent refused'
manifest=json.loads((bundle/'manifest.json').read_text())
assert manifest['kind']=='toplc-host-traffic-sampler-bundle' and manifest['version']=='1.0.0'
expected_files={'host_traffic_sampler.py','test_host_traffic_sampler.py','toplc-vpn-host-traffic.service','README.md','host-traffic-contract-fixture.json','deploy_host_traffic_sampler.sh'}
assert set(manifest['files'])==expected_files,'Bundle inventory differs'
assert {p.name for p in bundle.iterdir()}==expected_files|{'manifest.json'},'Unmanifested bundle files'
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
for name,value in manifest['files'].items():
path=bundle/name
assert path.is_file() and not path.is_symlink() and digest(path)==value,'Bundle hash mismatch'
env=pathlib.Path('/opt/toplc-vpn-node/node.env')
assert env.is_file() and not env.is_symlink() and env.stat().st_uid==0 and stat.S_IMODE(env.stat().st_mode)==0o600,'Expected root0600 node.env'
agent=pathlib.Path('/opt/toplc-vpn-node/agent.py')
compose=pathlib.Path('/opt/toplc-vpn-node/docker-compose.yml')
agent_unit=pathlib.Path('/etc/systemd/system/toplc-vpn-node-agent.service')
protected=[env,agent,compose,agent_unit]
before={str(path):digest(path) for path in protected}
# Import from verified bundle; reads only slug/token and never executes node.env.
sys.path.insert(0,str(bundle))
import host_traffic_sampler as sampler
credentials=sampler.load_credentials(env)
assert credentials.node_slug==expected,'Existing node slug differs'
configuration=subprocess.run(['/usr/bin/python3','-B',str(bundle/'host_traffic_sampler.py'),'--check-config'],capture_output=True,text=True,timeout=10)
assert configuration.returncode==0,'Sampler configuration or physical WAN detection failed'
safe=json.loads(configuration.stdout)
assert safe['node_slug']==expected and safe['configuration_valid'] is True and safe['network_requested'] is False
subprocess.run(['systemd-analyze','verify',str(bundle/'toplc-vpn-host-traffic.service')],check=True,capture_output=True,timeout=15)
destination.mkdir(mode=0o750)
for name in ('host_traffic_sampler.py','README.md'):
shutil.copyfile(bundle/name,destination/name);os.chmod(destination/name,0o600)
assert digest(destination/name)==manifest['files'][name]
shutil.copyfile(bundle/'toplc-vpn-host-traffic.service',unit);os.chmod(unit,0o644)
assert digest(unit)==manifest['files']['toplc-vpn-host-traffic.service']
subprocess.run(['systemctl','daemon-reload'],check=True,timeout=20)
subprocess.run(['systemctl','enable','--now','toplc-vpn-host-traffic.service'],check=True,capture_output=True,timeout=20)
subprocess.run(['systemctl','is-active','--quiet','toplc-vpn-host-traffic.service'],check=True,timeout=10)
after={str(path):digest(path) for path in protected}
assert before==after,'Protected existing deployment files changed; inspect external activity'
receipt={'kind':'toplc-host-traffic-sampler-install','version':'1.0.0','node_slug':expected,'interface':safe['interface'],'kind_semantics':'server_host_interface','counter_semantics':'linux_proc_net_dev_interface_bytes','sample_seconds':1,'upload_seconds':5,'queue_capacity':60,'protected_existing_files_unchanged':True,'network_rules_modified':False,'existing_agent_restarted':False,'xray_restarted':False,'new_sampler_active':True,'installed_at':datetime.now(timezone.utc).isoformat(),'bundle_files':manifest['files']}
with (destination/'install-receipt.json').open('x') as handle:json.dump(receipt,handle,indent=2);handle.write('\n')
print(json.dumps(receipt))
PY
@@ -0,0 +1,80 @@
{
"contract": 1,
"node_slug": "node-example",
"boot_id": "dd268f12-470c-4b7a-bb6a-3960072d659d",
"interface": "eth0",
"kind": "server_host_interface",
"counter_semantics": "linux_proc_net_dev_interface_bytes",
"samples": [
{
"sequence": 1,
"observed_at": "2026-11-06T06:00:01+00:00",
"monotonic_ns": 1000000000,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interval_seconds": 0.0,
"rx_bytes": 1000,
"tx_bytes": 500,
"rx_bytes_per_second": null,
"tx_bytes_per_second": null,
"quality": "baseline",
"gap_before": false,
"dropped_samples_before": 0
},
{
"sequence": 2,
"observed_at": "2026-11-06T06:00:02+00:00",
"monotonic_ns": 2000000000,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interval_seconds": 1.0,
"rx_bytes": 1200,
"tx_bytes": 600,
"rx_bytes_per_second": 200.0,
"tx_bytes_per_second": 100.0,
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
},
{
"sequence": 3,
"observed_at": "2026-11-06T06:00:03+00:00",
"monotonic_ns": 3000000000,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interval_seconds": 1.0,
"rx_bytes": 2000,
"tx_bytes": 900,
"rx_bytes_per_second": 800.0,
"tx_bytes_per_second": 300.0,
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
},
{
"sequence": 4,
"observed_at": "2026-11-06T06:00:04+00:00",
"monotonic_ns": 4000000000,
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
"interval_seconds": 1.0,
"rx_bytes": 20,
"tx_bytes": 10,
"rx_bytes_per_second": null,
"tx_bytes_per_second": null,
"quality": "reset",
"gap_before": true,
"dropped_samples_before": 0
},
{
"sequence": 5,
"observed_at": "2026-11-06T06:00:05+00:00",
"monotonic_ns": 5000000000,
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
"interval_seconds": 1.0,
"rx_bytes": 100,
"tx_bytes": 50,
"rx_bytes_per_second": 80.0,
"tx_bytes_per_second": 40.0,
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
}
]
}
@@ -0,0 +1,358 @@
#!/usr/bin/env python3
"""One-second physical WAN byte samples; independent of Xray/config/billing.
Linux /proc/net/dev RX means bytes into the server's default physical WAN
interface. TX means bytes out. These are host-interface counters, not per-user
proxy usage, application payload, or Tailscale logical-interface counters.
"""
from __future__ import annotations
import argparse
from collections import deque
import copy
from dataclasses import dataclass, field
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import signal
import ssl
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
VERSION = "toplc-host-traffic/1.0.0"
ENDPOINT = "https://vpn.example.invalid/api/v1/node/host-traffic/"
MAX_COUNTER = 2**63 - 1
MAX_SEQUENCE = 2**53 - 1
MAX_BATCH_BYTES = 64 * 1024
SAMPLE_SECONDS = 1.0
UPLOAD_SECONDS = 5.0
QUEUE_CAPACITY = 60
@dataclass(frozen=True)
class Credentials:
node_slug: str
token: str = field(repr=False)
@dataclass(frozen=True)
class Snapshot:
boot_id: str
interface: str
rx_bytes: int
tx_bytes: int
monotonic_ns: int
observed_at: str
@dataclass(frozen=True)
class Envelope:
boot_id: str
interface: str
sample: dict
def load_credentials(path: Path) -> Credentials:
# Read only these two data values; never source/evaluate an env file or copy
# Reality credentials into os.environ, output, state, or an upload payload.
wanted = {}
for line in Path(path).read_text(encoding="utf-8").splitlines():
key, separator, value = line.partition("=")
key = key.strip()
if not separator or key not in {"NODE_SLUG", "NODE_TOKEN"}:
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
if key in wanted:
raise ValueError("Duplicate node credential field")
wanted[key] = value
slug, token = wanted.get("NODE_SLUG", ""), wanted.get("NODE_TOKEN", "")
if not re.fullmatch(r"[A-Za-z0-9_-]{1,120}", slug):
raise ValueError("Invalid or missing node slug")
if not re.fullmatch(r"[A-Za-z0-9._~+/-]{1,512}=*", token):
raise ValueError("Invalid or missing node token")
return Credentials(slug, token)
class ProcWanReader:
EXCLUDED = ("lo", "tailscale", "docker", "veth", "br-", "virbr", "tun", "tap", "wg")
def __init__(self, proc: Path = Path("/proc"), sysfs: Path = Path("/sys")):
self.proc, self.sysfs = Path(proc), Path(sysfs)
def physical(self, name: str) -> bool:
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", name) or name.startswith(self.EXCLUDED):
return False
path = self.sysfs / "class/net" / name
try:
return (path / "device").exists() and (path / "type").read_text().strip() == "1"
except OSError:
return False
def default_interface(self) -> str:
routes = []
try:
for line in (self.proc / "net/route").read_text().splitlines()[1:]:
fields = line.split()
if len(fields) >= 8 and fields[1] == "00000000" and fields[7] == "00000000":
if int(fields[3], 16) & 1 and self.physical(fields[0]):
routes.append((int(fields[6]), fields[0]))
except (OSError, ValueError):
pass
if not routes:
try:
for line in (self.proc / "net/ipv6_route").read_text().splitlines():
fields = line.split()
if len(fields) >= 10 and fields[0] == "0" * 32 and fields[1] == "00":
if int(fields[8], 16) & 1 and self.physical(fields[9]):
routes.append((int(fields[5], 16), fields[9]))
except (OSError, ValueError):
pass
if not routes:
raise OSError("No default physical WAN interface available")
return min(routes)[1]
def read(self) -> Snapshot:
interface = self.default_interface()
boot_id = str(uuid.UUID((self.proc / "sys/kernel/random/boot_id").read_text().strip()))
for line in (self.proc / "net/dev").read_text().splitlines():
name, separator, counters = line.partition(":")
if separator and name.strip() == interface:
values = counters.split()
if len(values) < 16:
raise OSError("Incomplete physical WAN counters")
return Snapshot(boot_id, interface, int(values[0]), int(values[8]),
time.monotonic_ns(), datetime.now(timezone.utc).isoformat())
raise OSError("Default physical WAN interface counters unavailable")
class CounterTracker:
def __init__(self):
self.previous = None
self.counter_epoch = str(uuid.uuid4())
self.sequence = 0
self.missing = 0
def note_missing(self, count: int = 1):
self.sequence += count
self.missing += count
def observe(self, snapshot: Snapshot) -> Envelope:
for value in (snapshot.rx_bytes, snapshot.tx_bytes):
if type(value) is not int or not 0 <= value <= MAX_COUNTER:
raise ValueError("WAN counter outside signed-64-bit contract")
if type(snapshot.monotonic_ns) is not int or snapshot.monotonic_ns < 1:
raise ValueError("Positive monotonic timestamp required")
boot_id = str(uuid.UUID(snapshot.boot_id))
previous = self.previous
elapsed = 0.0 if previous is None else (snapshot.monotonic_ns - previous.monotonic_ns) / 1e9
quality, rx_rate, tx_rate = "baseline", None, None
if previous is not None:
if boot_id != str(uuid.UUID(previous.boot_id)):
quality, elapsed = "boot_changed", 0.0
elif snapshot.interface != previous.interface:
quality = "interface_changed"
elif snapshot.rx_bytes < previous.rx_bytes or snapshot.tx_bytes < previous.tx_bytes:
quality = "reset"
elif not 0.5 <= elapsed <= 3.0:
quality = "gap"
else:
quality = "ok"
rx_rate = (snapshot.rx_bytes - previous.rx_bytes) / elapsed
tx_rate = (snapshot.tx_bytes - previous.tx_bytes) / elapsed
if max(rx_rate, tx_rate) > 1e12:
quality, rx_rate, tx_rate = "gap", None, None
if quality in {"boot_changed", "interface_changed", "reset"}:
self.counter_epoch = str(uuid.uuid4())
elif quality == "gap" and elapsed <= 0:
self.counter_epoch = str(uuid.uuid4())
self.sequence += 1
if self.sequence > MAX_SEQUENCE:
# Practically unreachable (>285M years at 1 Hz); still no key reuse.
self.counter_epoch, self.sequence = str(uuid.uuid4()), 1
quality, rx_rate, tx_rate = "baseline", None, None
row = {"sequence": self.sequence, "observed_at": snapshot.observed_at,
"monotonic_ns": snapshot.monotonic_ns, "counter_epoch": self.counter_epoch,
"interval_seconds": max(0.0, elapsed), "rx_bytes": snapshot.rx_bytes,
"tx_bytes": snapshot.tx_bytes, "rx_bytes_per_second": rx_rate,
"tx_bytes_per_second": tx_rate, "quality": quality,
"gap_before": bool(self.missing or quality not in {"baseline", "ok"}),
"dropped_samples_before": 0}
self.previous, self.missing = snapshot, 0
return Envelope(boot_id, snapshot.interface, row)
class BoundedSampleQueue:
def __init__(self, capacity: int = QUEUE_CAPACITY):
if type(capacity) is not int or not 1 <= capacity <= QUEUE_CAPACITY:
raise ValueError("Queue capacity outside contract")
self.capacity, self.rows, self.lock = capacity, deque(), threading.Lock()
def put(self, envelope: Envelope):
# Never mutate an already queued/transmitted record: an HTTP timeout may
# hide a committed batch, and retry bytes must remain idempotent.
row = copy.deepcopy(envelope.sample)
with self.lock:
if len(self.rows) >= self.capacity:
dropped = self.rows.popleft()
row["gap_before"] = True
row["dropped_samples_before"] += 1 + dropped.sample["dropped_samples_before"]
self.rows.append(Envelope(envelope.boot_id, envelope.interface, row))
def batch(self, limit: int = QUEUE_CAPACITY) -> list[Envelope]:
with self.lock:
if not self.rows:
return []
group = self.rows[0].boot_id, self.rows[0].interface
result = []
for row in self.rows:
if len(result) >= min(limit, QUEUE_CAPACITY) or (row.boot_id, row.interface) != group:
break
result.append(copy.deepcopy(row))
return result
def acknowledge(self, batch: list[Envelope]):
keys = {(row.sample["counter_epoch"], row.sample["sequence"]) for row in batch}
with self.lock:
self.rows = deque(row for row in self.rows
if (row.sample["counter_epoch"], row.sample["sequence"]) not in keys)
def build_payload(batch: list[Envelope], node_slug: str) -> dict:
if not 1 <= len(batch) <= QUEUE_CAPACITY:
raise ValueError("Empty or oversized upload batch")
first = batch[0]
if any((row.boot_id, row.interface) != (first.boot_id, first.interface) for row in batch):
raise ValueError("Mixed interface or boot in upload batch")
return {"contract": 1, "node_slug": node_slug, "boot_id": first.boot_id,
"interface": first.interface, "kind": "server_host_interface",
"counter_semantics": "linux_proc_net_dev_interface_bytes",
"samples": [copy.deepcopy(row.sample) for row in batch]}
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise urllib.error.HTTPError(newurl, code, "Host traffic redirects are refused", headers, fp)
class HttpTransport:
def __init__(self, endpoint: str = ENDPOINT):
parsed = urllib.parse.urlsplit(endpoint)
if (parsed.scheme != "https" or parsed.hostname != "vpn.example.invalid"
or parsed.port not in {None, 443} or parsed.username or parsed.password
or parsed.path != "/api/v1/node/host-traffic/" or parsed.query or parsed.fragment):
raise ValueError("Untrusted host traffic endpoint")
self.endpoint = endpoint
self.ssl_context = ssl.create_default_context()
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
urllib.request.HTTPSHandler(context=self.ssl_context), NoRedirect())
def send(self, payload: dict, credentials: Credentials):
body = json.dumps(payload, separators=(",", ":"), allow_nan=False).encode("utf-8")
if len(body) > MAX_BATCH_BYTES:
raise ValueError("Host traffic batch exceeds 64 KiB")
request = urllib.request.Request(self.endpoint, data=body, method="POST", headers={
"Authorization": "Bearer " + credentials.token, "X-Node-Slug": credentials.node_slug,
"X-Agent-Version": VERSION, "User-Agent": VERSION, "Content-Type": "application/json"})
with self.opener.open(request, timeout=8) as response:
if not 200 <= response.status < 300:
raise OSError("Host traffic batch was not committed")
response.read(4096) # Body is not logged; HTTP 2xx acknowledges durable whole batch.
class Uploader(threading.Thread):
def __init__(self, queue: BoundedSampleQueue, credentials: Credentials, transport,
stop: threading.Event, interval: float = UPLOAD_SECONDS, log=None):
super().__init__(name="host-traffic-uploader", daemon=True)
self.queue, self.credentials, self.transport, self.stop = queue, credentials, transport, stop
self.interval = interval
self.log = log or (lambda text: print(text, file=sys.stderr, flush=True))
self.last_error_log = -1e30
def upload_once(self) -> bool:
batch = self.queue.batch()
if not batch:
return True
try:
self.transport.send(build_payload(batch, self.credentials.node_slug), self.credentials)
self.queue.acknowledge(batch)
return True
except Exception as error:
# Never include request, headers, response body, exception text, or
# credential objects. Failures are bounded and cannot block sampling.
now = time.monotonic()
if now - self.last_error_log >= 60:
status = error.code if isinstance(error, urllib.error.HTTPError) else "none"
self.log("host-traffic upload failed: type=" + type(error).__name__ + ",status=" + str(status))
self.last_error_log = now
return False
def run(self):
while not self.stop.wait(self.interval):
self.upload_once()
def run_sampler(reader, queue: BoundedSampleQueue, tracker: CounterTracker,
stop: threading.Event, log=None):
log = log or (lambda text: print(text, file=sys.stderr, flush=True))
deadline, last_error_log = time.monotonic(), -1e30
while not stop.is_set():
if stop.wait(max(0.0, deadline - time.monotonic())):
break
try:
queue.put(tracker.observe(reader.read()))
except (OSError, ValueError):
tracker.note_missing()
now = time.monotonic()
if now - last_error_log >= 60:
log("host-traffic sample unavailable; next valid sample will mark a gap")
last_error_log = now
deadline += SAMPLE_SECONDS
now = time.monotonic()
if deadline <= now:
skipped = int((now - deadline) // SAMPLE_SECONDS) + 1
tracker.note_missing(skipped)
deadline += skipped * SAMPLE_SECONDS
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--node-env", type=Path, default=Path("/opt/toplc-vpn-node/node.env"))
parser.add_argument("--check-config", action="store_true")
args = parser.parse_args(argv)
credentials = load_credentials(args.node_env)
reader = ProcWanReader()
if args.check_config:
snapshot = reader.read()
print(json.dumps({"version": VERSION, "node_slug": credentials.node_slug,
"interface": snapshot.interface, "kind": "server_host_interface",
"counter_semantics": "linux_proc_net_dev_interface_bytes", "configuration_valid": True,
"network_requested": False, "token_printed": False}))
return 0
stop = threading.Event()
for name in (signal.SIGTERM, signal.SIGINT):
signal.signal(name, lambda *_: stop.set())
queue, tracker = BoundedSampleQueue(), CounterTracker()
uploader = Uploader(queue, credentials, HttpTransport(), stop)
uploader.start()
try:
run_sampler(reader, queue, tracker, stop)
finally:
stop.set()
uploader.join(timeout=9)
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except (OSError, ValueError):
print("host-traffic startup refused: invalid or unreadable configuration", file=sys.stderr)
raise SystemExit(1)
@@ -0,0 +1,211 @@
"""Offline contract and failure-path tests; never opens a network connection."""
import copy
from datetime import datetime, timezone
import importlib.util
import json
from pathlib import Path
import sys
import tempfile
import threading
import time
import unittest
from unittest.mock import patch
HERE=Path(__file__).resolve().parent
sys.path.insert(0,str(HERE))
import host_traffic_sampler as target
BOOT='dd268f12-470c-4b7a-bb6a-3960072d659d'
OTHER_BOOT='8de4d479-f314-4f3d-aa17-a160053b3ac9'
def snap(rx=1000,tx=500,seconds=1,interface='eth0',boot=BOOT):
return target.Snapshot(boot,interface,rx,tx,int(seconds*1_000_000_000),'2026-11-06T06:00:00+00:00')
class TrackerTests(unittest.TestCase):
def test_first_counter_is_baseline_not_zero_speed(self):
row=target.CounterTracker().observe(snap()).sample
self.assertEqual(row['quality'],'baseline')
self.assertIsNone(row['rx_bytes_per_second']);self.assertIsNone(row['tx_bytes_per_second'])
self.assertEqual(row['interval_seconds'],0)
def test_real_elapsed_monotonic_rates_not_wall_clock(self):
tracker=target.CounterTracker();tracker.observe(snap())
current=snap(1600,800,2.2)
current=target.Snapshot(current.boot_id,current.interface,current.rx_bytes,current.tx_bytes,current.monotonic_ns,'2020-01-01T00:00:00+00:00')
row=tracker.observe(current).sample
self.assertEqual(row['quality'],'ok');self.assertAlmostEqual(row['interval_seconds'],1.2)
self.assertAlmostEqual(row['rx_bytes_per_second'],500);self.assertAlmostEqual(row['tx_bytes_per_second'],250)
def test_zero_actual_delta_is_valid_zero(self):
tracker=target.CounterTracker();tracker.observe(snap())
row=tracker.observe(snap(seconds=2)).sample
self.assertEqual(row['quality'],'ok');self.assertEqual(row['rx_bytes_per_second'],0)
def test_either_counter_decrease_starts_new_epoch_without_negative_rates(self):
for rx,tx in ((20,600),(1100,20)):
tracker=target.CounterTracker();old=tracker.observe(snap())
new=tracker.observe(snap(rx,tx,2))
self.assertEqual(new.sample['quality'],'reset');self.assertNotEqual(old.sample['counter_epoch'],new.sample['counter_epoch'])
self.assertIsNone(new.sample['rx_bytes_per_second']);self.assertIsNone(new.sample['tx_bytes_per_second'])
def test_boot_and_interface_changes_are_gaps_with_new_epochs(self):
for current,quality in ((snap(1500,700,2,boot=OTHER_BOOT),'boot_changed'),(snap(1500,700,2,interface='ens3'),'interface_changed')):
tracker=target.CounterTracker();old=tracker.observe(snap());new=tracker.observe(current)
self.assertEqual(new.sample['quality'],quality);self.assertTrue(new.sample['gap_before'])
self.assertNotEqual(old.sample['counter_epoch'],new.sample['counter_epoch'])
self.assertIsNone(new.sample['rx_bytes_per_second'])
def test_long_or_nonpositive_intervals_do_not_make_fake_rates(self):
for seconds in (1,0.5,1.1,5):
tracker=target.CounterTracker();tracker.observe(snap());row=tracker.observe(snap(1500,800,seconds)).sample
self.assertEqual(row['quality'],'gap');self.assertTrue(row['gap_before']);self.assertIsNone(row['rx_bytes_per_second'])
def test_restart_uuid_separates_sequence_one(self):
a=target.CounterTracker().observe(snap()).sample;b=target.CounterTracker().observe(snap()).sample
self.assertEqual(a['sequence'],1);self.assertEqual(b['sequence'],1);self.assertNotEqual(a['counter_epoch'],b['counter_epoch'])
def test_failed_capture_advances_sequence_and_marks_next_sample(self):
tracker=target.CounterTracker();tracker.observe(snap());tracker.note_missing(2)
row=tracker.observe(snap(1500,800,4)).sample
self.assertEqual(row['sequence'],4);self.assertTrue(row['gap_before'])
def test_int63_limit_and_invalid_counter_rejected(self):
for value in (-1,2**63,True,1.2):
with self.subTest(value=value),self.assertRaises(ValueError):target.CounterTracker().observe(snap(rx=value))
class QueueTests(unittest.TestCase):
def test_queue_bounds_and_explicit_old_sample_gap(self):
queue=target.BoundedSampleQueue(3);tracker=target.CounterTracker()
for i in range(1,7):queue.put(tracker.observe(snap(1000+i,500+i,i)))
rows=queue.batch()
self.assertEqual(len(rows),3);self.assertEqual([x.sample['sequence'] for x in rows],[4,5,6])
self.assertTrue(all(x.sample['gap_before'] for x in rows))
self.assertEqual(sum(x.sample['dropped_samples_before'] for x in rows),3)
def test_inflight_retry_record_is_immutable_when_queue_drops_older_samples(self):
queue=target.BoundedSampleQueue(3);tracker=target.CounterTracker()
for i in range(1,4):queue.put(tracker.observe(snap(1000+i,500+i,i)))
inflight=queue.batch();original=copy.deepcopy(inflight[1].sample)
queue.put(tracker.observe(snap(2000,1000,4)))
self.assertEqual(queue.batch()[0].sample,original)
def test_batch_group_does_not_mislabel_interface_or_boot(self):
queue=target.BoundedSampleQueue();tracker=target.CounterTracker()
queue.put(tracker.observe(snap()));queue.put(tracker.observe(snap(1600,700,2,interface='ens3')))
first=queue.batch();self.assertEqual(len(first),1);self.assertEqual(first[0].interface,'eth0')
queue.acknowledge(first);self.assertEqual(queue.batch()[0].interface,'ens3')
def test_ack_does_not_remove_later_or_dropped_unacknowledged_rows(self):
queue=target.BoundedSampleQueue(2);tracker=target.CounterTracker()
queue.put(tracker.observe(snap()));sent=queue.batch()
queue.put(tracker.observe(snap(1500,700,2)));queue.put(tracker.observe(snap(1700,900,3)))
queue.acknowledge(sent)
self.assertEqual([x.sample['sequence'] for x in queue.batch()],[2,3])
def test_upload_failure_keeps_queue_and_sampling_independent(self):
entered=threading.Event();release=threading.Event();stop=threading.Event()
class SlowTransport:
def send(self,*args):entered.set();release.wait(2);raise TimeoutError('offline failure')
queue=target.BoundedSampleQueue();tracker=target.CounterTracker();queue.put(tracker.observe(snap()))
worker=target.Uploader(queue,target.Credentials('node-example','secret-not-logged'),SlowTransport(),stop,interval=.01,log=lambda text:None)
worker.start();self.assertTrue(entered.wait(1))
started=time.monotonic()
for i in range(2,70):queue.put(tracker.observe(snap(i*2000,i*500,i)))
self.assertLess(time.monotonic()-started,.5);self.assertEqual(len(queue.batch()),60)
stop.set();release.set();worker.join(2);self.assertFalse(worker.is_alive());self.assertEqual(len(queue.batch()),60)
def test_transport_success_acknowledges_only_transmitted_prefix(self):
queue=target.BoundedSampleQueue();tracker=target.CounterTracker();queue.put(tracker.observe(snap()))
class Success:
def send(self,payload,credentials):
queue.put(tracker.observe(snap(1200,600,2)))
worker=target.Uploader(queue,target.Credentials('node-example','secret-not-logged'),Success(),threading.Event(),log=lambda text:None)
self.assertTrue(worker.upload_once());self.assertEqual([x.sample['sequence'] for x in queue.batch()],[2])
class ReaderAndContractTests(unittest.TestCase):
def setUp(self):
self.temp=tempfile.TemporaryDirectory();self.addCleanup(self.temp.cleanup);self.root=Path(self.temp.name)
self.proc=self.root/'proc';self.sys=self.root/'sys';(self.proc/'net').mkdir(parents=True)
(self.proc/'sys/kernel/random').mkdir(parents=True);(self.proc/'sys/kernel/random/boot_id').write_text(BOOT)
(self.proc/'net/route').write_text('Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT\ntailscale0 00000000 0100007F 0003 0 0 0 00000000 0 0 0\ndocker0 00000000 0100007F 0003 0 0 1 00000000 0 0 0\nens3 00000000 0100007F 0003 0 0 10 00000000 0 0 0\neth0 00000000 0100007F 0003 0 0 20 00000000 0 0 0\n')
(self.proc/'net/dev').write_text('Inter-| Receive | Transmit\n face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n eth0: 1000 1 0 0 0 0 0 0 500 1 0 0 0 0 0 0\n ens3: 2000 1 0 0 0 0 0 0 800 1 0 0 0 0 0 0\n tailscale0: 999999 1 0 0 0 0 0 0 888888 1 0 0 0 0 0 0\n')
for name in ('eth0','ens3'):
path=self.sys/'class/net'/name;(path/'device').mkdir(parents=True);(path/'type').write_text('1')
def test_default_wan_uses_lowest_metric_physical_interface_only(self):
reader=target.ProcWanReader(self.proc,self.sys);row=reader.read()
self.assertEqual(row.interface,'ens3');self.assertEqual(row.rx_bytes,2000);self.assertEqual(row.tx_bytes,800)
def test_no_default_physical_wan_raises_instead_of_zero_or_tailscale(self):
(self.proc/'net/route').write_text('Iface Destination Gateway Flags RefCnt Use Metric Mask\ntailscale0 00000000 0100007F 0003 0 0 0 00000000\n')
with self.assertRaises(OSError):target.ProcWanReader(self.proc,self.sys).read()
def test_credentials_ignore_other_node_env_secrets_and_never_repr_token(self):
path=self.root/'node.env';path.write_text('NODE_SLUG=node-example\nNODE_TOKEN="test-secret"\nREALITY_PRIVATE_KEY=do-not-use\nXRAY_PORT=11084\n')
credentials=target.load_credentials(path)
self.assertEqual(credentials.node_slug,'node-example');self.assertEqual(credentials.token,'test-secret')
self.assertNotIn('test-secret',repr(credentials));self.assertFalse(hasattr(credentials,'private_key'))
def test_header_injection_or_missing_credentials_refused(self):
for content in ('NODE_SLUG=node-example\n','NODE_SLUG=evil user\nNODE_TOKEN=secret\n','NODE_SLUG=node-example\nNODE_TOKEN="bad token"\n'):
path=self.root/'node.env';path.write_text(content)
with self.assertRaises(ValueError):target.load_credentials(path)
def test_contract_is_real_host_rx_tx_with_nullable_baseline(self):
tracker=target.CounterTracker();batch=[tracker.observe(snap()),tracker.observe(snap(1600,800,2))]
payload=target.build_payload(batch,'node-example')
self.assertEqual(payload['contract'],1);self.assertEqual(payload['kind'],'server_host_interface')
self.assertEqual(payload['counter_semantics'],'linux_proc_net_dev_interface_bytes');self.assertEqual(payload['interface'],'eth0')
self.assertIsNone(payload['samples'][0]['rx_bytes_per_second']);self.assertEqual(payload['samples'][1]['rx_bytes_per_second'],600)
self.assertLess(len(json.dumps(payload).encode()),65536)
def test_untrusted_or_redirectable_endpoints_refused(self):
for endpoint in ('http://vpn.example.invalid/api/v1/node/host-traffic/','https://evil.invalid/api/v1/node/host-traffic/','https://vpn.example.invalid@evil.invalid/api/v1/node/host-traffic/','https://vpn.example.invalid/api/v1/node/host-traffic/?q=secret'):
with self.assertRaises(ValueError):target.HttpTransport(endpoint)
def test_tls_default_verification_and_redirect_disabled(self):
transport=target.HttpTransport()
self.assertTrue(transport.ssl_context.check_hostname)
self.assertEqual(transport.ssl_context.verify_mode,2)
with self.assertRaises(Exception):target.NoRedirect().redirect_request(None,None,302,'found',{},'https://evil.invalid/')
class SamplingCadenceTests(unittest.TestCase):
def check_cadence(self,read_cost):
captured=[]
class Clock:
now=1.0
clock=Clock()
class Stop:
def is_set(self):return len(captured)>=4
def wait(self,delay):clock.now+=delay;return False
class Reader:
def read(self):
captured.append(clock.now)
value=snap(rx=int(clock.now)*1000,tx=int(clock.now)*500,seconds=clock.now)
clock.now+=read_cost
return value
queue=target.BoundedSampleQueue()
with patch.object(target.time,'monotonic',side_effect=lambda:clock.now):
target.run_sampler(Reader(),queue,target.CounterTracker(),Stop(),log=lambda _:None)
return captured,queue.batch()
def test_sample_deadlines_are_monotonic_one_second(self):
captured,rows=self.check_cadence(0)
self.assertEqual(captured,[1,2,3,4]);self.assertEqual([x.sample['sequence'] for x in rows],[1,2,3,4])
self.assertTrue(all(x.sample['interval_seconds']==1 for x in rows[1:]))
def test_delayed_read_marks_missing_intervals_instead_of_fake_catchup(self):
captured,rows=self.check_cadence(2.2)
self.assertEqual(captured,[1,4,7,10]);self.assertEqual([x.sample['sequence'] for x in rows],[1,4,7,10])
self.assertTrue(all(x.sample['gap_before'] for x in rows[1:]))
class PackageSafetyTests(unittest.TestCase):
def test_sampler_uses_no_external_process_or_persistent_writes(self):
import ast
tree=ast.parse((HERE/'host_traffic_sampler.py').read_text())
imports={node.names[0].name for node in ast.walk(tree) if isinstance(node,ast.Import)}
self.assertNotIn('subprocess',imports)
for node in ast.walk(tree):
if isinstance(node,ast.Call) and isinstance(node.func,ast.Attribute):
self.assertNotIn(node.func.attr,{'write_text','write_bytes','unlink','mkdir','rmdir','chmod','chown','system','popen'})
def test_service_does_not_depend_on_or_restart_existing_agent(self):
unit=(HERE/'toplc-vpn-host-traffic.service').read_text()
self.assertIn('--node-env /opt/toplc-vpn-node/node.env',unit)
self.assertIn('ProtectSystem=strict',unit);self.assertIn('CapabilityBoundingSet=\n',unit)
self.assertNotIn('EnvironmentFile=',unit);self.assertNotIn('Requires=docker',unit)
self.assertNotIn('ExecStartPre=',unit);self.assertNotIn('ExecStopPost=',unit)
def test_installer_only_starts_own_service_and_refuses_existing_install(self):
text=(HERE/'deploy_host_traffic_sampler.sh').read_text()
self.assertIn("assert not path.exists() and not path.is_symlink()",text)
self.assertIn("credentials.node_slug==expected",text)
self.assertIn("assert before==after",text)
self.assertIn("['systemctl','enable','--now','toplc-vpn-host-traffic.service']",text)
self.assertNotIn("['systemctl','restart'",text)
for command in ('iptables','nft ','tailscale up','docker restart','docker compose up'):
self.assertNotIn(command,text)
def test_example_payload_matches_sampler_schema_and_does_not_contain_credentials(self):
payload=json.loads((HERE/'host-traffic-contract-fixture.json').read_text())
self.assertEqual(payload['contract'],1)
self.assertEqual(set(payload),{'contract','node_slug','boot_id','interface','kind','counter_semantics','samples'})
self.assertEqual(set(payload['samples'][0]),{'sequence','observed_at','monotonic_ns','counter_epoch','interval_seconds','rx_bytes','tx_bytes','rx_bytes_per_second','tx_bytes_per_second','quality','gap_before','dropped_samples_before'})
self.assertFalse(any(word in json.dumps(payload).lower() for word in ('token','password','private_key')))
if __name__=='__main__':unittest.main()
@@ -0,0 +1,38 @@
[Unit]
Description=TopLC VPN physical WAN one-second traffic sampler
Documentation=file:/opt/toplc-vpn-host-traffic/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/toplc-vpn-host-traffic
ExecStart=/usr/bin/python3 -B /opt/toplc-vpn-host-traffic/host_traffic_sampler.py --node-env /opt/toplc-vpn-node/node.env
Restart=on-failure
RestartSec=10
TimeoutStopSec=12
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=true
CapabilityBoundingSet=
AmbientCapabilities=
SystemCallArchitectures=native
UMask=0077
MemoryMax=64M
TasksMax=8
CPUQuota=10%
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target