907 lines
41 KiB
Python
907 lines
41 KiB
Python
|
|
import json
|
||
|
|
import uuid
|
||
|
|
from unittest.mock import patch
|
||
|
|
|
||
|
|
from django.contrib.auth import get_user_model
|
||
|
|
from django.core.exceptions import ValidationError
|
||
|
|
from django.core.management import call_command
|
||
|
|
from django.test import TestCase, override_settings
|
||
|
|
from django.urls import reverse
|
||
|
|
from django.utils import timezone
|
||
|
|
|
||
|
|
from accounts.models import LoginAttempt
|
||
|
|
from accounts.admin import approve_as_external
|
||
|
|
from accounts.forms import RegistrationForm
|
||
|
|
from control.models import (
|
||
|
|
ClientSession,
|
||
|
|
Device,
|
||
|
|
LearnedRouteRule,
|
||
|
|
Node,
|
||
|
|
NodeReport,
|
||
|
|
NodeTrafficSample,
|
||
|
|
Plan,
|
||
|
|
PlanApplication,
|
||
|
|
RouteObservation,
|
||
|
|
RoutingPolicy,
|
||
|
|
Subscription,
|
||
|
|
UsageRecord,
|
||
|
|
HourlyUsageRecord,
|
||
|
|
VpnAiRuntime,
|
||
|
|
)
|
||
|
|
from control.vpn_ai import run_vpn_ai_cycle
|
||
|
|
|
||
|
|
|
||
|
|
@override_settings(
|
||
|
|
SECURE_SSL_REDIRECT=False,
|
||
|
|
PUBLIC_BASE_URL="https://vpn.toplc.cn",
|
||
|
|
STORAGES={
|
||
|
|
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
|
||
|
|
"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"},
|
||
|
|
},
|
||
|
|
)
|
||
|
|
class PlatformFlowTests(TestCase):
|
||
|
|
def setUp(self):
|
||
|
|
User = get_user_model()
|
||
|
|
self.admin = User.objects.create_superuser(
|
||
|
|
username="admin",
|
||
|
|
email="admin@example.com",
|
||
|
|
password="A-strong-admin-password-123",
|
||
|
|
display_name="管理员",
|
||
|
|
identity_type=User.IdentityType.EMPLOYEE,
|
||
|
|
account_status=User.AccountStatus.ACTIVE,
|
||
|
|
)
|
||
|
|
self.user = User.objects.create_user(
|
||
|
|
username="tester",
|
||
|
|
email="tester@example.com",
|
||
|
|
password="A-strong-user-password-123",
|
||
|
|
display_name="测试用户",
|
||
|
|
identity_type=User.IdentityType.EXTERNAL,
|
||
|
|
account_status=User.AccountStatus.ACTIVE,
|
||
|
|
)
|
||
|
|
self.plan = Plan.objects.create(
|
||
|
|
name="测试月度套餐",
|
||
|
|
slug="test-monthly",
|
||
|
|
audience=Plan.Audience.EXTERNAL,
|
||
|
|
price_cny=10,
|
||
|
|
traffic_limit_gb=10,
|
||
|
|
duration_days=30,
|
||
|
|
device_limit=2,
|
||
|
|
)
|
||
|
|
self.policy = RoutingPolicy.objects.create(
|
||
|
|
name="默认策略",
|
||
|
|
is_global=True,
|
||
|
|
rules=["GEOIP,CN,DIRECT", "MATCH,节点选择"],
|
||
|
|
)
|
||
|
|
self.node = Node.objects.create(
|
||
|
|
name="测试节点",
|
||
|
|
slug="test-node",
|
||
|
|
region="测试区",
|
||
|
|
server="203.0.113.10",
|
||
|
|
port=443,
|
||
|
|
protocol=Node.Protocol.VLESS_REALITY,
|
||
|
|
status=Node.Status.ONLINE,
|
||
|
|
active=True,
|
||
|
|
subscription_enabled=True,
|
||
|
|
sni="www.example.com",
|
||
|
|
reality_public_key="public-key",
|
||
|
|
reality_short_id="0123456789abcdef",
|
||
|
|
)
|
||
|
|
self.node.set_agent_token("node-test-token-that-is-long-enough-123")
|
||
|
|
self.node.save(update_fields=["agent_token_digest"])
|
||
|
|
|
||
|
|
def create_active_subscription(self):
|
||
|
|
subscription = Subscription.objects.create(user=self.user, plan=self.plan)
|
||
|
|
subscription.activate()
|
||
|
|
subscription.provisioning_state = Subscription.ProvisioningState.ACTIVE
|
||
|
|
subscription.save(update_fields=["provisioning_state"])
|
||
|
|
return subscription
|
||
|
|
|
||
|
|
def test_paid_application_requires_payment(self):
|
||
|
|
application = PlanApplication.objects.create(user=self.user, plan=self.plan)
|
||
|
|
with self.assertRaises(ValidationError):
|
||
|
|
application.approve(self.admin)
|
||
|
|
application.payment_status = PlanApplication.PaymentStatus.PAID
|
||
|
|
application.save(update_fields=["payment_status"])
|
||
|
|
subscription = application.approve(self.admin)
|
||
|
|
self.assertEqual(subscription.status, Subscription.Status.ACTIVE)
|
||
|
|
self.assertEqual(subscription.traffic_limit_bytes, 10 * 1024**3)
|
||
|
|
application.refresh_from_db()
|
||
|
|
self.assertEqual(application.subscription, subscription)
|
||
|
|
|
||
|
|
def test_application_approval_is_idempotent(self):
|
||
|
|
application = PlanApplication.objects.create(
|
||
|
|
user=self.user,
|
||
|
|
plan=self.plan,
|
||
|
|
payment_status=PlanApplication.PaymentStatus.PAID,
|
||
|
|
)
|
||
|
|
first = application.approve(self.admin)
|
||
|
|
second = application.approve(self.admin)
|
||
|
|
self.assertEqual(first.pk, second.pk)
|
||
|
|
self.assertEqual(Subscription.objects.filter(user=self.user).count(), 1)
|
||
|
|
|
||
|
|
def test_plan_change_reuses_subscription_and_preserves_period_usage(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
subscription.upload_bytes = 1024
|
||
|
|
subscription.download_bytes = 2048
|
||
|
|
subscription.save(update_fields=["upload_bytes", "download_bytes"])
|
||
|
|
original_period = (subscription.starts_at, subscription.expires_at)
|
||
|
|
original_credential = (subscription.credential_uuid, subscription.token_version)
|
||
|
|
new_plan = Plan.objects.create(
|
||
|
|
name="升级套餐",
|
||
|
|
slug="upgraded-monthly",
|
||
|
|
audience=Plan.Audience.EXTERNAL,
|
||
|
|
price_cny=20,
|
||
|
|
traffic_limit_gb=30,
|
||
|
|
duration_days=60,
|
||
|
|
device_limit=5,
|
||
|
|
)
|
||
|
|
application = PlanApplication.objects.create(
|
||
|
|
user=self.user,
|
||
|
|
plan=new_plan,
|
||
|
|
payment_status=PlanApplication.PaymentStatus.PAID,
|
||
|
|
)
|
||
|
|
|
||
|
|
changed = application.approve(self.admin)
|
||
|
|
|
||
|
|
self.assertEqual(changed.pk, subscription.pk)
|
||
|
|
self.assertEqual(changed.plan, new_plan)
|
||
|
|
self.assertEqual(changed.status, Subscription.Status.ACTIVE)
|
||
|
|
self.assertEqual(changed.provisioning_state, Subscription.ProvisioningState.PENDING)
|
||
|
|
self.assertEqual(changed.traffic_limit_bytes, 30 * 1024**3)
|
||
|
|
self.assertEqual(changed.device_limit, 5)
|
||
|
|
self.assertEqual(changed.used_bytes, 3072)
|
||
|
|
self.assertEqual((changed.starts_at, changed.expires_at), original_period)
|
||
|
|
self.assertEqual((changed.credential_uuid, changed.token_version), original_credential)
|
||
|
|
|
||
|
|
def test_active_subscriber_can_apply_for_a_different_plan(self):
|
||
|
|
self.create_active_subscription()
|
||
|
|
new_plan = Plan.objects.create(
|
||
|
|
name="可申请的新套餐",
|
||
|
|
slug="change-request-plan",
|
||
|
|
audience=Plan.Audience.EXTERNAL,
|
||
|
|
price_cny=0,
|
||
|
|
traffic_limit_gb=20,
|
||
|
|
duration_days=30,
|
||
|
|
device_limit=3,
|
||
|
|
)
|
||
|
|
self.client.force_login(self.user)
|
||
|
|
|
||
|
|
response = self.client.post(reverse("apply-plan"), {"plan": new_plan.pk, "note": "升级"})
|
||
|
|
|
||
|
|
self.assertRedirects(response, reverse("portal-dashboard"))
|
||
|
|
application = PlanApplication.objects.get(user=self.user, status=PlanApplication.Status.PENDING)
|
||
|
|
self.assertEqual(application.plan, new_plan)
|
||
|
|
|
||
|
|
def test_user_admin_approval_creates_subscription_from_pending_application(self):
|
||
|
|
self.user.account_status = self.user.AccountStatus.PENDING
|
||
|
|
self.user.save(update_fields=["account_status"])
|
||
|
|
application = PlanApplication.objects.create(
|
||
|
|
user=self.user,
|
||
|
|
plan=self.plan,
|
||
|
|
payment_status=PlanApplication.PaymentStatus.PAID,
|
||
|
|
)
|
||
|
|
self.client.force_login(self.admin)
|
||
|
|
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("admin:accounts_user_changelist"),
|
||
|
|
{"action": approve_as_external.__name__, "_selected_action": [self.user.pk]},
|
||
|
|
follow=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
self.user.refresh_from_db()
|
||
|
|
application.refresh_from_db()
|
||
|
|
self.assertEqual(self.user.account_status, self.user.AccountStatus.ACTIVE)
|
||
|
|
self.assertEqual(application.status, PlanApplication.Status.APPROVED)
|
||
|
|
self.assertIsNotNone(application.subscription_id)
|
||
|
|
|
||
|
|
def test_user_admin_approval_without_application_does_not_enable_account(self):
|
||
|
|
self.user.account_status = self.user.AccountStatus.PENDING
|
||
|
|
self.user.save(update_fields=["account_status"])
|
||
|
|
self.client.force_login(self.admin)
|
||
|
|
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("admin:accounts_user_changelist"),
|
||
|
|
{"action": approve_as_external.__name__, "_selected_action": [self.user.pk]},
|
||
|
|
follow=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
self.user.refresh_from_db()
|
||
|
|
self.assertEqual(self.user.account_status, self.user.AccountStatus.PENDING)
|
||
|
|
self.assertFalse(Subscription.objects.filter(user=self.user).exists())
|
||
|
|
|
||
|
|
def test_approval_refuses_duplicate_subscriptions_without_cancelling_any(self):
|
||
|
|
first = self.create_active_subscription()
|
||
|
|
duplicate = Subscription.objects.create(user=self.user, plan=self.plan)
|
||
|
|
application = PlanApplication.objects.create(
|
||
|
|
user=self.user, plan=self.plan, payment_status=PlanApplication.PaymentStatus.PAID,
|
||
|
|
)
|
||
|
|
credentials = (first.credential_uuid, duplicate.credential_uuid)
|
||
|
|
with self.assertRaisesMessage(ValidationError, "多个未结束订阅"):
|
||
|
|
application.approve(self.admin)
|
||
|
|
first.refresh_from_db()
|
||
|
|
duplicate.refresh_from_db()
|
||
|
|
application.refresh_from_db()
|
||
|
|
self.assertEqual(first.status, Subscription.Status.ACTIVE)
|
||
|
|
self.assertEqual(duplicate.status, Subscription.Status.PENDING)
|
||
|
|
self.assertEqual((first.credential_uuid, duplicate.credential_uuid), credentials)
|
||
|
|
self.assertEqual(application.status, PlanApplication.Status.PENDING)
|
||
|
|
|
||
|
|
def test_failed_subscription_save_rolls_back_user_approval(self):
|
||
|
|
self.user.account_status = self.user.AccountStatus.PENDING
|
||
|
|
self.user.save(update_fields=["account_status"])
|
||
|
|
application = PlanApplication.objects.create(
|
||
|
|
user=self.user, plan=self.plan, payment_status=PlanApplication.PaymentStatus.PAID,
|
||
|
|
)
|
||
|
|
with patch.object(Subscription, "full_clean", side_effect=ValidationError("test validation failure")):
|
||
|
|
with self.assertRaises(ValidationError):
|
||
|
|
application.approve(self.admin)
|
||
|
|
self.user.refresh_from_db()
|
||
|
|
application.refresh_from_db()
|
||
|
|
self.assertEqual(self.user.account_status, self.user.AccountStatus.PENDING)
|
||
|
|
self.assertEqual(application.status, PlanApplication.Status.PENDING)
|
||
|
|
self.assertFalse(Subscription.objects.filter(user=self.user).exists())
|
||
|
|
|
||
|
|
def test_disabled_plan_cannot_be_approved(self):
|
||
|
|
application = PlanApplication.objects.create(
|
||
|
|
user=self.user, plan=self.plan, payment_status=PlanApplication.PaymentStatus.PAID,
|
||
|
|
)
|
||
|
|
Plan.objects.filter(pk=self.plan.pk).update(active=False)
|
||
|
|
with self.assertRaisesMessage(ValidationError, "已停用"):
|
||
|
|
application.approve(self.admin)
|
||
|
|
self.assertFalse(Subscription.objects.filter(user=self.user).exists())
|
||
|
|
|
||
|
|
def test_pending_application_submission_is_not_duplicated(self):
|
||
|
|
PlanApplication.submit(user=self.user, plan=self.plan)
|
||
|
|
with self.assertRaisesMessage(ValidationError, "已有待处理申请"):
|
||
|
|
PlanApplication.submit(user=self.user, plan=self.plan)
|
||
|
|
self.assertEqual(PlanApplication.objects.filter(user=self.user).count(), 1)
|
||
|
|
|
||
|
|
def test_approval_rechecks_audience_changed_after_submission(self):
|
||
|
|
application = PlanApplication.submit(user=self.user, plan=self.plan)
|
||
|
|
application.payment_status = PlanApplication.PaymentStatus.PAID
|
||
|
|
application.save(update_fields=["payment_status"])
|
||
|
|
Plan.objects.filter(pk=self.plan.pk).update(audience=Plan.Audience.EMPLOYEE)
|
||
|
|
with self.assertRaisesMessage(ValidationError, "适用身份"):
|
||
|
|
application.approve(self.admin)
|
||
|
|
application.refresh_from_db()
|
||
|
|
self.assertEqual(application.status, PlanApplication.Status.PENDING)
|
||
|
|
self.assertFalse(self.user.subscriptions.exists())
|
||
|
|
|
||
|
|
def test_all_audience_plan_remains_approvable(self):
|
||
|
|
Plan.objects.filter(pk=self.plan.pk).update(audience=Plan.Audience.ALL)
|
||
|
|
application = PlanApplication.objects.create(
|
||
|
|
user=self.user, plan=self.plan, payment_status=PlanApplication.PaymentStatus.PAID,
|
||
|
|
)
|
||
|
|
self.assertEqual(application.approve(self.admin).plan_id, self.plan.pk)
|
||
|
|
|
||
|
|
def test_active_user_dashboard_has_change_plan_link(self):
|
||
|
|
self.create_active_subscription()
|
||
|
|
self.client.force_login(self.user)
|
||
|
|
self.assertContains(self.client.get(reverse("portal-dashboard")), "申请更换套餐")
|
||
|
|
|
||
|
|
def test_employee_benefit_not_self_assigned_by_registration(self):
|
||
|
|
benefit = Plan.objects.create(name="员工福利", slug="private-benefit", employee_benefit=True)
|
||
|
|
form = RegistrationForm()
|
||
|
|
self.assertNotIn(benefit, form.fields["plan"].queryset)
|
||
|
|
with self.assertRaisesMessage(ValidationError, "不可申请"):
|
||
|
|
PlanApplication.submit(user=self.user, plan=benefit)
|
||
|
|
|
||
|
|
def test_registration_without_plan_does_not_create_account(self):
|
||
|
|
data = self.registration_data()
|
||
|
|
data.pop("plan")
|
||
|
|
response = self.client.post(reverse("register"), data)
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
self.assertIn("plan", response.context["form"].errors)
|
||
|
|
self.assertFalse(get_user_model().objects.filter(username="newcontact").exists())
|
||
|
|
|
||
|
|
def test_registration_rollback_if_application_fails(self):
|
||
|
|
with patch.object(PlanApplication, "submit", side_effect=ValidationError("套餐已经停用")):
|
||
|
|
response = self.client.post(reverse("register"), self.registration_data())
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
self.assertFalse(get_user_model().objects.filter(username="newcontact").exists())
|
||
|
|
|
||
|
|
def test_free_registration_approval_automatically_creates_subscription(self):
|
||
|
|
self.plan.price_cny = 0
|
||
|
|
self.plan.save(update_fields=["price_cny"])
|
||
|
|
response = self.client.post(reverse("register"), self.registration_data())
|
||
|
|
self.assertRedirects(response, reverse("portal-dashboard"))
|
||
|
|
created = get_user_model().objects.get(username="newcontact")
|
||
|
|
application = PlanApplication.objects.get(user=created)
|
||
|
|
self.assertEqual(application.payment_status, PlanApplication.PaymentStatus.NOT_REQUIRED)
|
||
|
|
subscription = application.approve(self.admin)
|
||
|
|
self.assertEqual(subscription.user_id, created.pk)
|
||
|
|
self.assertEqual(subscription.status, Subscription.Status.ACTIVE)
|
||
|
|
self.assertEqual(subscription.provisioning_state, Subscription.ProvisioningState.PENDING)
|
||
|
|
|
||
|
|
def test_subscription_endpoint_returns_mihomo_yaml(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
response = self.client.get(reverse("subscription-config", args=[subscription.subscription_token]))
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
self.assertContains(response, "type: vless")
|
||
|
|
self.assertContains(response, str(subscription.credential_uuid))
|
||
|
|
self.assertEqual(response["Cache-Control"], "no-store")
|
||
|
|
|
||
|
|
def test_rotating_token_invalidates_old_url(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
old_token = subscription.subscription_token
|
||
|
|
subscription.rotate_subscription()
|
||
|
|
response = self.client.get(reverse("subscription-config", args=[old_token]))
|
||
|
|
self.assertEqual(response.status_code, 404)
|
||
|
|
|
||
|
|
def test_windows_client_login_profile_config_and_logout(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
login_response = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.email,
|
||
|
|
"password": "A-strong-user-password-123",
|
||
|
|
"device_id": "windows-device-0001",
|
||
|
|
"device_name": "测试电脑",
|
||
|
|
"app_version": "0.1.0",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
)
|
||
|
|
self.assertEqual(login_response.status_code, 200)
|
||
|
|
token = login_response.json()["access_token"]
|
||
|
|
self.assertNotIn(token, ClientSession.objects.get().token_digest)
|
||
|
|
headers = {"HTTP_AUTHORIZATION": f"Bearer {token}"}
|
||
|
|
|
||
|
|
profile_response = self.client.get(reverse("client-profile"), **headers)
|
||
|
|
self.assertEqual(profile_response.status_code, 200)
|
||
|
|
self.assertEqual(profile_response.json()["profile"]["nodes"][0]["slug"], self.node.slug)
|
||
|
|
|
||
|
|
config_response = self.client.get(
|
||
|
|
reverse("client-config"),
|
||
|
|
{"node": self.node.slug, "route": "smart"},
|
||
|
|
**headers,
|
||
|
|
)
|
||
|
|
self.assertEqual(config_response.status_code, 200)
|
||
|
|
config = config_response.json()["config"]
|
||
|
|
self.assertEqual(config["inbounds"][0]["port"], 10808)
|
||
|
|
self.assertEqual(config["outbounds"][0]["protocol"], "vless")
|
||
|
|
self.assertEqual(
|
||
|
|
config["outbounds"][0]["settings"]["vnext"][0]["users"][0]["id"],
|
||
|
|
str(subscription.credential_uuid),
|
||
|
|
)
|
||
|
|
self.assertEqual(config["routing"]["rules"][-1]["outboundTag"], "direct")
|
||
|
|
self.assertEqual(config["routing"]["rules"][-1]["network"], "tcp,udp")
|
||
|
|
|
||
|
|
logout_response = self.client.post(reverse("client-logout"), **headers)
|
||
|
|
self.assertEqual(logout_response.status_code, 200)
|
||
|
|
self.assertIsNotNone(ClientSession.objects.get().revoked_at)
|
||
|
|
self.assertEqual(self.client.get(reverse("client-profile"), **headers).status_code, 401)
|
||
|
|
|
||
|
|
def test_windows_client_enforces_device_limit(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
subscription.device_limit = 1
|
||
|
|
subscription.save(update_fields=["device_limit"])
|
||
|
|
Device.objects.create(
|
||
|
|
subscription=subscription,
|
||
|
|
device_id="existing-device-0001",
|
||
|
|
name="已有设备",
|
||
|
|
platform="Windows",
|
||
|
|
)
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.username,
|
||
|
|
"password": "A-strong-user-password-123",
|
||
|
|
"device_id": "second-device-0002",
|
||
|
|
"device_name": "第二台电脑",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 403)
|
||
|
|
self.assertIn("设备数量", response.json()["error"])
|
||
|
|
|
||
|
|
def test_client_business_denials_do_not_count_as_password_failures(self):
|
||
|
|
for number in range(9):
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.email,
|
||
|
|
"password": "A-strong-user-password-123",
|
||
|
|
"device_id": f"no-subscription-device-{number:04d}",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_X_REAL_IP="198.51.100.10",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 403)
|
||
|
|
self.assertIn("没有可用订阅", response.json()["error"])
|
||
|
|
self.assertFalse(LoginAttempt.objects.exists())
|
||
|
|
|
||
|
|
def test_client_rate_limit_is_scoped_by_network_and_login_identifier(self):
|
||
|
|
for number in range(7):
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.email,
|
||
|
|
"password": "definitely-the-wrong-password",
|
||
|
|
"device_id": f"wrong-password-device-{number:04d}",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_X_REAL_IP="198.51.100.20",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 401)
|
||
|
|
|
||
|
|
blocked = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.email,
|
||
|
|
"password": "definitely-the-wrong-password",
|
||
|
|
"device_id": "blocked-device-0001",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_X_REAL_IP="198.51.100.20",
|
||
|
|
)
|
||
|
|
self.assertEqual(blocked.status_code, 429)
|
||
|
|
|
||
|
|
other_login = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": "another-user@example.com",
|
||
|
|
"password": "definitely-the-wrong-password",
|
||
|
|
"device_id": "other-login-device-0001",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_X_REAL_IP="198.51.100.20",
|
||
|
|
)
|
||
|
|
self.assertEqual(other_login.status_code, 401)
|
||
|
|
self.assertEqual(LoginAttempt.objects.count(), 2)
|
||
|
|
|
||
|
|
def test_verified_credentials_clear_previous_failures_without_subscription(self):
|
||
|
|
for number in range(2):
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.email,
|
||
|
|
"password": "definitely-the-wrong-password",
|
||
|
|
"device_id": f"retry-device-{number:04d}",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_X_REAL_IP="198.51.100.30",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 401)
|
||
|
|
self.assertEqual(LoginAttempt.objects.get().failures, 2)
|
||
|
|
|
||
|
|
verified = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.email,
|
||
|
|
"password": "A-strong-user-password-123",
|
||
|
|
"device_id": "retry-device-verified",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_X_REAL_IP="198.51.100.30",
|
||
|
|
)
|
||
|
|
self.assertEqual(verified.status_code, 403)
|
||
|
|
self.assertFalse(LoginAttempt.objects.exists())
|
||
|
|
|
||
|
|
def test_android_client_is_recorded_as_android_device(self):
|
||
|
|
self.create_active_subscription()
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.email,
|
||
|
|
"password": "A-strong-user-password-123",
|
||
|
|
"device_id": "android-device-0001",
|
||
|
|
"device_name": "测试手机",
|
||
|
|
"app_version": "1.0.0",
|
||
|
|
"platform": "android",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
device = Device.objects.get(device_id="android-device-0001")
|
||
|
|
self.assertEqual(device.name, "测试手机")
|
||
|
|
self.assertEqual(device.platform, "Android · 优创⁺纵横家 1.0.0")
|
||
|
|
|
||
|
|
def test_ios_client_is_recorded_as_apple_device(self):
|
||
|
|
self.create_active_subscription()
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-login"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"login": self.user.email,
|
||
|
|
"password": "A-strong-user-password-123",
|
||
|
|
"device_id": "ios-device-00000001",
|
||
|
|
"device_name": "测试 iPhone",
|
||
|
|
"app_version": "1.0.0",
|
||
|
|
"platform": "ios",
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
device = Device.objects.get(device_id="ios-device-00000001")
|
||
|
|
self.assertEqual(device.name, "测试 iPhone")
|
||
|
|
self.assertEqual(device.platform, "iPhone / iPad · 优创⁺纵横家 1.0.0")
|
||
|
|
|
||
|
|
def test_vpn_ai_accepts_minimal_observations_and_learns_across_devices(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
sessions = []
|
||
|
|
for number in (1, 2):
|
||
|
|
device = Device.objects.create(
|
||
|
|
subscription=subscription,
|
||
|
|
device_id=f"learning-device-{number:04d}",
|
||
|
|
name=f"学习设备 {number}",
|
||
|
|
)
|
||
|
|
session, token = ClientSession.issue(subscription, device)
|
||
|
|
sessions.append((session, token))
|
||
|
|
|
||
|
|
for _, token in sessions:
|
||
|
|
direct_report_id = str(uuid.uuid4())
|
||
|
|
for outcome in ("direct_failed", "proxy_succeeded"):
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-observations"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"observations": [
|
||
|
|
{
|
||
|
|
"report_id": direct_report_id if outcome == "direct_failed" else str(uuid.uuid4()),
|
||
|
|
"related_report_id": direct_report_id if outcome == "proxy_succeeded" else None,
|
||
|
|
"evidence_kind": "tls" if outcome == "proxy_succeeded" else "",
|
||
|
|
"target_type": "domain",
|
||
|
|
"target": "blocked.example.com",
|
||
|
|
"port": 443,
|
||
|
|
"network": "tcp",
|
||
|
|
"outcome": outcome,
|
||
|
|
"failure_kind": "timeout" if outcome == "direct_failed" else "other",
|
||
|
|
"node": self.node.slug,
|
||
|
|
"client_version": "0.2.6",
|
||
|
|
}
|
||
|
|
]
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_AUTHORIZATION=f"Bearer {token}",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
|
||
|
|
self.node.last_seen_at = timezone.now()
|
||
|
|
self.node.save(update_fields=["last_seen_at"])
|
||
|
|
runtime = VpnAiRuntime.objects.create(service_name="vpn-ai")
|
||
|
|
run_vpn_ai_cycle(runtime)
|
||
|
|
rule = LearnedRouteRule.objects.get(target="blocked.example.com")
|
||
|
|
self.assertEqual(rule.status, LearnedRouteRule.Status.ACTIVE)
|
||
|
|
self.assertEqual(rule.distinct_devices, 2)
|
||
|
|
self.assertEqual(rule.failure_reports, 2)
|
||
|
|
self.assertEqual(rule.proxy_success_reports, 2)
|
||
|
|
|
||
|
|
config_response = self.client.get(
|
||
|
|
reverse("client-config"),
|
||
|
|
{"node": self.node.slug, "route": "smart"},
|
||
|
|
HTTP_AUTHORIZATION=f"Bearer {sessions[0][1]}",
|
||
|
|
)
|
||
|
|
# Learning candidates must not silently force proxy on older clients.
|
||
|
|
self.assertNotIn("full:blocked.example.com", json.dumps(config_response.json()))
|
||
|
|
candidates = self.client.get(reverse("client-routing-rules"), HTTP_AUTHORIZATION=f"Bearer {sessions[0][1]}")
|
||
|
|
self.assertTrue(any(rule["target"] == "blocked.example.com" for rule in candidates.json()["rules"]))
|
||
|
|
|
||
|
|
def test_preset_openai_and_google_domains_are_immediately_active(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
device = Device.objects.create(
|
||
|
|
subscription=subscription,
|
||
|
|
device_id="preset-rule-device",
|
||
|
|
name="预置规则设备",
|
||
|
|
)
|
||
|
|
_, token = ClientSession.issue(subscription, device)
|
||
|
|
|
||
|
|
preset = LearnedRouteRule.objects.get(target="openai.com")
|
||
|
|
self.assertEqual(preset.source, LearnedRouteRule.Source.PRESET)
|
||
|
|
self.assertEqual(preset.match_mode, LearnedRouteRule.MatchMode.SUFFIX)
|
||
|
|
self.assertEqual(preset.status, LearnedRouteRule.Status.ACTIVE)
|
||
|
|
self.assertTrue(preset.manually_locked)
|
||
|
|
|
||
|
|
response = self.client.get(
|
||
|
|
reverse("client-config"),
|
||
|
|
{"node": self.node.slug, "route": "smart"},
|
||
|
|
HTTP_AUTHORIZATION=f"Bearer {token}",
|
||
|
|
)
|
||
|
|
proxy_rule = next(
|
||
|
|
rule
|
||
|
|
for rule in response.json()["config"]["routing"]["rules"]
|
||
|
|
if rule.get("outboundTag") == "proxy" and "domain:openai.com" in rule.get("domain", [])
|
||
|
|
)
|
||
|
|
self.assertIn("domain:chatgpt.com", proxy_rule["domain"])
|
||
|
|
self.assertIn("domain:google.com", proxy_rule["domain"])
|
||
|
|
self.assertIn("domain:googleapis.com", proxy_rule["domain"])
|
||
|
|
|
||
|
|
def test_admin_index_uses_fishbone_workflow(self):
|
||
|
|
self.client.force_login(self.admin)
|
||
|
|
response = self.client.get(reverse("admin:index"))
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
self.assertTemplateUsed(response, "admin/vpn_dashboard.html")
|
||
|
|
self.assertContains(response, "服务开通鱼骨流程")
|
||
|
|
self.assertContains(response, "AI 智能代理动作流程")
|
||
|
|
self.assertContains(response, "持续状态 1")
|
||
|
|
self.assertContains(response, "持续状态 5")
|
||
|
|
self.assertContains(response, "直连可用状态")
|
||
|
|
self.assertContains(response, "只要检测结果不变,状态就保持不变")
|
||
|
|
self.assertContains(response, "节点运维鱼骨流程")
|
||
|
|
self.assertContains(response, "安全审计鱼骨闭环")
|
||
|
|
self.assertContains(response, 'role="tablist"')
|
||
|
|
self.assertContains(response, 'data-workflow-tab=', count=4)
|
||
|
|
self.assertContains(response, "OpenAI/Codex")
|
||
|
|
|
||
|
|
def test_vpn_ai_rejects_private_and_company_targets(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
device = Device.objects.create(subscription=subscription, device_id="private-target-device", name="设备")
|
||
|
|
_, token = ClientSession.issue(subscription, device)
|
||
|
|
for target_type, target in (("ip", "127.0.0.1"), ("domain", "vpn.toplc.cn")):
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-observations"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"observations": [
|
||
|
|
{
|
||
|
|
"report_id": str(uuid.uuid4()),
|
||
|
|
"target_type": target_type,
|
||
|
|
"target": target,
|
||
|
|
"port": 443,
|
||
|
|
"network": "tcp",
|
||
|
|
"outcome": "direct_failed",
|
||
|
|
}
|
||
|
|
]
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_AUTHORIZATION=f"Bearer {token}",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 400)
|
||
|
|
self.assertEqual(RouteObservation.objects.count(), 0)
|
||
|
|
|
||
|
|
def test_observation_classifies_http_and_socket_access(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
device = Device.objects.create(subscription=subscription, device_id="access-kind-device", name="识别设备")
|
||
|
|
_, token = ClientSession.issue(subscription, device)
|
||
|
|
|
||
|
|
for port, expected in ((443, RouteObservation.AccessKind.HTTP), (5222, RouteObservation.AccessKind.SOCKET)):
|
||
|
|
response = self.client.post(
|
||
|
|
reverse("client-observations"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"observations": [
|
||
|
|
{
|
||
|
|
"report_id": str(uuid.uuid4()),
|
||
|
|
"target_type": "domain",
|
||
|
|
"target": f"failure-{port}.example.com",
|
||
|
|
"port": port,
|
||
|
|
"network": "tcp",
|
||
|
|
"outcome": "direct_failed",
|
||
|
|
}
|
||
|
|
]
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
HTTP_AUTHORIZATION=f"Bearer {token}",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
self.assertEqual(RouteObservation.objects.get(target=f"failure-{port}.example.com").access_kind, expected)
|
||
|
|
|
||
|
|
def test_usage_rollup_and_quota_enforcement(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
UsageRecord.objects.create(
|
||
|
|
subscription=subscription,
|
||
|
|
node=self.node,
|
||
|
|
day=timezone.localdate(),
|
||
|
|
upload_bytes=4 * 1024**3,
|
||
|
|
download_bytes=6 * 1024**3,
|
||
|
|
)
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
self.assertEqual(subscription.used_bytes, 10 * 1024**3)
|
||
|
|
response = self.client.get(reverse("subscription-config", args=[subscription.subscription_token]))
|
||
|
|
self.assertEqual(response.status_code, 403)
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
self.assertEqual(subscription.status, Subscription.Status.SUSPENDED)
|
||
|
|
|
||
|
|
def test_departed_user_is_cancelled_by_enforcement(self):
|
||
|
|
subscription = self.create_active_subscription()
|
||
|
|
self.user.account_status = self.user.AccountStatus.DEPARTED
|
||
|
|
self.user.save(update_fields=["account_status"])
|
||
|
|
call_command("enforce_vpn")
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
self.assertEqual(subscription.status, Subscription.Status.CANCELLED)
|
||
|
|
self.assertEqual(subscription.provisioning_state, Subscription.ProvisioningState.REVOKE_PENDING)
|
||
|
|
|
||
|
|
def registration_data(self):
|
||
|
|
return {
|
||
|
|
"username": "newcontact",
|
||
|
|
"display_name": "新联系人",
|
||
|
|
"email": "newcontact@example.com",
|
||
|
|
"phone": "13800000000",
|
||
|
|
"company_name": "测试公司",
|
||
|
|
"password1": "A-new-contact-password-123",
|
||
|
|
"password2": "A-new-contact-password-123",
|
||
|
|
"accept_terms": "on",
|
||
|
|
"plan": self.plan.pk,
|
||
|
|
}
|
||
|
|
|
||
|
|
def test_registration_creates_pending_external_user(self):
|
||
|
|
response = self.client.post(reverse("register"), self.registration_data())
|
||
|
|
self.assertRedirects(response, reverse("portal-dashboard"))
|
||
|
|
created = get_user_model().objects.get(username="newcontact")
|
||
|
|
self.assertEqual(created.account_status, created.AccountStatus.PENDING)
|
||
|
|
self.assertEqual(created.identity_type, created.IdentityType.EXTERNAL)
|
||
|
|
application = PlanApplication.objects.get(user=created)
|
||
|
|
self.assertEqual(application.plan, self.plan)
|
||
|
|
self.assertEqual(application.payment_status, PlanApplication.PaymentStatus.UNPAID)
|
||
|
|
self.assertEqual(application.status, PlanApplication.Status.PENDING)
|
||
|
|
self.assertFalse(Subscription.objects.filter(user=created).exists())
|
||
|
|
|
||
|
|
def test_node_sync_applies_revokes_and_reports_usage_idempotently(self):
|
||
|
|
subscription = Subscription.objects.create(user=self.user, plan=self.plan)
|
||
|
|
subscription.activate()
|
||
|
|
headers = {
|
||
|
|
"HTTP_X_NODE_SLUG": self.node.slug,
|
||
|
|
"HTTP_AUTHORIZATION": "Bearer node-test-token-that-is-long-enough-123",
|
||
|
|
"HTTP_X_AGENT_VERSION": "test-agent",
|
||
|
|
}
|
||
|
|
|
||
|
|
desired = self.client.get(reverse("node-sync"), **headers)
|
||
|
|
self.assertEqual(desired.status_code, 200)
|
||
|
|
self.assertEqual(desired.json()["clients"][0]["subscription_id"], subscription.pk)
|
||
|
|
|
||
|
|
report_id = str(uuid.uuid4())
|
||
|
|
report = {
|
||
|
|
"report_id": report_id,
|
||
|
|
"success": True,
|
||
|
|
"applied_subscription_ids": [subscription.pk],
|
||
|
|
"usage": [{"subscription_id": subscription.pk, "upload_bytes": 1024, "download_bytes": 2048}],
|
||
|
|
}
|
||
|
|
applied = self.client.post(
|
||
|
|
reverse("node-sync"),
|
||
|
|
data=json.dumps(report),
|
||
|
|
content_type="application/json",
|
||
|
|
**headers,
|
||
|
|
)
|
||
|
|
self.assertEqual(applied.status_code, 200)
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
self.assertEqual(subscription.provisioning_state, Subscription.ProvisioningState.ACTIVE)
|
||
|
|
self.assertEqual(subscription.used_bytes, 3072)
|
||
|
|
sample = NodeTrafficSample.objects.get()
|
||
|
|
self.assertEqual(sample.upload_bytes, 1024)
|
||
|
|
self.assertEqual(sample.download_bytes, 2048)
|
||
|
|
self.assertEqual(sample.interval_seconds, 60)
|
||
|
|
self.assertEqual(sample.upload_bytes_per_second, 1024 // 60)
|
||
|
|
self.assertEqual(sample.download_bytes_per_second, 2048 // 60)
|
||
|
|
self.assertEqual(sample.active_subscriptions, 1)
|
||
|
|
|
||
|
|
duplicate = self.client.post(
|
||
|
|
reverse("node-sync"),
|
||
|
|
data=json.dumps(report),
|
||
|
|
content_type="application/json",
|
||
|
|
**headers,
|
||
|
|
)
|
||
|
|
self.assertEqual(duplicate.json()["status"], "already_processed")
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
self.assertEqual(subscription.used_bytes, 3072)
|
||
|
|
self.assertEqual(NodeTrafficSample.objects.count(), 1)
|
||
|
|
hourly = HourlyUsageRecord.objects.get(subscription=subscription)
|
||
|
|
self.assertEqual(hourly.upload_bytes, 1024)
|
||
|
|
self.assertEqual(hourly.download_bytes, 2048)
|
||
|
|
self.assertEqual(hourly.hour.minute, 0)
|
||
|
|
|
||
|
|
subscription.suspend("test revoke")
|
||
|
|
desired = self.client.get(reverse("node-sync"), **headers)
|
||
|
|
self.assertEqual(desired.json()["clients"], [])
|
||
|
|
revoked = self.client.post(
|
||
|
|
reverse("node-sync"),
|
||
|
|
data=json.dumps(
|
||
|
|
{
|
||
|
|
"report_id": str(uuid.uuid4()),
|
||
|
|
"success": True,
|
||
|
|
"applied_subscription_ids": [],
|
||
|
|
"usage": [],
|
||
|
|
}
|
||
|
|
),
|
||
|
|
content_type="application/json",
|
||
|
|
**headers,
|
||
|
|
)
|
||
|
|
self.assertEqual(revoked.status_code, 200)
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
self.assertEqual(subscription.provisioning_state, Subscription.ProvisioningState.REVOKED)
|
||
|
|
self.assertEqual(NodeTrafficSample.objects.count(), 2)
|
||
|
|
|
||
|
|
def test_hourly_failure_rolls_back_daily_report_and_can_retry(self):
|
||
|
|
subscription = Subscription.objects.create(user=self.user, plan=self.plan)
|
||
|
|
subscription.activate()
|
||
|
|
headers = {"HTTP_X_NODE_SLUG": self.node.slug,
|
||
|
|
"HTTP_AUTHORIZATION": "Bearer node-test-token-that-is-long-enough-123"}
|
||
|
|
report = {"report_id": str(uuid.uuid4()), "success": True,
|
||
|
|
"applied_subscription_ids": [subscription.pk],
|
||
|
|
"usage": [{"subscription_id": subscription.pk, "upload_bytes": 10, "download_bytes": 20}]}
|
||
|
|
with patch.object(HourlyUsageRecord, "save", side_effect=RuntimeError("test write failure")):
|
||
|
|
with self.assertRaises(RuntimeError):
|
||
|
|
self.client.post(reverse("node-sync"), data=json.dumps(report), content_type="application/json", **headers)
|
||
|
|
self.assertFalse(UsageRecord.objects.filter(subscription=subscription).exists())
|
||
|
|
self.assertFalse(NodeReport.objects.filter(report_id=report["report_id"]).exists())
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
self.assertEqual(subscription.used_bytes, 0)
|
||
|
|
response = self.client.post(reverse("node-sync"), data=json.dumps(report), content_type="application/json", **headers)
|
||
|
|
self.assertEqual(response.status_code, 200)
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
self.assertEqual(subscription.used_bytes, 30)
|
||
|
|
self.assertEqual(HourlyUsageRecord.objects.get(subscription=subscription).download_bytes, 20)
|
||
|
|
|
||
|
|
def test_admin_node_traffic_dashboard_and_data(self):
|
||
|
|
self.node.last_seen_at = timezone.now()
|
||
|
|
self.node.total_upload_bytes = 4096
|
||
|
|
self.node.total_download_bytes = 8192
|
||
|
|
self.node.save(update_fields=["last_seen_at", "total_upload_bytes", "total_download_bytes"])
|
||
|
|
report = NodeReport.objects.create(node=self.node, report_id=uuid.uuid4())
|
||
|
|
NodeTrafficSample.objects.create(
|
||
|
|
node=self.node,
|
||
|
|
report=report,
|
||
|
|
interval_seconds=60,
|
||
|
|
upload_bytes=6000,
|
||
|
|
download_bytes=12000,
|
||
|
|
upload_bytes_per_second=100,
|
||
|
|
download_bytes_per_second=200,
|
||
|
|
active_subscriptions=3,
|
||
|
|
)
|
||
|
|
|
||
|
|
anonymous = self.client.get(reverse("admin-node-traffic"))
|
||
|
|
self.assertEqual(anonymous.status_code, 302)
|
||
|
|
self.client.force_login(self.admin)
|
||
|
|
dashboard = self.client.get(reverse("admin-node-traffic"))
|
||
|
|
self.assertEqual(dashboard.status_code, 200)
|
||
|
|
self.assertTemplateUsed(dashboard, "admin/node_traffic.html")
|
||
|
|
self.assertContains(dashboard, "节点实时流量监控")
|
||
|
|
|
||
|
|
data = self.client.get(reverse("admin-node-traffic-data"), {"minutes": 15})
|
||
|
|
self.assertEqual(data.status_code, 200)
|
||
|
|
self.assertEqual(data["Cache-Control"], "no-store")
|
||
|
|
payload = data.json()
|
||
|
|
self.assertEqual(payload["range_minutes"], 15)
|
||
|
|
self.assertEqual(payload["nodes"][0]["slug"], self.node.slug)
|
||
|
|
self.assertTrue(payload["nodes"][0]["online"])
|
||
|
|
self.assertEqual(payload["nodes"][0]["current_download_bytes_per_second"], 200)
|
||
|
|
self.assertEqual(payload["nodes"][0]["active_subscriptions"], 3)
|
||
|
|
self.assertNotIn("server", payload["nodes"][0])
|
||
|
|
|
||
|
|
def test_node_sync_rejects_bad_token(self):
|
||
|
|
response = self.client.get(
|
||
|
|
reverse("node-sync"),
|
||
|
|
HTTP_X_NODE_SLUG=self.node.slug,
|
||
|
|
HTTP_AUTHORIZATION="Bearer wrong-token",
|
||
|
|
)
|
||
|
|
self.assertEqual(response.status_code, 401)
|
||
|
|
|
||
|
|
def test_configure_node_creates_complete_node(self):
|
||
|
|
with patch.dict("os.environ", {"VPN_NODE_TOKEN": "management-command-node-token-123456"}):
|
||
|
|
call_command(
|
||
|
|
"configure_node",
|
||
|
|
slug="command-node",
|
||
|
|
name="命令节点",
|
||
|
|
region="测试地区",
|
||
|
|
server="198.51.100.20",
|
||
|
|
port=443,
|
||
|
|
sni="vpn.toplc.cn",
|
||
|
|
public_key="test-public-key",
|
||
|
|
short_id="0123456789abcdef",
|
||
|
|
)
|
||
|
|
node = Node.objects.get(slug="command-node")
|
||
|
|
self.assertEqual(node.port, 443)
|
||
|
|
self.assertTrue(node.check_agent_token("management-command-node-token-123456"))
|