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
@@ -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.
@@ -0,0 +1,49 @@
# 独立服务器 WAN 秒级采样接线
此目录仅增加真实主网卡监控入口和独立 SQLite 时序存储。与主代理、账号限速、节点调度、订阅配置、Django 业务数据库及候选功能完全分离。需由主任务审查后部署,本目录没有自动远端部署动作。
输入为 `host-traffic-sampler` 独立服务每秒读取的 Linux 主 WAN 网卡 RX/TX 原始计数;每 5 秒批量上传。服务器出站为 TX,入站为 RX。界面中的 `upload` 因沿用网卡视角等于 TX/出站,`download` 等于 RX/入站。此数据包含整个主机的网卡开销,不是某个账户的代理计费。
## 两个入口
- `POST /api/v1/node/host-traffic/`:已有节点 Bearer token、`X-Node-Slug`、active+subscription_enabled 节点才可上报。最多 64 KiB、60 点。协议字段与相邻 `host-traffic-sampler/host-traffic-contract-fixture.json` 一致。整批提交后返回 `{status:"accepted",accepted:N,duplicates:M}`;相同 epoch+sequence 的不同内容使整批回滚。Node token 摘要只读验证,不回传令牌、不修改心跳、下发或计费。
- `GET /api/v1/client/node-traffic/`:原 ClientSession Bearer token、有效设备和订阅、正常且启用的 staff 账号才可查看。沿用正式模型的到期、配额、付款和账号有效性判断,但不调用会写 last_seen/订阅状态的旧鉴权助手。401/403/200 均 no-store。没有登录或 profile 授权字段改动。
GET 保留 host contract 1:scope=`server_host_interface`,source=`linux_host_interface`,direction=`interface_perspective`,counter_since=`boot_or_interface_reset`。`refresh_seconds=5`,`sample_period_seconds=1`,`freshness_seconds=15`;节点动态取 active+subscription_enabled,不硬编码 VPN002/003/004。当前值超过 15 秒、缺数据或基线/复位/缺口时为 null,不能以零伪装在线。
独立库每节点保留最近一小时、最多 3600 个真实秒级点。首载只返回最近 5 分钟,每节点最多 300 点,并在全节点之间公平分配最多 2000 点的响应预算;JSON 硬上限 1 MiB。这样当前 3/4 节点首载约数百 KiB,在限速账户上也无需下载整个一小时。`available_storage_history_seconds=3600` 表明存储范围;`requested_history_seconds` 表示请求下限;`history_seconds` 是本次真实返回点的实际跨度,不假称首载一小时。`history_truncated`、`history_point_limit_per_node` 和每节点 `returned_history_since` 明示截断和范围。
每个返回点有真实 `sampled_at`、`interval_seconds`、`sequence`、`counter_epoch`、`interface`、`quality` 和 `gap_before`。TX 对应 `upload_bytes_per_second`,RX 对应 `download_bytes_per_second`。非 ok 点双向速率为 null;接口切换、启动、计数复位、漏样或时间缺口必须断开曲线。若新 epoch 的首次基线因离线队列丢弃,服务端把恢复后的首个观测仅作为 gap/null 基线,下一条才校验差分,避免永久重试失败。
可选 `?since=<带时区ISO8601>` 增量读取。过旧下限钳到最近一小时,未来超过 5 秒拒绝。过滤同时包含“观测时间或接收时间大于下限”的点,防止上一响应游标跳过延迟批次;客户端按 epoch+sequence 或 epoch+sampled_at 去重。当前值不受 since 过滤。首载五分钟,随后每 5 秒增量;客户端可以积累最多一小时的本次运行真实历史,但没有后台分页补齐一小时或下采样功能,不能伪造更早曲线。
## 持久性与部署边界
`control/urls.py` 必须从当前生产 `control/urls.py` 基线生成;只增加 host_traffic import 和两个 path,不能复制工作区候选 URLs。`candidate-manifest.json` 记录正式基线和候选 SHA。
示例 overlay 固定挂载本目录中两个新模块与最小 patched URLs,并独立挂载 `/opt/toplc-vpn/host-traffic-state`。需将 overlay 放在当前三个 Compose 文件之后,保持已有镜像、入口、端口和 `/app/releases` 挂载。只重建 web;不触碰 scheduler、vpn-ai、db、NPM 或 VPN 节点网络。`VPN_RUN_STARTUP_TASKS=false` 必须存在,避免 entrypoint 自动 migrate、collectstatic--clear、bootstrap_vpn。
部署前先在专用状态目录显式初始化独立数据库(不通过 GET 隐式创建):
```sh
python3 control/host_traffic_store.py --init --path /opt/toplc-vpn/host-traffic-state/host-traffic.sqlite3
```
为实际容器运行 UID 设置专用目录访问权限;数据库文件 0600。SQLite 使用 WAL、2 秒 busy_timeout;POST 每批一个事务,按节点+epoch+sequence 去重,最多 32 节点,各保留最近 3600 点且清除一小时前数据。GET 只以 `mode=ro`、`query_only=ON` 打开已初始化文件,并在一个只读事务中生成一致快照。没有 Django DB schema 或 migration。
部署和重建验证由主任务执行:确认 health200、无令牌401、无权限403、三节点新数据真实每秒、只出现专用 SQLite 写入、重建后 bind 持久、主网卡方向和既有节点/路由/限速配置摘要一致。回退仅移除本新增 overlay 并按原三个 Compose 文件重建 web;不删除业务数据或改变节点服务。
## 隔离验证
`tests/run_tests.py` 使用只读取得的正式 accounts/control 模型源码快照、实际 Django 5.2.17 和完整生产 middleware 链,在本地 SQLite 运行。两种 API 请求期间捕获的 Django SQL 必须全部为 SELECT;另检查独立数据库幂等、冲突整批回滚、counter reset、单调时钟、速率差分、上限、迟到批次、真实方向及 sampler fixture 端到端兼容。所有账号和令牌均为本地生成的虚构测试数据。
可复现命令(工作目录为项目根):
```powershell
& 'output/proxy-aggregate-api-20261106/test-venv/Scripts/python.exe' 'services/toplc-vpn-platform/host-traffic-standalone-20261106/tests/run_tests.py'
```
正式源码基线只在 `output/proxy-aggregate-api-20261106/baseline` 中做隔离测试输入,不能把其 models/views 当作待部署文件。公开导出此目录时不要导出本地运行环境、SQLite 数据或真实 token。
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,91 @@
"""Isolated endpoints for true one-second host WAN telemetry, never billing."""
import hashlib
import secrets
import sqlite3
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.vary import vary_on_headers
from .models import ClientSession, Node
from . import host_traffic_store as store
def _token(request):
authorization = request.headers.get("Authorization", "")
if not authorization.startswith("Bearer "):
return None
token = authorization[7:].strip()
return token if 32 <= len(token) <= 256 else None
def _client_allowed(request):
token = _token(request)
if token is None:
return JsonResponse({"error": "Client access token required."}, status=401)
digest = hashlib.sha256(token.encode()).hexdigest()
session = ClientSession.objects.select_related("device", "subscription__user", "subscription__plan").filter(token_digest=digest, revoked_at__isnull=True).first()
if session is None or not secrets.compare_digest(session.token_digest, digest) or not session.is_valid:
return JsonResponse({"error": "Client login expired."}, status=401)
if not session.device.active or session.device.subscription_id != session.subscription_id:
return JsonResponse({"error": "Client device unavailable."}, status=403)
user = session.subscription.user
if not user.service_enabled or not user.is_staff or not session.subscription.is_usable:
return JsonResponse({"error": "Server traffic monitoring is not permitted."}, status=403)
return None
@never_cache
@vary_on_headers("Authorization")
@require_GET
def client_node_traffic(request):
# Existing model properties enforce the same token/account/expiry/quota policy
# as the production login helper, without its writes to last_seen/status.
denial = _client_allowed(request)
if denial is not None:
return denial
try:
since = store.timestamp(request.GET["since"]) if "since" in request.GET else None
nodes = list(Node.objects.filter(active=True, subscription_enabled=True).order_by("sort_order", "region", "name", "pk").values("id", "slug", "name", "region"))
if len(nodes) > store.MAX_NODES:
return JsonResponse({"error": "Host traffic node capacity exceeded."}, status=503)
result = store.snapshot(nodes, timezone.now(), since)
except store.InvalidSample:
return JsonResponse({"error": "Invalid history range."}, status=400)
except sqlite3.Error:
return JsonResponse({"error": "Host traffic telemetry temporarily unavailable."}, status=503)
response = JsonResponse(result, json_dumps_params={"separators": (",", ":"), "ensure_ascii": False})
if len(response.content) > store.MAX_RESPONSE_BYTES:
return JsonResponse({"error": "Host traffic response capacity exceeded."}, status=503)
return response
@csrf_exempt
@never_cache
@require_POST
def node_host_traffic(request):
token = _token(request)
slug = request.headers.get("X-Node-Slug", "")
if token is None or not 1 <= len(slug) <= 80:
return JsonResponse({"error": "Node authentication failed."}, status=401)
node = Node.objects.filter(slug=slug, active=True, subscription_enabled=True).first()
if node is None or not node.check_agent_token(token):
return JsonResponse({"error": "Node authentication failed."}, status=401)
try:
# Bound reads before deserializing JSON. Real nginx/Django limits remain
# in force; this endpoint additionally permits only one small batch.
declared = request.META.get("CONTENT_LENGTH", "")
if declared and (not declared.isdigit() or int(declared) > store.MAX_BODY_BYTES):
raise store.InvalidSample("batch too large")
body = request.read(store.MAX_BODY_BYTES + 1)
now = timezone.now()
points = store.parse_batch(body, node.slug, now)
result = store.ingest(node.pk, points, now)
except (store.InvalidSample, UnicodeError, OverflowError, TypeError):
return JsonResponse({"error": "Invalid host traffic sample batch."}, status=400)
except sqlite3.Error:
return JsonResponse({"error": "Host traffic telemetry temporarily unavailable."}, status=503)
return JsonResponse(result)
@@ -0,0 +1,330 @@
"""Bounded standalone WAN sample store. Does not use or write Django models."""
from __future__ import annotations
import hashlib
import json
import math
import os
import re
import sqlite3
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
MAX_BODY_BYTES = 65536
MAX_BATCH = 60
MAX_NODES = 32
MAX_POINTS = 3600
HISTORY_SECONDS = 3600
DEFAULT_HISTORY_SECONDS = 300
MAX_RESPONSE_POINTS = 2000
MAX_RESPONSE_BYTES = 1024 * 1024
FRESHNESS_SECONDS = 15
MAX_INT = 2**63 - 1
MAX_SEQUENCE = 2**53 - 1
MAX_RATE = 10**12
INTERFACE = re.compile(r"[A-Za-z0-9_.-]{1,15}\Z")
EXCLUDED = re.compile(r"(?:lo\Z|tailscale|tun|tap|utun|wg|docker|veth|virbr|br[.-])", re.I)
QUALITIES = {"baseline", "ok", "reset", "gap", "interface_changed", "boot_changed"}
SCHEMA = """
CREATE TABLE IF NOT EXISTS samples (
id INTEGER PRIMARY KEY,
node_id INTEGER NOT NULL,
counter_epoch TEXT NOT NULL,
sequence INTEGER NOT NULL,
boot_id TEXT NOT NULL,
interface TEXT NOT NULL,
observed_us INTEGER NOT NULL,
monotonic_ns INTEGER NOT NULL,
interval_seconds REAL NOT NULL,
rx_bytes INTEGER NOT NULL,
tx_bytes INTEGER NOT NULL,
rx_rate INTEGER,
tx_rate INTEGER,
quality TEXT NOT NULL,
gap_before INTEGER NOT NULL,
dropped_samples_before INTEGER NOT NULL,
payload_sha256 TEXT NOT NULL,
received_us INTEGER NOT NULL,
UNIQUE(node_id,counter_epoch,sequence)
);
CREATE INDEX IF NOT EXISTS samples_node_time ON samples(node_id,observed_us,id);
CREATE INDEX IF NOT EXISTS samples_time ON samples(observed_us);
PRAGMA user_version=1;
"""
class InvalidSample(ValueError):
pass
def store_path():
return Path(os.environ.get("TOPLC_HOST_TRAFFIC_DB", "/var/lib/toplc-vpn-host-traffic/host-traffic.sqlite3"))
def _require(value, message):
if not value:
raise InvalidSample(message)
def _integer(value, maximum=MAX_INT):
_require(type(value) is int and 0 <= value <= maximum, "invalid integer")
return value
def _finite(value, minimum, maximum):
_require(type(value) in (int, float) and math.isfinite(value) and minimum <= value <= maximum, "invalid numeric value")
return float(value)
def _uuid(value):
_require(isinstance(value, str) and len(value) <= 36, "invalid counter identity")
try:
return str(uuid.UUID(value))
except (ValueError, AttributeError) as exc:
raise InvalidSample("invalid counter identity") from exc
def timestamp(value):
_require(isinstance(value, str) and len(value) <= 40, "invalid observation timestamp")
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError as exc:
raise InvalidSample("invalid observation timestamp") from exc
_require(parsed.tzinfo is not None, "observation timestamp requires timezone")
return parsed.astimezone(timezone.utc)
def microseconds(value):
return int(value.timestamp() * 1_000_000)
def iso_from_us(value):
return datetime.fromtimestamp(value / 1_000_000, timezone.utc).isoformat()
def parse_batch(body, expected_slug, now):
_require(len(body) <= MAX_BODY_BYTES, "batch too large")
try:
payload = json.loads(body)
except (ValueError, UnicodeDecodeError) as exc:
raise InvalidSample("invalid JSON") from exc
required = {"contract", "node_slug", "boot_id", "interface", "kind", "counter_semantics", "samples"}
_require(isinstance(payload, dict) and set(payload) == required, "unexpected batch fields")
_require(type(payload["contract"]) is int and payload["contract"] == 1, "invalid contract")
_require(payload["node_slug"] == expected_slug, "node identity mismatch")
_require(payload["kind"] == "server_host_interface" and payload["counter_semantics"] == "linux_proc_net_dev_interface_bytes", "invalid counter semantics")
interface = payload["interface"]
_require(isinstance(interface, str) and INTERFACE.fullmatch(interface) and not EXCLUDED.match(interface), "invalid WAN interface")
boot = _uuid(payload["boot_id"])
samples = payload["samples"]
_require(isinstance(samples, list) and 1 <= len(samples) <= MAX_BATCH, "invalid batch count")
points = []
fields = {"sequence", "observed_at", "monotonic_ns", "counter_epoch", "interval_seconds", "rx_bytes", "tx_bytes", "rx_bytes_per_second", "tx_bytes_per_second", "quality"}
optional = {"gap_before", "dropped_samples_before"}
for item in samples:
_require(isinstance(item, dict) and fields.issubset(item) and set(item).issubset(fields | optional), "unexpected sample fields")
seq = _integer(item["sequence"], MAX_SEQUENCE)
mono = _integer(item["monotonic_ns"])
_require(mono > 0, "monotonic clock must be positive")
epoch = _uuid(item["counter_epoch"])
observed = timestamp(item["observed_at"])
_require(now - timedelta(seconds=HISTORY_SECONDS) <= observed <= now + timedelta(seconds=5), "observation timestamp outside window")
quality = item["quality"]
_require(quality in QUALITIES, "invalid sample quality")
interval = _finite(item["interval_seconds"], 0, HISTORY_SECONDS)
rx = _integer(item["rx_bytes"])
tx = _integer(item["tx_bytes"])
rates = [item["rx_bytes_per_second"], item["tx_bytes_per_second"]]
if quality == "ok":
_require(.5 <= interval <= 3, "invalid regular sample interval")
rates = [_finite(value, 0, MAX_RATE) for value in rates]
else:
_require(rates == [None, None], "baseline/reset/gap must not claim rates")
gap = item.get("gap_before", False)
_require(type(gap) is bool, "invalid gap flag")
dropped = _integer(item.get("dropped_samples_before", 0), 1_000_000)
normalized = dict(sequence=seq, observed_at=observed.isoformat(), monotonic_ns=mono,
counter_epoch=epoch, interval_seconds=interval, rx_bytes=rx, tx_bytes=tx,
rx_bytes_per_second=rates[0], tx_bytes_per_second=rates[1], quality=quality,
gap_before=gap, dropped_samples_before=dropped, boot_id=boot, interface=interface)
normalized["payload_sha256"] = hashlib.sha256(json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
normalized["observed_us"] = microseconds(observed)
if points:
_require(seq > points[-1]["sequence"] and observed >= timestamp(points[-1]["observed_at"]), "batch must be ordered")
points.append(normalized)
return points
def initialize(path=None):
path = Path(path) if path is not None else store_path()
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
database = sqlite3.connect(path, timeout=2)
try:
database.execute("PRAGMA journal_mode=WAL")
database.execute("PRAGMA busy_timeout=2000")
database.execute("PRAGMA journal_size_limit=8388608")
database.execute("PRAGMA wal_autocheckpoint=256")
database.executescript(SCHEMA)
finally:
database.close()
try:
path.chmod(0o600)
except OSError:
pass
def _connect(path, readonly=False):
path = Path(path)
if not path.is_file():
raise sqlite3.OperationalError("sample store is not initialized")
# mode=ro never creates a database; initialization is an explicit deploy step.
mode = "ro" if readonly else "rw"
connection = sqlite3.connect(path.resolve().as_uri() + "?mode=" + mode, uri=True, timeout=2)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA busy_timeout=2000")
if readonly:
connection.execute("PRAGMA query_only=ON")
else:
connection.execute("PRAGMA wal_autocheckpoint=256")
connection.execute("PRAGMA journal_size_limit=8388608")
return connection
def _derived(point, previous):
quality = point["quality"]
gap = bool(point["gap_before"] or point["dropped_samples_before"])
rx_rate = tx_rate = None
if previous is None:
return None, None, quality if quality != "ok" else "gap", True
same_epoch = point["counter_epoch"] == previous["counter_epoch"]
if same_epoch:
_require(point["boot_id"] == previous["boot_id"] and point["interface"] == previous["interface"], "identity change requires new epoch")
_require(point["sequence"] > previous["sequence"] and point["monotonic_ns"] > previous["monotonic_ns"], "sequence/clock must advance")
_require(point["rx_bytes"] >= previous["rx_bytes"] and point["tx_bytes"] >= previous["tx_bytes"], "counter reset requires new epoch")
skipped = point["sequence"] != previous["sequence"] + 1
gap = gap or skipped
if quality == "ok" and not gap:
elapsed = (point["monotonic_ns"] - previous["monotonic_ns"]) / 1_000_000_000
_require(abs(elapsed - point["interval_seconds"]) <= max(.01, elapsed * .005), "interval and monotonic clock differ")
computed = [(point["rx_bytes"] - previous["rx_bytes"]) / elapsed,
(point["tx_bytes"] - previous["tx_bytes"]) / elapsed]
for actual, claimed in zip(computed, [point["rx_bytes_per_second"], point["tx_bytes_per_second"]]):
_require(math.isfinite(actual) and 0 <= actual <= MAX_RATE and abs(actual - claimed) <= max(2, actual * .005), "rate and counter delta differ")
rx_rate, tx_rate = [round(value) for value in computed]
elif quality == "ok":
quality = "gap"
else:
# A sampler's bounded queue may have dropped a new epoch's baseline
# while disconnected. Its first surviving observation is useful only
# as a new baseline; never trust a rate that cannot be checked here.
if quality == "ok":
quality = "gap"
gap = True
return rx_rate, tx_rate, quality, gap
def ingest(node_id, points, now, path=None):
database = _connect(path if path is not None else store_path())
accepted = duplicates = 0
try:
database.execute("BEGIN IMMEDIATE")
cutoff = microseconds(now - timedelta(seconds=HISTORY_SECONDS))
database.execute("DELETE FROM samples WHERE observed_us < ?", (cutoff,))
known = database.execute("SELECT 1 FROM samples WHERE node_id=? LIMIT 1", (node_id,)).fetchone()
count = database.execute("SELECT COUNT(DISTINCT node_id) FROM samples").fetchone()[0]
_require(known is not None or count < MAX_NODES, "sample store node limit reached")
for point in points:
old = database.execute("SELECT payload_sha256 FROM samples WHERE node_id=? AND counter_epoch=? AND sequence=?", (node_id, point["counter_epoch"], point["sequence"])).fetchone()
if old is not None:
_require(old["payload_sha256"] == point["payload_sha256"], "conflicting repeated sample")
duplicates += 1
continue
previous = database.execute("SELECT * FROM samples WHERE node_id=? ORDER BY observed_us DESC,id DESC LIMIT 1", (node_id,)).fetchone()
if previous is not None:
_require(point["observed_us"] >= previous["observed_us"], "late unordered sample")
rx_rate, tx_rate, quality, gap = _derived(point, previous)
database.execute("""INSERT INTO samples (node_id,counter_epoch,sequence,boot_id,interface,observed_us,monotonic_ns,interval_seconds,rx_bytes,tx_bytes,rx_rate,tx_rate,quality,gap_before,dropped_samples_before,payload_sha256,received_us) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(node_id, point["counter_epoch"], point["sequence"], point["boot_id"], point["interface"], point["observed_us"], point["monotonic_ns"], point["interval_seconds"], point["rx_bytes"], point["tx_bytes"], rx_rate, tx_rate, quality, int(gap), point["dropped_samples_before"], point["payload_sha256"], microseconds(now)))
accepted += 1
database.execute("DELETE FROM samples WHERE node_id=? AND id NOT IN (SELECT id FROM samples WHERE node_id=? ORDER BY observed_us DESC,id DESC LIMIT ?)", (node_id, node_id, MAX_POINTS))
database.commit()
return {"status": "accepted", "accepted": accepted, "duplicates": duplicates}
except BaseException:
database.rollback()
raise
finally:
database.close()
def _history_point(row):
return {"sampled_at": iso_from_us(row["observed_us"]), "interval_seconds": row["interval_seconds"], "sequence": row["sequence"],
"upload_bytes_per_second": row["tx_rate"], "download_bytes_per_second": row["rx_rate"],
"counter_epoch": row["counter_epoch"], "interface": row["interface"],
"quality": row["quality"], "gap_before": bool(row["gap_before"]),
"dropped_samples_before": row["dropped_samples_before"]}
def snapshot(nodes, now, since=None, path=None):
_require(len(nodes) <= MAX_NODES, "node response limit reached")
cutoff = now - timedelta(seconds=HISTORY_SECONDS)
incremental = since is not None
since = max(cutoff, since) if incremental else now - timedelta(seconds=DEFAULT_HISTORY_SECONDS)
_require(since <= now + timedelta(seconds=5), "history lower bound is in the future")
point_limit = min(DEFAULT_HISTORY_SECONDS, MAX_RESPONSE_POINTS // max(1, len(nodes)))
database = _connect(path if path is not None else store_path(), readonly=True)
try:
database.execute("BEGIN")
output = []
for node in nodes:
node_id = node["id"]
latest = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? ORDER BY observed_us DESC,id DESC LIMIT 1", (node_id, microseconds(cutoff), microseconds(now))).fetchone()
# Include newly received backfill even when its observed time predates
# the previous response's generated_at cursor. Polling never loses
# true one-second points from a late five-second batch.
if incremental:
rows = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? AND (observed_us>=? OR received_us>=?) ORDER BY observed_us DESC,id DESC LIMIT ?", (node_id, microseconds(cutoff), microseconds(now), microseconds(since), microseconds(since), point_limit + 1)).fetchall()
else:
rows = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? ORDER BY observed_us DESC,id DESC LIMIT ?", (node_id, microseconds(since), microseconds(now), point_limit + 1)).fetchall()
truncated = len(rows) > point_limit
rows = rows[:point_limit]
rows.reverse()
if not incremental and rows:
truncated = truncated or database.execute("SELECT 1 FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<? LIMIT 1", (node_id, microseconds(cutoff), rows[0]["observed_us"])).fetchone() is not None
stale = latest is None or not 0 <= (microseconds(now) - latest["observed_us"]) / 1_000_000 <= FRESHNESS_SECONDS or not 0 <= (microseconds(now) - latest["received_us"]) / 1_000_000 <= FRESHNESS_SECONDS
valid = not stale and latest["quality"] == "ok" and latest["tx_rate"] is not None and latest["rx_rate"] is not None
output.append({"slug": node["slug"], "name": node["name"], "region": node["region"],
"current_upload_bytes_per_second": latest["tx_rate"] if valid else None,
"current_download_bytes_per_second": latest["rx_rate"] if valid else None,
"total_upload_bytes": latest["tx_bytes"] if latest is not None else None,
"total_download_bytes": latest["rx_bytes"] if latest is not None else None,
"sampled_at": iso_from_us(latest["observed_us"]) if latest is not None else None,
"interval_seconds": latest["interval_seconds"] if latest is not None else None,
"interface": latest["interface"] if latest is not None else None,
"counter_epoch": latest["counter_epoch"] if latest is not None else None,
"stale": bool(stale), "history_truncated": bool(truncated),
"returned_history_since": iso_from_us(rows[0]["observed_us"]) if rows else None,
"history": [_history_point(row) for row in rows]})
oldest = min((timestamp(node["returned_history_since"]) for node in output if node["returned_history_since"]), default=now)
return {"contract": 1, "scope": "server_host_interface", "source": "linux_host_interface",
"direction": "interface_perspective", "counter_since": "boot_or_interface_reset",
"refresh_seconds": 5, "sample_period_seconds": 1, "freshness_seconds": FRESHNESS_SECONDS,
"history_seconds": min(HISTORY_SECONDS, max(0, math.ceil((now-oldest).total_seconds()))),
"available_storage_history_seconds": HISTORY_SECONDS,
"requested_history_seconds": max(0, math.ceil((now-since).total_seconds())),
"history_point_limit_per_node": point_limit,
"history_truncated": any(node["history_truncated"] for node in output),
"history_since": since.isoformat(),
"generated_at": now.isoformat(), "nodes": output}
finally:
database.close()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Initialize only the standalone host traffic SQLite store.")
parser.add_argument("--init", action="store_true", required=True)
parser.add_argument("--path", type=Path)
args = parser.parse_args()
initialize(args.path)
print("Standalone host traffic store initialized; Django database unchanged.")
@@ -0,0 +1,25 @@
from django.urls import path
from . import views, private_auxiliary, host_traffic
urlpatterns = [
path("api/v1/client/node-traffic/", host_traffic.client_node_traffic, name="client-node-traffic"),
path("api/v1/node/host-traffic/", host_traffic.node_host_traffic, name="node-host-traffic"),
path("api/v1/client/private-auxiliary/config/", private_auxiliary.client_config),
path("api/v1/private-auxiliary/verify/", private_auxiliary.verify_device),
path("", views.dashboard, name="portal-dashboard"),
path("register/", views.register, name="register"),
path("apply/", views.apply_plan, name="apply-plan"),
path("sub/<str:token>/config.yaml", views.subscription_config, name="subscription-config"),
path("api/v1/me/", views.api_me, name="api-me"),
path("api/v1/client/login/", views.client_login, name="client-login"),
path("api/v1/client/profile/", views.client_profile, name="client-profile"),
path("api/v1/client/update/", views.client_update, name="client-update"),
path("api/v1/client/config/", views.client_config, name="client-config"),
path("api/v1/client/observations/", views.client_observations, name="client-observations"),
path("api/v1/client/logout/", views.client_logout, name="client-logout"),
path("api/v1/node/sync/", views.node_sync, name="node-sync"),
path("downloads/windows/latest/", views.client_download_latest, name="client-download-latest"),
path("health/", views.health, name="health"),
]
@@ -0,0 +1,24 @@
# Add this overlay AFTER all three existing production compose files.
# Keep the existing web image, command, ports and all existing volume entries.
services:
web:
environment:
VPN_RUN_STARTUP_TASKS: "false"
TOPLC_HOST_TRAFFIC_DB: /var/lib/toplc-vpn-host-traffic/host-traffic.sqlite3
volumes:
- type: bind
source: /opt/toplc-vpn/host-traffic-standalone-20261106/control/host_traffic.py
target: /app/control/host_traffic.py
read_only: true
- type: bind
source: /opt/toplc-vpn/host-traffic-standalone-20261106/control/host_traffic_store.py
target: /app/control/host_traffic_store.py
read_only: true
- type: bind
source: /opt/toplc-vpn/host-traffic-standalone-20261106/control/urls.py
target: /app/control/urls.py
read_only: true
- type: bind
source: /opt/toplc-vpn/host-traffic-state
target: /var/lib/toplc-vpn-host-traffic
read_only: false
@@ -0,0 +1,424 @@
"""Exercise actual candidate modules with production model snapshots in SQLite.
Only local temporary databases are used. No server connection or real token.
Run with output/proxy-aggregate-api-20261106/test-venv/Scripts/python.exe.
"""
from __future__ import annotations
import copy
import hashlib
import json
import os
import shutil
import sqlite3
import sys
import tempfile
import unittest
import uuid
from datetime import datetime, timedelta, timezone as utc
from pathlib import Path
from unittest.mock import patch
CANDIDATE = Path(__file__).resolve().parents[1]
ROOT = CANDIDATE.parents[2]
BASELINE = ROOT / "output/proxy-aggregate-api-20261106/baseline"
OUTPUT = ROOT / "output/host-traffic-standalone-20261106"
OUTPUT.mkdir(parents=True, exist_ok=True)
runtime_context = tempfile.TemporaryDirectory(prefix="django-tests-", dir=OUTPUT)
RUNTIME = Path(runtime_context.name).resolve()
assert RUNTIME.parent == OUTPUT.resolve()
for package in ("accounts", "control"):
(RUNTIME / package).mkdir()
(RUNTIME / package / "__init__.py").write_text("")
shutil.copy2(BASELINE / package / "models.py", RUNTIME / package / "models.py")
shutil.copy2(BASELINE / "accounts/middleware.py", RUNTIME / "accounts/middleware.py")
for module in ("host_traffic.py", "host_traffic_store.py"):
shutil.copy2(CANDIDATE / "control" / module, RUNTIME / "control" / module)
(RUNTIME / "test_urls.py").write_text('from django.urls import path\nfrom control import host_traffic\nurlpatterns=[path("api/v1/client/node-traffic/",host_traffic.client_node_traffic),path("api/v1/node/host-traffic/",host_traffic.node_host_traffic)]\n')
sys.path.insert(0, str(RUNTIME))
from django.conf import settings
settings.configure(SECRET_KEY="local-isolated-fixture-only", USE_TZ=True, TIME_ZONE="UTC",
DEBUG=False, ALLOWED_HOSTS=["testserver"], ROOT_URLCONF="test_urls", STATIC_URL="/static/",
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
AUTH_USER_MODEL="accounts.User", DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions",
"django.contrib.messages", "accounts", "control"],
MIGRATION_MODULES={"accounts": None, "control": None},
MIDDLEWARE=["django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware",
"accounts.middleware.LoginRateLimitMiddleware", "django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware"])
import django
django.setup()
from django.db import connection
from django.test import TestCase, Client
from django.test.runner import DiscoverRunner
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from accounts.models import User, LoginAttempt
from control.models import Plan, Subscription, Device, ClientSession, Node
from control import host_traffic_store as store
NOW = datetime(2026, 11, 6, 8, 0, 0, tzinfo=utc.utc)
BOOT = "11111111-1111-4111-8111-111111111111"
EPOCH = "22222222-2222-4222-8222-222222222222"
def point(sequence=1, *, at=None, rx=None, tx=None, quality=None, epoch=EPOCH):
at = at if at is not None else NOW - timedelta(seconds=10-sequence)
quality = quality or ("baseline" if sequence == 1 else "ok")
return dict(sequence=sequence, observed_at=at.isoformat(), monotonic_ns=sequence*1_000_000_000,
counter_epoch=epoch, interval_seconds=0 if quality != "ok" else 1,
rx_bytes=sequence*1000 if rx is None else rx, tx_bytes=sequence*2000 if tx is None else tx,
rx_bytes_per_second=1000 if quality == "ok" else None,
tx_bytes_per_second=2000 if quality == "ok" else None,
quality=quality, gap_before=False, dropped_samples_before=0)
def batch(samples=None):
return dict(contract=1, node_slug="fixture-node", boot_id=BOOT, interface="eth0",
kind="server_host_interface", counter_semantics="linux_proc_net_dev_interface_bytes",
samples=samples if samples is not None else [point(), point(2)])
class StoreTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="store-", dir=RUNTIME)
self.path = Path(self.temp.name) / "samples.sqlite3"
store.initialize(self.path)
def tearDown(self):
self.temp.cleanup()
def parsed(self, payload):
return store.parse_batch(json.dumps(payload).encode(), "fixture-node", NOW)
def write(self, payload=None, node=1):
return store.ingest(node, self.parsed(payload or batch()), NOW, self.path)
def count(self):
db = sqlite3.connect(self.path)
try:
return db.execute("SELECT COUNT(*) FROM samples").fetchone()[0]
finally:
db.close()
def test_real_rx_tx_direction_and_first_sample_unknown(self):
self.write()
result = store.snapshot([dict(id=1, slug="fixture-node", name="VPN", region="fixture")], NOW, path=self.path)
node = result["nodes"][0]
self.assertEqual(node["current_upload_bytes_per_second"], 2000)
self.assertEqual(node["current_download_bytes_per_second"], 1000)
self.assertIsNone(node["history"][0]["upload_bytes_per_second"])
self.assertEqual(len(node["history"]), 2)
self.assertEqual(node["history"][1]["sampled_at"], point(2)["observed_at"])
self.assertEqual(node["total_upload_bytes"], 4000)
(OUTPUT / "client-node-traffic-fixture.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
def test_duplicates_and_conflicting_duplicate_rollback(self):
self.assertEqual(self.write()["accepted"], 2)
self.assertEqual(self.write(), {"status": "accepted", "accepted": 0, "duplicates": 2})
altered = batch()
altered["samples"][0]["rx_bytes"] += 1
with self.assertRaises(store.InvalidSample):
self.write(altered)
self.assertEqual(self.count(), 2)
def test_partial_batch_is_rolled_back(self):
self.write()
with self.assertRaises(store.InvalidSample):
self.write(batch([point(3), point(4, rx=1)]))
self.assertEqual(self.count(), 2)
def test_reset_requires_new_epoch_and_breaks_history(self):
self.write()
with self.assertRaises(store.InvalidSample):
self.write(batch([point(3, rx=1, tx=1, quality="reset")]))
self.write(batch([point(3, rx=1, tx=1, quality="reset", epoch=str(uuid.uuid4()))]))
result = store.snapshot([dict(id=1, slug="fixture-node", name="VPN", region="fixture")], NOW, path=self.path)["nodes"][0]
self.assertIsNone(result["current_upload_bytes_per_second"])
self.assertTrue(result["history"][-1]["gap_before"])
def test_clock_and_rate_mismatch_rejected(self):
self.write()
for field, value in (("monotonic_ns", 100), ("interval_seconds", 2), ("rx_bytes_per_second", 500000)):
value_point = point(3)
value_point[field] = value
with self.subTest(field=field), self.assertRaises(store.InvalidSample):
self.write(batch([value_point]))
self.assertEqual(self.count(), 2)
def test_body_bounds_and_field_validation(self):
wrong = []
for field, value in (("contract", True), ("node_slug", "other"), ("interface", "tailscale0"),
("interface", "../eth0"), ("boot_id", "bad"), ("samples", []),
("samples", [point()]*61)):
payload = batch()
payload[field] = value
wrong.append(payload)
for field, value in (("rx_bytes", -1), ("tx_bytes", 2**63), ("sequence", True),
("observed_at", (NOW+timedelta(seconds=6)).isoformat()),
("observed_at", (NOW-timedelta(seconds=3601)).isoformat()),
("observed_at", "2026-11-06T08:00:00"), ("rx_bytes_per_second", float("nan")),
("tx_bytes_per_second", float("inf")), ("interval_seconds", .1),
("gap_before", 1), ("dropped_samples_before", -1), ("counter_epoch", "x")):
payload = batch([point(2)])
payload["samples"][0][field] = value
wrong.append(payload)
for index, payload in enumerate(wrong):
with self.subTest(index=index), self.assertRaises((store.InvalidSample, TypeError)):
self.parsed(payload)
with self.assertRaises(store.InvalidSample):
store.parse_batch(b"x"*65537, "fixture-node", NOW)
def test_since_stale_missing_and_no_read_initialization(self):
self.write()
nodes = [dict(id=i, slug=f"node-{i}", name="VPN", region="fixture") for i in [1, 2]]
result = store.snapshot(nodes, NOW+timedelta(seconds=1), NOW+timedelta(seconds=.5), self.path)
self.assertEqual(len(result["nodes"][0]["history"]), 0)
result = store.snapshot(nodes, NOW, NOW-timedelta(seconds=8), self.path)
# Both old observations arrived after the lower-bound cursor.
self.assertEqual(len(result["nodes"][0]["history"]), 2)
self.assertIsNone(result["nodes"][1]["sampled_at"])
stale = store.snapshot(nodes, NOW+timedelta(seconds=20), path=self.path)["nodes"][0]
self.assertTrue(stale["stale"])
self.assertIsNone(stale["current_upload_bytes_per_second"])
with self.assertRaises(sqlite3.Error):
store.snapshot(nodes, NOW, path=self.path.parent / "does-not-exist.sqlite3")
self.assertFalse((self.path.parent / "does-not-exist.sqlite3").exists())
def test_late_batch_incremental_read_uses_receipt_time(self):
nodes = [dict(id=1, slug="n", name="n", region="n")]
self.write(batch([point()]))
before = store.snapshot(nodes, NOW, path=self.path)
later = NOW+timedelta(seconds=5)
delayed = batch([point(2), point(3), point(4), point(5), point(6)])
store.ingest(1, store.parse_batch(json.dumps(delayed).encode(), "fixture-node", later), later, self.path)
after = store.snapshot(nodes, later, datetime.fromisoformat(before["generated_at"]), self.path)
self.assertEqual([p["sequence"] for p in after["nodes"][0]["history"]], [1,2,3,4,5,6])
def test_sequence_gap_does_not_invent_rate(self):
self.write()
self.write(batch([point(4)]))
node = store.snapshot([dict(id=1, slug="n", name="n", region="n")], NOW, path=self.path)["nodes"][0]
self.assertTrue(node["history"][-1]["gap_before"])
self.assertIsNone(node["current_upload_bytes_per_second"])
def test_lost_new_epoch_baseline_can_reconnect(self):
self.write()
epoch = str(uuid.uuid4())
self.write(batch([point(50, at=NOW-timedelta(seconds=2), epoch=epoch)]))
# The first new epoch rate is deliberately unknown, then normal deltas
# are usable again. It must not remain in a permanent HTTP400 loop.
self.write(batch([point(51, at=NOW-timedelta(seconds=1), epoch=epoch)]))
node = store.snapshot([dict(id=1, slug="n", name="n", region="n")], NOW, path=self.path)["nodes"][0]
self.assertEqual(node["history"][-2]["quality"], "gap")
self.assertIsNone(node["history"][-2]["upload_bytes_per_second"])
self.assertEqual(node["history"][-1]["upload_bytes_per_second"], 2000)
def test_first_load_window_response_point_budget(self):
# Seed one second of real data for a full hour, using bounded batches.
for start in range(1, 3601, 60):
points = [point(i, at=NOW-timedelta(seconds=3600-i)) for i in range(start, start+60)]
self.write(batch(points))
nodes = [dict(id=i, slug=f"node-{i}", name="VPN", region="fixture") for i in range(1, 33)]
result = store.snapshot(nodes, NOW, path=self.path)
self.assertEqual(result["available_storage_history_seconds"], 3600)
self.assertEqual(result["requested_history_seconds"], 300)
self.assertEqual(result["history_point_limit_per_node"], 62)
self.assertEqual(len(result["nodes"][0]["history"]), 62)
self.assertTrue(result["history_truncated"])
# Populate every response node with maximal scalar field widths to
# verify the hard byte budget independently of JSON whitespace.
worst_point = copy.deepcopy(result["nodes"][0]["history"][-1])
worst_point.update(sequence=2**53-1, sampled_at="2026-11-06T08:00:00.999999+00:00",
interface="abcdefghijklmn0", interval_seconds=3599.999999,
upload_bytes_per_second=10**12, download_bytes_per_second=10**12,
quality="interface_changed", dropped_samples_before=1000000)
for node in result["nodes"]:
node["history"] = [worst_point] * result["history_point_limit_per_node"]
node["name"] = "界" * 100
node["region"] = "界" * 100
self.assertLess(len(json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode()), store.MAX_RESPONSE_BYTES)
def test_at_most_32_nodes(self):
for node_id in range(1, 33):
self.write(node=node_id)
with self.assertRaises(store.InvalidSample):
self.write(node=33)
def test_actual_sampler_fixture_round_trip(self):
source = CANDIDATE.parent / "host-traffic-sampler/host-traffic-contract-fixture.json"
payload = source.read_bytes()
now = datetime(2026, 11, 6, 6, 0, 6, tzinfo=utc.utc)
points = store.parse_batch(payload, "node-example", now)
self.assertEqual(store.ingest(1, points, now, self.path)["accepted"], 5)
self.assertEqual(store.ingest(1, points, now, self.path)["duplicates"], 5)
result = store.snapshot([dict(id=1, slug="node-example", name="VPN", region="fixture")], now, path=self.path)
self.assertEqual(result["nodes"][0]["current_upload_bytes_per_second"], 40)
self.assertEqual(result["nodes"][0]["current_download_bytes_per_second"], 80)
self.assertEqual([p["quality"] for p in result["nodes"][0]["history"]], ["baseline", "ok", "ok", "reset", "ok"])
(OUTPUT / "sampler-client-roundtrip-fixture.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
def test_point_cap_and_one_hour_retention(self):
for start in range(1, 3602, 60):
points = [point(i, at=NOW-timedelta(seconds=3601-i)) for i in range(start, min(start+60, 3602))]
self.write(batch(points))
self.assertEqual(self.count(), 3600)
later = NOW + timedelta(seconds=3599)
payload = batch([point(3602, at=later, quality="gap")])
store.ingest(1, store.parse_batch(json.dumps(payload).encode(), "fixture-node", later), later, self.path)
self.assertLessEqual(self.count(), 3)
class EndpointTests(TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="api-store-", dir=RUNTIME)
self.path = Path(self.temp.name) / "samples.sqlite3"
store.initialize(self.path)
self.env = patch.dict(os.environ, TOPLC_HOST_TRAFFIC_DB=str(self.path))
self.env.start()
self.clock = patch.object(timezone, "now", return_value=NOW)
self.clock.start()
self.user = User.objects.create(username="fixture-staff", email="fixture@example.invalid", is_staff=True,
is_active=True, account_status="active", identity_type="employee")
self.plan = Plan.objects.create(name="fixture", slug="fixture")
self.sub = Subscription.objects.create(user=self.user, plan=self.plan, status="active", provisioning_state="active")
self.device = Device.objects.create(subscription=self.sub, device_id="fixture-device-1234567890", active=True)
self.session, self.token = ClientSession.issue(self.sub, self.device)
self.node = Node.objects.create(name="VPN-fixture", slug="fixture-node", region="fixture", server="example.invalid",
port=11084, protocol="vless_reality", status="online", active=True, subscription_enabled=True)
self.node_token = "node-fixture-token-" + "x"*32
self.node.set_agent_token(self.node_token)
self.node.save(update_fields=["agent_token_digest"])
self.client = Client()
def tearDown(self):
self.clock.stop()
self.env.stop()
self.temp.cleanup()
def get(self, token=None, **kwargs):
with CaptureQueriesContext(connection) as queries:
response = self.client.get("/api/v1/client/node-traffic/", HTTP_AUTHORIZATION="Bearer "+(token if token is not None else self.token), **kwargs)
self.assertTrue(all(q["sql"].lstrip().upper().startswith("SELECT") for q in queries.captured_queries), queries.captured_queries)
self.assertNotIn(self.token.encode(), response.content)
self.assertNotIn(self.session.token_digest.encode(), response.content)
self.assertIn("no-store", response.get("Cache-Control", ""))
return response
def post(self, payload=None, token=None, slug="fixture-node"):
with CaptureQueriesContext(connection) as queries:
response = self.client.post("/api/v1/node/host-traffic/", data=json.dumps(payload or batch()), content_type="application/json",
HTTP_AUTHORIZATION="Bearer "+(token if token is not None else self.node_token), HTTP_X_NODE_SLUG=slug)
self.assertTrue(all(q["sql"].lstrip().upper().startswith("SELECT") for q in queries.captured_queries), queries.captured_queries)
self.assertNotIn(self.node_token.encode(), response.content)
return response
def test_staff_token_get_and_primary_database_unchanged(self):
self.assertEqual(self.post().status_code, 200)
response = self.get()
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["nodes"][0]["current_upload_bytes_per_second"], 2000)
self.session.refresh_from_db()
self.assertEqual(self.session.last_seen_at, NOW)
self.assertEqual(LoginAttempt.objects.count(), 0)
def test_missing_malformed_unknown_token(self):
response = self.client.get("/api/v1/client/node-traffic/")
self.assertEqual(response.status_code, 401)
for token in ["x", "x"*31, "x"*257, "x"*40]:
with self.subTest(token_length=len(token)):
self.assertEqual(self.get(token).status_code, 401)
def test_expired_or_revoked_session(self):
self.session.expires_at = NOW
self.session.save(update_fields=["expires_at"])
self.assertEqual(self.get().status_code, 401)
self.session.expires_at = NOW+timedelta(days=1)
self.session.revoked_at = NOW
self.session.save(update_fields=["expires_at", "revoked_at"])
self.assertEqual(self.get().status_code, 401)
def test_device_disabled(self):
self.device.active = False
self.device.save(update_fields=["active"])
self.assertEqual(self.get().status_code, 403)
def test_staff_and_active_account_checks(self):
for field, value in [("is_staff", False), ("is_active", False), ("account_status", "suspended"),
("account_status", "departed"), ("account_status", "pending")]:
original = getattr(self.user, field)
setattr(self.user, field, value)
self.user.save(update_fields=[field])
with self.subTest(field=field, value=value):
self.assertEqual(self.get().status_code, 403)
setattr(self.user, field, original)
self.user.save(update_fields=[field])
def test_subscription_expiry_suspension_provisioning_quota(self):
for field, value in [("expires_at", NOW), ("status", "suspended"), ("provisioning_state", "pending")]:
original = getattr(self.sub, field)
setattr(self.sub, field, value)
self.sub.save(update_fields=[field])
self.assertEqual(self.get().status_code, 403)
self.sub.refresh_from_db()
self.assertEqual(getattr(self.sub, field), value)
setattr(self.sub, field, original)
self.sub.save(update_fields=[field])
self.sub.traffic_limit_bytes = 10
self.sub.upload_bytes = 10
self.sub.save(update_fields=["traffic_limit_bytes", "upload_bytes"])
self.assertEqual(self.get().status_code, 403)
self.sub.refresh_from_db()
self.assertEqual(self.sub.status, "active")
def test_node_auth_and_disabled_not_accepted(self):
self.assertEqual(self.post(token="unknown"+"x"*32).status_code, 401)
self.assertEqual(self.post(slug="different").status_code, 401)
self.node.active = False
self.node.save(update_fields=["active"])
self.assertEqual(self.post().status_code, 401)
def test_dynamic_node_scope_only_active_and_subscribed(self):
for i in range(2, 5):
Node.objects.create(name=f"VPN{i}", slug=f"node-{i}", region="fixture", server="example.invalid", port=10000+i,
protocol="vless_reality", active=(i != 3), subscription_enabled=(i != 4))
self.assertEqual({n["slug"] for n in self.get().json()["nodes"]}, {"fixture-node", "node-2"})
def test_invalid_payload_size_and_method(self):
self.assertEqual(self.client.post("/api/v1/client/node-traffic/").status_code, 405)
self.assertEqual(self.client.get("/api/v1/node/host-traffic/").status_code, 405)
self.assertEqual(self.client.post("/api/v1/node/host-traffic/", data="x"*65537,
content_type="application/json", HTTP_AUTHORIZATION="Bearer "+self.node_token, HTTP_X_NODE_SLUG="fixture-node").status_code, 400)
invalid = batch()
invalid["node_slug"] = "other"
self.assertEqual(self.post(invalid).status_code, 400)
def test_read_requires_initialized_store_and_since_validation(self):
self.path.unlink()
self.assertEqual(self.get().status_code, 503)
self.assertFalse(self.path.exists())
store.initialize(self.path)
self.assertEqual(self.get(QUERY_STRING="since=bad").status_code, 400)
self.assertEqual(self.get(QUERY_STRING="since=2099-01-01T00:00:00Z").status_code, 400)
if __name__ == "__main__":
suite = unittest.TestSuite([unittest.defaultTestLoader.loadTestsFromTestCase(StoreTests),
unittest.defaultTestLoader.loadTestsFromTestCase(EndpointTests)])
runner = DiscoverRunner(verbosity=2)
old_config = runner.setup_databases()
try:
result = unittest.TextTestRunner(verbosity=2).run(suite)
report = {"passed": result.wasSuccessful(), "tests_run": result.testsRun,
"failures": len(result.failures), "errors": len(result.errors),
"django_version": django.get_version(), "actual_production_models": True,
"production_servers_modified": False, "primary_database_dml_in_requests": False,
"fixture": str(OUTPUT / "client-node-traffic-fixture.json")}
(OUTPUT / "security-test-result.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
finally:
runner.teardown_databases(old_config)
runtime_context.cleanup()
sys.exit(0 if result.wasSuccessful() else 1)