196 lines
12 KiB
Python
196 lines
12 KiB
Python
|
|
"""Real Django policy checks; all exercise writes are rolled back.
|
|||
|
|
|
|||
|
|
The deployment driver execs this source in a separate namespace and explicitly
|
|||
|
|
calls protected_snapshot()/validate(before); Django shell is not __main__.
|
|||
|
|
For a direct script entry, RATE500_BEFORE_JSON can supply the prior snapshot.
|
|||
|
|
No node process, network, user credential or limiter flag is changed here.
|
|||
|
|
"""
|
|||
|
|
import io
|
|||
|
|
import importlib
|
|||
|
|
import json
|
|||
|
|
import os
|
|||
|
|
import uuid
|
|||
|
|
from types import SimpleNamespace
|
|||
|
|
|
|||
|
|
from django.conf import settings
|
|||
|
|
from django.contrib import admin
|
|||
|
|
from django.contrib.auth import get_user_model
|
|||
|
|
from django.core.exceptions import ValidationError
|
|||
|
|
from django.core.management import call_command
|
|||
|
|
from django.db import IntegrityError, connection, transaction
|
|||
|
|
from django.db import migrations
|
|||
|
|
from django.db.migrations.executor import MigrationExecutor
|
|||
|
|
from django.test import RequestFactory
|
|||
|
|
from django.template.loader import render_to_string
|
|||
|
|
from django.utils import timezone
|
|||
|
|
|
|||
|
|
|
|||
|
|
def protected_snapshot():
|
|||
|
|
from shared_budget.models import AccountBandwidthExemption, AccountBandwidthPolicy
|
|||
|
|
return {
|
|||
|
|
"owner_policy": list(AccountBandwidthPolicy.objects.filter(user_id=5).values()),
|
|||
|
|
"exemptions": list(AccountBandwidthExemption.objects.order_by("policy_key").values()),
|
|||
|
|
"user_count": get_user_model().objects.count(),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def validate(before=None):
|
|||
|
|
from shared_budget import policy
|
|||
|
|
from shared_budget.allocator import node_bandwidth_budget_v2, node_budget_executor
|
|||
|
|
from shared_budget.models import AccountBandwidthBucket, AccountBandwidthExemption, AccountBandwidthPolicy
|
|||
|
|
from shared_budget.web_context import portal_context
|
|||
|
|
|
|||
|
|
checks, errors = {}, {}
|
|||
|
|
|
|||
|
|
def check(name, action):
|
|||
|
|
try:
|
|||
|
|
action()
|
|||
|
|
checks[name] = True
|
|||
|
|
except Exception as error:
|
|||
|
|
checks[name] = False
|
|||
|
|
errors[name] = f"{type(error).__name__}: {error}"
|
|||
|
|
|
|||
|
|
def require(value, message):
|
|||
|
|
if not value:
|
|||
|
|
raise AssertionError(message)
|
|||
|
|
|
|||
|
|
def rejected(action, exception):
|
|||
|
|
try:
|
|||
|
|
with transaction.atomic():
|
|||
|
|
action()
|
|||
|
|
except exception:
|
|||
|
|
return
|
|||
|
|
raise AssertionError(f"expected {exception.__name__}")
|
|||
|
|
|
|||
|
|
check("all_ordinary_users_have_policy", lambda: require(
|
|||
|
|
get_user_model().objects.exclude(pk=5).exclude(
|
|||
|
|
pk__in=AccountBandwidthPolicy.objects.values("user_id")).count() == 0, "missing ordinary policy"))
|
|||
|
|
check("all_ordinary_accounts_500_each_direction", lambda: require(
|
|||
|
|
not AccountBandwidthPolicy.objects.exclude(user_id=5).exclude(
|
|||
|
|
upload_limit_kib_per_second=500, download_limit_kib_per_second=500).exists(), "ordinary policy is not 500/500"))
|
|||
|
|
check("owner_fixed_id5_exemption_unchanged", lambda: require(
|
|||
|
|
list(AccountBandwidthExemption.objects.values_list("policy_key", "user_id")) == [("owner-approved-20261022", 5)],
|
|||
|
|
"expected existing fixed-ID owner exemption"))
|
|||
|
|
if before is not None:
|
|||
|
|
after = protected_snapshot()
|
|||
|
|
for key in ("owner_policy", "exemptions", "user_count"):
|
|||
|
|
check("migration_preserves_" + key, lambda key=key: require(
|
|||
|
|
json.dumps(after[key], sort_keys=True, default=str) == json.dumps(before[key], sort_keys=True, default=str), key + " changed"))
|
|||
|
|
check("default_is_500", lambda: require(
|
|||
|
|
AccountBandwidthPolicy._meta.get_field("upload_limit_kib_per_second").default == 500
|
|||
|
|
and AccountBandwidthPolicy._meta.get_field("download_limit_kib_per_second").default == 500, "default != 500"))
|
|||
|
|
check("admin_max_10240", lambda: require(policy.MAX_KIB_PER_SECOND == 10240, "max != 10240"))
|
|||
|
|
def migration_lock_order():
|
|||
|
|
module = importlib.import_module("shared_budget.migrations.0002_account_rate_500")
|
|||
|
|
first = module.Migration.operations[0]
|
|||
|
|
require(isinstance(first, migrations.RunPython) and first.code is module.lock_accounts_before_policy_ddl,
|
|||
|
|
"account lock must be first operation, before policy DDL")
|
|||
|
|
statements = []
|
|||
|
|
class Cursor:
|
|||
|
|
def __enter__(self):
|
|||
|
|
return self
|
|||
|
|
def __exit__(self, *args):
|
|||
|
|
return False
|
|||
|
|
def execute(self, sql):
|
|||
|
|
statements.append(sql)
|
|||
|
|
state = MigrationExecutor(connection).loader.project_state([("shared_budget", "0001_initial")]).apps
|
|||
|
|
first.code(state, SimpleNamespace(connection=SimpleNamespace(vendor="postgresql", ops=connection.ops, cursor=Cursor)))
|
|||
|
|
require(len(statements) == 2 and '"accounts_user" IN SHARE MODE' in statements[0]
|
|||
|
|
and '"shared_budget_accountbandwidthpolicy" IN SHARE ROW EXCLUSIVE MODE' in statements[1], "User must lock before Policy")
|
|||
|
|
check("migration_locks_user_before_any_policy_ddl", migration_lock_order)
|
|||
|
|
check("policy_501_converts_without_200_clamp", lambda: require(policy._limit_in_bytes(501) == 513024, "501 conversion"))
|
|||
|
|
check("policy_max_converts", lambda: require(policy._limit_in_bytes(10240) == 10485760, "10240 conversion"))
|
|||
|
|
for value in (0, -1, 10241, True, "500"):
|
|||
|
|
check("policy_rejects_" + type(value).__name__ + "_" + str(value), lambda value=value: rejected(lambda: policy._limit_in_bytes(value), ValueError))
|
|||
|
|
check("allocator_stays_disabled", lambda: require(
|
|||
|
|
getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is False
|
|||
|
|
and getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_ENABLED", False) is False, "allocator enabled"))
|
|||
|
|
factory = RequestFactory()
|
|||
|
|
for label, endpoint in (("credit", node_bandwidth_budget_v2), ("executor", node_budget_executor)):
|
|||
|
|
def disabled(endpoint=endpoint):
|
|||
|
|
response = endpoint(factory.post("/", "{}", content_type="application/json"))
|
|||
|
|
require(response.status_code == 503 and json.loads(response.content)["error_code"] == "budget_disabled", "API not disabled")
|
|||
|
|
check("disabled_" + label + "_api", disabled)
|
|||
|
|
|
|||
|
|
with transaction.atomic():
|
|||
|
|
user = get_user_model().objects.create_user(username="rate500-test-" + uuid.uuid4().hex,
|
|||
|
|
email=uuid.uuid4().hex + "@example.invalid", display_name="Isolated policy verification")
|
|||
|
|
row = AccountBandwidthPolicy.objects.get(user=user)
|
|||
|
|
check("new_user_signal_500_each_direction", lambda: require(
|
|||
|
|
(row.upload_limit_kib_per_second, row.download_limit_kib_per_second) == (500, 500), "new user defaults"))
|
|||
|
|
request = factory.get("/")
|
|||
|
|
request.user = get_user_model()(is_active=True, is_staff=True, is_superuser=True)
|
|||
|
|
form_type = admin.site._registry[AccountBandwidthPolicy].get_form(request, row)
|
|||
|
|
for value in (501, 10240):
|
|||
|
|
def form_valid(value=value):
|
|||
|
|
form = form_type(data={"upload_limit_kib_per_second": value, "download_limit_kib_per_second": value}, instance=row)
|
|||
|
|
require(form.is_valid(), str(form.errors))
|
|||
|
|
check("real_admin_form_accepts_" + str(value), form_valid)
|
|||
|
|
def model_valid(value=value):
|
|||
|
|
with transaction.atomic():
|
|||
|
|
row.upload_limit_kib_per_second = row.download_limit_kib_per_second = value
|
|||
|
|
row.full_clean()
|
|||
|
|
row.save()
|
|||
|
|
row.refresh_from_db()
|
|||
|
|
require(row.upload_limit_kib_per_second == value and row.download_limit_kib_per_second == value, "not stored")
|
|||
|
|
check("model_and_db_accept_" + str(value), model_valid)
|
|||
|
|
for value in (0, 10241):
|
|||
|
|
def invalid(value=value):
|
|||
|
|
row.upload_limit_kib_per_second = value
|
|||
|
|
rejected(row.full_clean, ValidationError)
|
|||
|
|
rejected(lambda: AccountBandwidthPolicy.objects.filter(user=user).update(download_limit_kib_per_second=value), IntegrityError)
|
|||
|
|
check("python_and_db_reject_" + str(value), invalid)
|
|||
|
|
def bucket_at_max():
|
|||
|
|
with transaction.atomic():
|
|||
|
|
AccountBandwidthBucket.objects.create(user=user, direction="upload", rate_bytes_per_second=10485760,
|
|||
|
|
available_microbytes=2097152000000, refilled_at=timezone.now())
|
|||
|
|
check("bucket_db_accepts_admin_max_rate_and_credit", bucket_at_max)
|
|||
|
|
check("bucket_db_rejects_above_max", lambda: rejected(lambda: AccountBandwidthBucket.objects.create(
|
|||
|
|
user=user, direction="download", rate_bytes_per_second=10485761, available_microbytes=0,
|
|||
|
|
refilled_at=timezone.now()), IntegrityError))
|
|||
|
|
check("bucket_db_rejects_above_credit_max", lambda: rejected(lambda: AccountBandwidthBucket.objects.create(
|
|||
|
|
user=user, direction="download", rate_bytes_per_second=512000, available_microbytes=2097152000001,
|
|||
|
|
refilled_at=timezone.now()), IntegrityError))
|
|||
|
|
check("portal_context_matches_500_and_max", lambda: require(
|
|||
|
|
portal_context(request)["admin_budget"]["default_upload"] == 500
|
|||
|
|
and portal_context(request)["admin_budget"]["default_download"] == 500
|
|||
|
|
and portal_context(request)["admin_budget"]["maximum_limit"] == 10240, "portal values"))
|
|||
|
|
def portal_template():
|
|||
|
|
rendered = render_to_string("includes/admin_budget.html", portal_context(request))
|
|||
|
|
require("500 KiB/s" in rendered and "10,240" not in rendered and "10240 KiB/s" in rendered
|
|||
|
|
and "1–200" not in rendered and "未开启" in rendered, "template range/default/state")
|
|||
|
|
check("actual_portal_template_500_and_max", portal_template)
|
|||
|
|
def database_defaults():
|
|||
|
|
AccountBandwidthPolicy.objects.filter(user=user).delete()
|
|||
|
|
table = connection.ops.quote_name(AccountBandwidthPolicy._meta.db_table)
|
|||
|
|
with connection.cursor() as cursor:
|
|||
|
|
cursor.execute("INSERT INTO " + table + " (user_id) VALUES (%s)", [user.pk])
|
|||
|
|
saved = AccountBandwidthPolicy.objects.get(user=user)
|
|||
|
|
require((saved.upload_limit_kib_per_second, saved.download_limit_kib_per_second) == (500, 500), "DB defaults")
|
|||
|
|
check("raw_insert_db_defaults_500", database_defaults)
|
|||
|
|
transaction.set_rollback(True)
|
|||
|
|
|
|||
|
|
def no_pending_migrations():
|
|||
|
|
call_command("makemigrations", "shared_budget", check=True, dry_run=True, stdout=io.StringIO())
|
|||
|
|
check("real_models_have_no_pending_migration", no_pending_migrations)
|
|||
|
|
check("all_real_apps_have_no_pending_migration", lambda: call_command(
|
|||
|
|
"makemigrations", check=True, dry_run=True, stdout=io.StringIO()))
|
|||
|
|
check("policy_retains_positive_small_integer_type", lambda: require(all(
|
|||
|
|
AccountBandwidthPolicy._meta.get_field(field).get_internal_type() == "PositiveSmallIntegerField"
|
|||
|
|
for field in ("upload_limit_kib_per_second", "download_limit_kib_per_second")), "policy field type changed"))
|
|||
|
|
return {"passed": all(checks.values()), "checks": checks, "errors": errors,
|
|||
|
|
"ordinary_account_count": get_user_model().objects.exclude(pk=5).count(),
|
|||
|
|
"allocator_enabled": False, "wire_enforcement_verified": False,
|
|||
|
|
"exercise_writes_rolled_back": True, "production_modified": False,
|
|||
|
|
"known_executor_max_bytes_per_second": 204800,
|
|||
|
|
"scope": "legacy shared_budget policy configuration only; no deployed 500 KiB/s enforcement claim"}
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
snapshot_file = os.environ.get("RATE500_BEFORE_JSON")
|
|||
|
|
before = json.load(open(snapshot_file, encoding="utf-8")) if snapshot_file else None
|
|||
|
|
result = validate(before)
|
|||
|
|
print("RATE500_CLONE_VALIDATION=" + json.dumps(result, ensure_ascii=False, sort_keys=True, default=str))
|
|||
|
|
if not result["passed"]:
|
|||
|
|
raise SystemExit(1)
|