130 lines
7.4 KiB
Python
130 lines
7.4 KiB
Python
|
|
"""Approval must not silently undo an independent account suspension/departure."""
|
||
|
|
from concurrent.futures import ThreadPoolExecutor
|
||
|
|
from threading import Event
|
||
|
|
|
||
|
|
from django.contrib.auth import get_user_model
|
||
|
|
from django.core.exceptions import ValidationError
|
||
|
|
from django.db import close_old_connections, connection, connections, transaction
|
||
|
|
from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
|
||
|
|
|
||
|
|
from control.approval_audit import audit_plan_approvals
|
||
|
|
from control.models import Plan, PlanApplication, Subscription
|
||
|
|
|
||
|
|
|
||
|
|
class AccountApprovalSafetyTests(TestCase):
|
||
|
|
def setUp(self):
|
||
|
|
self.owner = get_user_model().objects.create_user(
|
||
|
|
username="approval-owner-fixture", email="approval-owner@example.invalid", identity_type="employee"
|
||
|
|
)
|
||
|
|
self.reviewer = get_user_model().objects.create_superuser(
|
||
|
|
username="approval-reviewer-fixture", email="approval-reviewer@example.invalid", password="fixture-only"
|
||
|
|
)
|
||
|
|
self.plan = Plan.objects.create(name="Approval fixture", slug="approval-fixture")
|
||
|
|
|
||
|
|
def test_stale_submit_cannot_create_requests_for_suspended_departed_disabled_or_invalid_account(self):
|
||
|
|
for status, active in (("suspended", True), ("departed", True), ("pending", False), ("unknown", True)):
|
||
|
|
with self.subTest(status=status, is_active=active), transaction.atomic():
|
||
|
|
get_user_model().objects.filter(pk=self.owner.pk).update(account_status=status, is_active=active)
|
||
|
|
# self.owner intentionally still contains the old eligible state.
|
||
|
|
with self.assertRaises(ValidationError):
|
||
|
|
PlanApplication.submit(user=self.owner, plan=self.plan)
|
||
|
|
self.assertFalse(PlanApplication.objects.filter(user=self.owner).exists())
|
||
|
|
|
||
|
|
def test_approval_cannot_reactivate_stopped_accounts_or_change_previous_subscription(self):
|
||
|
|
subscription = Subscription.objects.create(
|
||
|
|
user=self.owner, plan=self.plan, status="suspended", upload_bytes=123, download_bytes=456
|
||
|
|
)
|
||
|
|
application = PlanApplication.objects.create(user=self.owner, plan=self.plan, payment_status="not_required")
|
||
|
|
before_sub = Subscription.objects.values().get(pk=subscription.pk)
|
||
|
|
before_app = PlanApplication.objects.values().get(pk=application.pk)
|
||
|
|
for status, active in (("suspended", True), ("departed", True), ("active", False), ("unknown", True)):
|
||
|
|
with self.subTest(status=status, is_active=active), transaction.atomic():
|
||
|
|
get_user_model().objects.filter(pk=self.owner.pk).update(account_status=status, is_active=active)
|
||
|
|
before_owner = get_user_model().objects.values().get(pk=self.owner.pk)
|
||
|
|
with self.assertRaises(ValidationError):
|
||
|
|
application.approve(self.reviewer)
|
||
|
|
self.assertEqual(get_user_model().objects.values().get(pk=self.owner.pk), before_owner)
|
||
|
|
self.assertEqual(Subscription.objects.values().get(pk=subscription.pk), before_sub)
|
||
|
|
self.assertEqual(PlanApplication.objects.values().get(pk=application.pk), before_app)
|
||
|
|
|
||
|
|
def test_already_approved_replay_is_read_only_after_departure(self):
|
||
|
|
application = PlanApplication.submit(user=self.owner, plan=self.plan)
|
||
|
|
subscription = application.approve(self.reviewer)
|
||
|
|
get_user_model().objects.filter(pk=self.owner.pk).update(account_status="departed")
|
||
|
|
subscription.cancel(reason="fixture departure")
|
||
|
|
before_owner = get_user_model().objects.values().get(pk=self.owner.pk)
|
||
|
|
before_sub = Subscription.objects.values().get(pk=subscription.pk)
|
||
|
|
self.assertEqual(application.approve(self.reviewer).pk, subscription.pk)
|
||
|
|
self.assertEqual(get_user_model().objects.values().get(pk=self.owner.pk), before_owner)
|
||
|
|
self.assertEqual(Subscription.objects.values().get(pk=subscription.pk), before_sub)
|
||
|
|
|
||
|
|
def test_audit_reports_stopped_pending_accounts_using_only_ids_and_without_repair(self):
|
||
|
|
application = PlanApplication.objects.create(user=self.owner, plan=self.plan)
|
||
|
|
get_user_model().objects.filter(pk=self.owner.pk).update(account_status="departed")
|
||
|
|
before_app = PlanApplication.objects.values().get(pk=application.pk)
|
||
|
|
statements = []
|
||
|
|
|
||
|
|
def readonly(execute, sql, params, many, context):
|
||
|
|
statements.append(sql)
|
||
|
|
self.assertTrue(sql.lstrip().upper().startswith(("SELECT", "PRAGMA")), sql)
|
||
|
|
return execute(sql, params, many, context)
|
||
|
|
|
||
|
|
with connection.execute_wrapper(readonly):
|
||
|
|
report = audit_plan_approvals(sample_limit=1)
|
||
|
|
self.assertTrue(statements)
|
||
|
|
finding = next(f for f in report["findings"] if f["code"] == "pending_account_no_longer_eligible")
|
||
|
|
self.assertEqual(finding["count"], 1)
|
||
|
|
self.assertEqual(finding["samples"], [{"id": application.pk, "user_id": self.owner.pk, "plan_id": self.plan.pk}])
|
||
|
|
self.assertNotIn(self.owner.username, str(report))
|
||
|
|
self.assertNotIn(self.owner.email, str(report))
|
||
|
|
self.assertFalse(report["database_modified"])
|
||
|
|
self.assertEqual(PlanApplication.objects.values().get(pk=application.pk), before_app)
|
||
|
|
|
||
|
|
|
||
|
|
@skipUnlessDBFeature("has_select_for_update")
|
||
|
|
class AccountApprovalLockTests(TransactionTestCase):
|
||
|
|
def test_approval_waits_for_account_lock_and_observes_committed_suspension(self):
|
||
|
|
user_model = get_user_model()
|
||
|
|
owner = user_model.objects.create_user(username="lock-owner-fixture", email="lock-owner@example.invalid")
|
||
|
|
reviewer = user_model.objects.create_superuser(
|
||
|
|
username="lock-reviewer-fixture", email="lock-reviewer@example.invalid", password="fixture-only"
|
||
|
|
)
|
||
|
|
plan = Plan.objects.create(name="Lock fixture", slug="lock-fixture")
|
||
|
|
application = PlanApplication.submit(user=owner, plan=plan)
|
||
|
|
locking_query_started = Event()
|
||
|
|
|
||
|
|
def approve():
|
||
|
|
close_old_connections()
|
||
|
|
try:
|
||
|
|
def observe(execute, sql, params, many, context):
|
||
|
|
if "FOR UPDATE" in sql.upper() and "accounts_user" in sql:
|
||
|
|
locking_query_started.set()
|
||
|
|
return execute(sql, params, many, context)
|
||
|
|
|
||
|
|
with connections["default"].cursor() as cursor:
|
||
|
|
cursor.execute("SET lock_timeout = '5s'")
|
||
|
|
with connections["default"].execute_wrapper(observe):
|
||
|
|
try:
|
||
|
|
application.approve(reviewer)
|
||
|
|
except ValidationError:
|
||
|
|
return "account_rejected"
|
||
|
|
return "approved"
|
||
|
|
finally:
|
||
|
|
connections.close_all()
|
||
|
|
|
||
|
|
with ThreadPoolExecutor(max_workers=1) as pool:
|
||
|
|
with transaction.atomic():
|
||
|
|
locked_owner = user_model.objects.select_for_update().get(pk=owner.pk)
|
||
|
|
locked_owner.account_status = "suspended"
|
||
|
|
locked_owner.save(update_fields=["account_status"])
|
||
|
|
future = pool.submit(approve)
|
||
|
|
self.assertTrue(locking_query_started.wait(timeout=8))
|
||
|
|
self.assertFalse(future.done())
|
||
|
|
self.assertEqual(future.result(timeout=12), "account_rejected")
|
||
|
|
owner.refresh_from_db()
|
||
|
|
application.refresh_from_db()
|
||
|
|
self.assertEqual(owner.account_status, "suspended")
|
||
|
|
self.assertEqual(application.status, "pending")
|
||
|
|
self.assertIsNone(application.subscription_id)
|
||
|
|
self.assertFalse(Subscription.objects.filter(user=owner).exists())
|