466 lines
18 KiB
Python
466 lines
18 KiB
Python
import json
|
|
import uuid
|
|
from datetime import timedelta
|
|
from io import StringIO
|
|
from unittest.mock import patch
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.core.management import call_command, get_commands
|
|
from django.core.management.base import CommandError
|
|
from django.test import TestCase
|
|
from django.utils import timezone
|
|
|
|
from control import dispatch
|
|
from control.models import (
|
|
ClientSession,
|
|
Device,
|
|
Node,
|
|
NodeDeployment,
|
|
Plan,
|
|
Subscription,
|
|
UsageRecord,
|
|
)
|
|
from control.services import desired_subscriptions_for_node
|
|
|
|
|
|
class RetiredNodeProvisioningTests(TestCase):
|
|
def setUp(self):
|
|
User = get_user_model()
|
|
self.user = User.objects.create_user(
|
|
username="retirement-user",
|
|
email="retirement@example.com",
|
|
password="retirement-test-password",
|
|
display_name="Retirement Test",
|
|
identity_type=User.IdentityType.EMPLOYEE,
|
|
account_status=User.AccountStatus.ACTIVE,
|
|
)
|
|
self.plan = Plan.objects.create(
|
|
name="Retirement Test Plan",
|
|
slug="retirement-test-plan",
|
|
audience=Plan.Audience.EMPLOYEE,
|
|
employee_benefit=True,
|
|
duration_days=0,
|
|
)
|
|
self.subscription = Subscription.objects.create(
|
|
user=self.user,
|
|
plan=self.plan,
|
|
status=Subscription.Status.ACTIVE,
|
|
provisioning_state=Subscription.ProvisioningState.ACTIVE,
|
|
)
|
|
self.node = Node.objects.create(
|
|
name="Legacy Node",
|
|
slug="legacy-node",
|
|
region="Legacy",
|
|
server="legacy.example.invalid",
|
|
port=11082,
|
|
protocol=Node.Protocol.VLESS_REALITY,
|
|
status=Node.Status.ONLINE,
|
|
active=True,
|
|
subscription_enabled=True,
|
|
sni="www.example.com",
|
|
reality_public_key="test-public-key",
|
|
reality_short_id="0123456789abcdef",
|
|
)
|
|
|
|
def test_disabled_or_unavailable_node_never_receives_subscription_credentials(self):
|
|
self.assertIn(self.subscription, desired_subscriptions_for_node(self.node))
|
|
|
|
unavailable_states = (
|
|
{"active": False},
|
|
{"subscription_enabled": False},
|
|
{"status": Node.Status.PREPARING},
|
|
{"status": Node.Status.MAINTENANCE},
|
|
{"status": Node.Status.OFFLINE},
|
|
)
|
|
for changes in unavailable_states:
|
|
with self.subTest(changes=changes):
|
|
Node.objects.filter(pk=self.node.pk).update(
|
|
active=True,
|
|
subscription_enabled=True,
|
|
status=Node.Status.ONLINE,
|
|
)
|
|
Node.objects.filter(pk=self.node.pk).update(**changes)
|
|
self.node.refresh_from_db()
|
|
self.assertFalse(desired_subscriptions_for_node(self.node).exists())
|
|
|
|
def test_profile_and_config_exclude_retired_nodes(self):
|
|
target = Node.objects.create(
|
|
name="VPN004",
|
|
slug="racknerd-newyork-004",
|
|
region="New York",
|
|
server="vpn004.example.invalid",
|
|
port=11084,
|
|
protocol=Node.Protocol.VLESS_REALITY,
|
|
status=Node.Status.ONLINE,
|
|
active=True,
|
|
subscription_enabled=True,
|
|
sort_order=1,
|
|
sni="www.example.com",
|
|
reality_public_key="target-public-key",
|
|
reality_short_id="fedcba9876543210",
|
|
)
|
|
self.node.subscription_enabled = False
|
|
self.node.save(update_fields=["subscription_enabled"])
|
|
device = Device.objects.create(
|
|
subscription=self.subscription,
|
|
device_id="single-node-profile-device",
|
|
)
|
|
_, token = ClientSession.issue(self.subscription, device)
|
|
headers = {"HTTP_AUTHORIZATION": f"Bearer {token}"}
|
|
|
|
profile_response = self.client.get("/api/v1/client/profile/", **headers)
|
|
self.assertEqual(profile_response.status_code, 200)
|
|
self.assertEqual(
|
|
[node["slug"] for node in profile_response.json()["profile"]["nodes"]],
|
|
[target.slug],
|
|
)
|
|
|
|
config_response = self.client.get(
|
|
"/api/v1/client/config/",
|
|
{"route": "smart"},
|
|
**headers,
|
|
)
|
|
self.assertEqual(config_response.status_code, 200)
|
|
self.assertEqual(config_response.json()["node"]["slug"], target.slug)
|
|
|
|
retired_response = self.client.get(
|
|
"/api/v1/client/config/",
|
|
{"node": self.node.slug, "route": "smart"},
|
|
**headers,
|
|
)
|
|
self.assertEqual(retired_response.status_code, 404)
|
|
|
|
def test_sync_preserves_administrative_state_and_returns_no_credentials(self):
|
|
self.node.set_agent_token("offline-node-token")
|
|
self.node.save(update_fields=["agent_token_digest"])
|
|
|
|
for status in (
|
|
Node.Status.PREPARING,
|
|
Node.Status.MAINTENANCE,
|
|
Node.Status.OFFLINE,
|
|
):
|
|
with self.subTest(status=status):
|
|
Node.objects.filter(pk=self.node.pk).update(
|
|
status=status,
|
|
active=True,
|
|
subscription_enabled=True,
|
|
last_seen_at=None,
|
|
)
|
|
response = self.client.get(
|
|
"/api/v1/node/sync/",
|
|
HTTP_X_NODE_SLUG=self.node.slug,
|
|
HTTP_AUTHORIZATION="Bearer offline-node-token",
|
|
)
|
|
|
|
self.assertEqual(response.status_code, 200)
|
|
self.assertEqual(response.json()["clients"], [])
|
|
self.node.refresh_from_db()
|
|
self.assertEqual(self.node.status, status)
|
|
self.assertIsNotNone(self.node.last_seen_at)
|
|
|
|
|
|
class SharedDispatchLockRegistrationTests(TestCase):
|
|
def test_dispatch_exposes_one_shared_runtime_lock_for_reservations_and_retirement(self):
|
|
self.assertTrue(hasattr(dispatch, "lock_vpn_ai_runtime"))
|
|
|
|
|
|
class SingleNodeRetirementCommandRegistrationTests(TestCase):
|
|
def test_safe_retirement_command_is_registered(self):
|
|
self.assertIn("retire_legacy_nodes", get_commands())
|
|
|
|
|
|
class SingleNodeRetirementCommandTests(TestCase):
|
|
legacy_slugs = ("aliyun-tokyo-002", "aliyun-siliconvalley-003")
|
|
|
|
@staticmethod
|
|
def create_node(slug, port, *, sort_order=10):
|
|
return Node.objects.create(
|
|
name=slug,
|
|
slug=slug,
|
|
region=slug,
|
|
server=f"{slug}.example.invalid",
|
|
port=port,
|
|
protocol=Node.Protocol.VLESS_REALITY,
|
|
status=Node.Status.ONLINE,
|
|
active=True,
|
|
subscription_enabled=True,
|
|
last_seen_at=timezone.now(),
|
|
sort_order=sort_order,
|
|
sni="www.example.com",
|
|
reality_public_key=f"{slug}-public-key",
|
|
reality_short_id=f"{port:016d}"[-16:],
|
|
)
|
|
|
|
def setUp(self):
|
|
User = get_user_model()
|
|
user = User.objects.create_user(
|
|
username="retirement-command-user",
|
|
email="retirement-command@example.com",
|
|
password="retirement-command-test-password",
|
|
display_name="Retirement Command Test",
|
|
identity_type=User.IdentityType.EMPLOYEE,
|
|
account_status=User.AccountStatus.ACTIVE,
|
|
)
|
|
plan = Plan.objects.create(
|
|
name="Retirement Command Plan",
|
|
slug="retirement-command-plan",
|
|
audience=Plan.Audience.EMPLOYEE,
|
|
employee_benefit=True,
|
|
duration_days=0,
|
|
)
|
|
self.subscription = Subscription.objects.create(
|
|
user=user,
|
|
plan=plan,
|
|
status=Subscription.Status.ACTIVE,
|
|
provisioning_state=Subscription.ProvisioningState.ACTIVE,
|
|
route_mode=Subscription.RouteMode.DEDICATED,
|
|
)
|
|
self.target = self.create_node("racknerd-newyork-004", 11084, sort_order=1)
|
|
self.legacy_nodes = (
|
|
self.create_node(self.legacy_slugs[0], 10803),
|
|
self.create_node(self.legacy_slugs[1], 11083),
|
|
)
|
|
for index, node in enumerate(self.legacy_nodes):
|
|
node.set_agent_token(f"legacy-node-token-{index}")
|
|
node.save(update_fields=["agent_token_digest"])
|
|
self.subscription.allowed_nodes.set(self.legacy_nodes)
|
|
self.device = Device.objects.create(
|
|
subscription=self.subscription,
|
|
device_id="retirement-command-device",
|
|
)
|
|
self.active_session, _ = ClientSession.issue(self.subscription, self.device)
|
|
ClientSession.objects.filter(pk=self.active_session.pk).update(
|
|
assigned_node=self.legacy_nodes[0],
|
|
dispatch_decision={"node": self.legacy_nodes[0].slug},
|
|
)
|
|
self.expired_session, _ = ClientSession.issue(
|
|
self.subscription,
|
|
self.device,
|
|
lifetime=timedelta(seconds=-1),
|
|
)
|
|
ClientSession.objects.filter(pk=self.expired_session.pk).update(
|
|
assigned_node=self.legacy_nodes[1],
|
|
dispatch_decision={"node": self.legacy_nodes[1].slug},
|
|
)
|
|
for node in self.legacy_nodes:
|
|
NodeDeployment.objects.create(
|
|
subscription=self.subscription,
|
|
node=node,
|
|
deployed=True,
|
|
applied_at=timezone.now(),
|
|
)
|
|
self.usage = UsageRecord.objects.create(
|
|
subscription=self.subscription,
|
|
node=self.legacy_nodes[0],
|
|
day=timezone.localdate(),
|
|
upload_bytes=123,
|
|
download_bytes=456,
|
|
)
|
|
|
|
def run_retirement(self, phase):
|
|
output = StringIO()
|
|
args = () if phase == "drain" else ("--phase", phase)
|
|
call_command("retire_legacy_nodes", *args, stdout=output)
|
|
return output.getvalue()
|
|
|
|
def acknowledge_empty_authorization(self, node, index):
|
|
response = self.client.post(
|
|
"/api/v1/node/sync/",
|
|
data=json.dumps(
|
|
{
|
|
"report_id": str(uuid.uuid4()),
|
|
"success": True,
|
|
"applied_subscription_ids": [],
|
|
"usage": [],
|
|
}
|
|
),
|
|
content_type="application/json",
|
|
HTTP_X_NODE_SLUG=node.slug,
|
|
HTTP_AUTHORIZATION=f"Bearer legacy-node-token-{index}",
|
|
)
|
|
self.assertEqual(response.status_code, 200, response.content)
|
|
node.refresh_from_db()
|
|
self.assertEqual(node.status, Node.Status.MAINTENANCE)
|
|
|
|
def test_drain_migrates_authorization_and_active_sessions_without_deleting_history(self):
|
|
self.run_retirement("drain")
|
|
self.run_retirement("drain")
|
|
|
|
self.subscription.refresh_from_db()
|
|
self.assertEqual(
|
|
list(self.subscription.allowed_nodes.values_list("slug", flat=True)),
|
|
[self.target.slug],
|
|
)
|
|
self.active_session.refresh_from_db()
|
|
self.assertEqual(self.active_session.assigned_node, self.target)
|
|
self.assertEqual(self.active_session.dispatch_decision, {})
|
|
self.expired_session.refresh_from_db()
|
|
self.assertEqual(self.expired_session.assigned_node, self.legacy_nodes[1])
|
|
|
|
for node in self.legacy_nodes:
|
|
node.refresh_from_db()
|
|
self.assertTrue(node.active)
|
|
self.assertFalse(node.subscription_enabled)
|
|
self.assertEqual(node.status, Node.Status.MAINTENANCE)
|
|
self.assertFalse(desired_subscriptions_for_node(node).exists())
|
|
|
|
self.assertEqual(Node.objects.filter(slug__in=self.legacy_slugs).count(), 2)
|
|
self.assertTrue(UsageRecord.objects.filter(pk=self.usage.pk).exists())
|
|
|
|
def test_finalize_requires_agent_revocation_acknowledgement_then_is_idempotent(self):
|
|
self.run_retirement("drain")
|
|
|
|
with self.assertRaisesMessage(CommandError, "still report deployed credentials"):
|
|
self.run_retirement("finalize")
|
|
|
|
for index, node in enumerate(self.legacy_nodes):
|
|
self.acknowledge_empty_authorization(node, index)
|
|
self.run_retirement("finalize")
|
|
self.run_retirement("finalize")
|
|
|
|
for node in self.legacy_nodes:
|
|
node.refresh_from_db()
|
|
self.assertFalse(node.active)
|
|
self.assertFalse(node.subscription_enabled)
|
|
self.assertEqual(node.status, Node.Status.OFFLINE)
|
|
self.assertEqual(Node.objects.filter(slug__in=self.legacy_slugs).count(), 2)
|
|
self.assertTrue(UsageRecord.objects.filter(pk=self.usage.pk).exists())
|
|
|
|
def test_get_authenticated_before_finalize_cannot_serve_a_retired_generation(self):
|
|
stale_authenticated_node = Node.objects.get(pk=self.legacy_nodes[0].pk)
|
|
Node.objects.filter(pk=stale_authenticated_node.pk).update(
|
|
active=False,
|
|
subscription_enabled=False,
|
|
status=Node.Status.OFFLINE,
|
|
)
|
|
|
|
with patch("control.views._authenticate_node", return_value=stale_authenticated_node):
|
|
response = self.client.get("/api/v1/node/sync/")
|
|
|
|
self.assertEqual(response.status_code, 409)
|
|
self.assertEqual(response.json(), {"error": "node retired"})
|
|
|
|
def test_post_authenticated_before_finalize_cannot_restore_a_deployment(self):
|
|
self.run_retirement("drain")
|
|
node = self.legacy_nodes[0]
|
|
stale_authenticated_node = Node.objects.get(pk=node.pk)
|
|
deployment = NodeDeployment.objects.get(node=node, subscription=self.subscription)
|
|
deployment.deployed = False
|
|
deployment.revoked_at = timezone.now()
|
|
deployment.save(update_fields=["deployed", "revoked_at", "updated_at"])
|
|
Node.objects.filter(pk=node.pk).update(
|
|
active=False,
|
|
subscription_enabled=False,
|
|
status=Node.Status.OFFLINE,
|
|
)
|
|
|
|
with patch("control.views._authenticate_node", return_value=stale_authenticated_node):
|
|
response = self.client.post(
|
|
"/api/v1/node/sync/",
|
|
data=json.dumps(
|
|
{
|
|
"report_id": str(uuid.uuid4()),
|
|
"success": True,
|
|
"applied_subscription_ids": [self.subscription.pk],
|
|
"usage": [],
|
|
}
|
|
),
|
|
content_type="application/json",
|
|
)
|
|
|
|
self.assertEqual(response.status_code, 409)
|
|
self.assertEqual(response.json(), {"error": "node retired"})
|
|
deployment.refresh_from_db()
|
|
self.assertFalse(deployment.deployed)
|
|
node.refresh_from_db()
|
|
self.assertFalse(node.active)
|
|
self.assertEqual(node.status, Node.Status.OFFLINE)
|
|
|
|
def test_finalize_refuses_nodes_that_have_not_been_drained(self):
|
|
NodeDeployment.objects.filter(node__in=self.legacy_nodes).update(
|
|
deployed=False,
|
|
revoked_at=timezone.now(),
|
|
)
|
|
|
|
with self.assertRaisesMessage(CommandError, "must be drained"):
|
|
self.run_retirement("finalize")
|
|
|
|
for node in self.legacy_nodes:
|
|
node.refresh_from_db()
|
|
self.assertTrue(node.active)
|
|
self.assertTrue(node.subscription_enabled)
|
|
self.assertEqual(node.status, Node.Status.ONLINE)
|
|
|
|
def test_finalize_refuses_false_deployments_without_post_drain_empty_acknowledgement(self):
|
|
self.run_retirement("drain")
|
|
NodeDeployment.objects.filter(node__in=self.legacy_nodes).update(
|
|
deployed=False,
|
|
revoked_at=timezone.now(),
|
|
)
|
|
|
|
with self.assertRaisesMessage(CommandError, "empty authorization acknowledgement"):
|
|
self.run_retirement("finalize")
|
|
|
|
for node in self.legacy_nodes:
|
|
node.refresh_from_db()
|
|
self.assertTrue(node.active)
|
|
|
|
def test_drain_refuses_an_unavailable_replacement_without_mutating_legacy_nodes(self):
|
|
self.target.status = Node.Status.MAINTENANCE
|
|
self.target.save(update_fields=["status"])
|
|
|
|
with self.assertRaisesMessage(CommandError, "replacement node"):
|
|
self.run_retirement("drain")
|
|
|
|
for node in self.legacy_nodes:
|
|
node.refresh_from_db()
|
|
self.assertTrue(node.active)
|
|
self.assertTrue(node.subscription_enabled)
|
|
self.assertEqual(node.status, Node.Status.ONLINE)
|
|
|
|
def test_drain_refuses_replacement_without_a_fresh_heartbeat(self):
|
|
for last_seen_at in (None, timezone.now() - dispatch.FRESHNESS - timedelta(seconds=1)):
|
|
with self.subTest(last_seen_at=last_seen_at):
|
|
Node.objects.filter(pk=self.target.pk).update(last_seen_at=last_seen_at)
|
|
|
|
with self.assertRaisesMessage(CommandError, "fresh heartbeat"):
|
|
self.run_retirement("drain")
|
|
|
|
for node in self.legacy_nodes:
|
|
node.refresh_from_db()
|
|
self.assertTrue(node.active)
|
|
self.assertTrue(node.subscription_enabled)
|
|
self.assertEqual(node.status, Node.Status.ONLINE)
|
|
|
|
def test_drain_requires_both_named_legacy_rows(self):
|
|
for retained_count in (0, 1):
|
|
with self.subTest(retained_count=retained_count):
|
|
for index, node in enumerate(self.legacy_nodes):
|
|
node.slug = (
|
|
self.legacy_slugs[index]
|
|
if index < retained_count
|
|
else f"renamed-legacy-{index}"
|
|
)
|
|
node.save(update_fields=["slug"])
|
|
|
|
with self.assertRaisesMessage(CommandError, "both legacy node records"):
|
|
self.run_retirement("drain")
|
|
|
|
for index, node in enumerate(self.legacy_nodes):
|
|
node.slug = self.legacy_slugs[index]
|
|
node.save(update_fields=["slug"])
|
|
|
|
def test_drain_aborts_before_mutation_when_shared_dispatch_lock_is_unavailable(self):
|
|
with patch(
|
|
"control.management.commands.retire_legacy_nodes.lock_vpn_ai_runtime",
|
|
side_effect=CommandError("dispatch lock unavailable"),
|
|
):
|
|
with self.assertRaisesMessage(CommandError, "dispatch lock unavailable"):
|
|
self.run_retirement("drain")
|
|
|
|
self.active_session.refresh_from_db()
|
|
self.assertEqual(self.active_session.assigned_node, self.legacy_nodes[0])
|
|
for node in self.legacy_nodes:
|
|
node.refresh_from_db()
|
|
self.assertTrue(node.subscription_enabled)
|