harden OTP for real SMS and close the second audit round
Kavenegar is being switched on, so every OTP request now costs credit: - phone numbers are normalised to 09XXXXXXXXX everywhere (login, OTP, family invite, TEST_LOGIN_PHONES keys) and existing rows are migrated; non-Iranian and landline numbers are rejected before any SMS - cooldown and a daily per-phone cap are counted in the database, so the three gunicorn workers no longer triple them - a global daily OTP SMS cap (default 300) stops SMS pumping - per-IP rates widened for CGNAT / school Wi-Fi (env-overridable) - provider message id is logged; SMS text warns not to share the code Second audit round: an offer no longer shortens a longer paid plan, Zarinpal error bodies no longer 500, island XP reaches the parent report, a non-numeric questionId no longer 500s after the answer is generated. 596 tests green. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -422,9 +422,13 @@ REST_FRAMEWORK = {
|
||||
# `/api/health` در `clientIp` نشان میدهد سرور چه IPای میبیند.
|
||||
'NUM_PROXIES': int(os.environ.get('NUM_PROXIES', '2')),
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'otp_request': '5/hour',
|
||||
'otp_login': '10/hour',
|
||||
'guest_session': '20/hour',
|
||||
# سقفهای per-IP عمداً گشادهاند: پشتِ CGNATِ اپراتورهای موبایل، وایفایِ
|
||||
# مدرسه یا شبکهی یک دفتر، دهها نفر یک IP دارند و با ۵ در ساعت فقط ۵ نفر
|
||||
# میتوانستند وارد شوند. حفاظِ اصلی per-phone و per-code است (پایینتر و
|
||||
# در دیتابیس)؛ اینها فقط جلوی یک ماشینِ تنها را میگیرند.
|
||||
'otp_request': os.environ.get('OTP_REQUEST_IP_RATE', '20/hour'),
|
||||
'otp_login': os.environ.get('OTP_LOGIN_IP_RATE', '30/hour'),
|
||||
'guest_session': os.environ.get('GUEST_SESSION_IP_RATE', '60/hour'),
|
||||
'bazaar_verify': '10/hour',
|
||||
'ai_ask': '20/hour',
|
||||
'rag_ingest': '30/hour',
|
||||
@@ -600,6 +604,20 @@ OTP_REQUEST_PHONE_WINDOW_SECONDS = 3600
|
||||
# (که جلویِ burst رو نمیگیره، مثلاً ۵ تلاش در کمتر از یک ثانیه). این مقدار
|
||||
# باید با countdownِ فرانت یکی باشه — countdown صرفاً UX است، نه مرجعِ امنیتی.
|
||||
OTP_REQUEST_PHONE_COOLDOWN_SECONDS = 120
|
||||
|
||||
# عمرِ هر کدِ ورود. سقفهای دیتابیسیِ پایین زمانِ صدور را از expires_at منهای
|
||||
# همین مقدار میخوانند، پس عوض کردنش آن سقفها را هم (برای کدهای قدیمی) جابهجا میکند.
|
||||
OTP_TTL_SECONDS = 300
|
||||
|
||||
# سقفهایی که در دیتابیس شمرده میشوند، نه در کش. کشِ پیشفرض LocMem و مالِ
|
||||
# هر worker است، پس cooldown و سقفِ ساعتیِ بالا روی سرور (۳ worker) عملاً سه
|
||||
# برابرند؛ این دو بینِ همهی workerها مشترکاند و بدونِ Redis هم درست کار میکنند.
|
||||
# - روزانهی هر شماره: جلوی بمبارانِ پیامکیِ یک گوشی در طولِ روز.
|
||||
# - روزانهی کلِ سامانه: سقفِ خرجِ اعتبارِ کاوهنگار اگر کسی با شمارههای تصادفی
|
||||
# و IPهای زیاد پیامک بکشد (SMS pumping). رسیدن به آن ۵۰۳ و لاگِ ERROR میدهد؛
|
||||
# با رشدِ کاربرِ واقعی از .env بالا ببرید.
|
||||
OTP_REQUEST_PHONE_DAILY_MAX = int(os.environ.get('OTP_REQUEST_PHONE_DAILY_MAX', '10'))
|
||||
OTP_SMS_GLOBAL_DAILY_MAX = int(os.environ.get('OTP_SMS_GLOBAL_DAILY_MAX', '300'))
|
||||
# هر کدِ ورود بعد از این تعداد حدسِ غلط باطل میشود (شمارش در دیتابیس).
|
||||
# با کدِ ۶رقمی یعنی شانسِ حدس زدنِ هر کد ۵ در یک میلیون.
|
||||
OTP_MAX_FAILED_ATTEMPTS = 5
|
||||
@@ -617,6 +635,8 @@ DEV_MASTER_OTP = '0000' if DEBUG else None
|
||||
# را normalize نمیکند (accounts/serializers.py فقط CharField است)، پس
|
||||
# «09121111111» و «+989121111111» دو کاربرِ جدا هستند.
|
||||
def _parse_test_login_phones(raw: str) -> dict[str, str]:
|
||||
from accounts.phone import normalize_phone
|
||||
|
||||
pairs = {}
|
||||
for item in raw.split(','):
|
||||
item = item.strip()
|
||||
@@ -633,7 +653,14 @@ def _parse_test_login_phones(raw: str) -> dict[str, str]:
|
||||
'قالبِ درست «شماره:کد» است؛ شماره ۱۰ تا ۱۵ رقم (با + اختیاری) '
|
||||
'و کد ۴ تا ۶ رقم. مثال: TEST_LOGIN_PHONES=09120000001:834512'
|
||||
)
|
||||
pairs[phone] = code
|
||||
# همان نرمالسازیِ ورودیِ API (accounts/phone.py)، وگرنه شمارهای که
|
||||
# اینجا +98… نوشته شده با ورودیِ نرمالشدهی 09… هرگز جور نمیشد.
|
||||
normalized = normalize_phone(phone)
|
||||
if normalized is None:
|
||||
raise ImproperlyConfigured(
|
||||
f'TEST_LOGIN_PHONES شمارهی موبایلِ ایران نیست: «{item}». مثال: 09120000001:834512'
|
||||
)
|
||||
pairs[normalized] = code
|
||||
return pairs
|
||||
|
||||
|
||||
@@ -646,7 +673,11 @@ TEST_LOGIN_PHONES = _parse_test_login_phones(os.environ.get('TEST_LOGIN_PHONES',
|
||||
# بدون تنظیم این env، ارسال باید صراحتاً خطا بدهد، نه silently موفق باشد.
|
||||
KAVENEGAR_API_KEY = os.environ.get('KAVENEGAR_API_KEY', '')
|
||||
KAVENEGAR_SENDER = os.environ.get('KAVENEGAR_SENDER', '')
|
||||
OTP_SMS_TEMPLATE = os.environ.get('OTP_SMS_TEMPLATE', 'کد ورود شما به تدریسینو: {code}')
|
||||
# جملهی دوم هشدارِ مهندسیِ اجتماعی است (رایج در پیامکهای بانکی)؛ کلِ متن زیرِ
|
||||
# ۷۰ نویسه میماند تا یک صفحه پیامکِ فارسی حساب شود، نه دو صفحه.
|
||||
OTP_SMS_TEMPLATE = os.environ.get(
|
||||
'OTP_SMS_TEMPLATE', 'کد ورود شما به تدریسینو: {code}\nاین کد را به هیچکس ندهید.',
|
||||
)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# Content progress (NodeProgress status)
|
||||
|
||||
140
config/tests_audit_round2.py
Normal file
140
config/tests_audit_round2.py
Normal file
@@ -0,0 +1,140 @@
|
||||
"""
|
||||
بازبینیِ دومِ ۲۰۲۶-۰۹-۲۵: ایرادهایی که بازتولید و بسته شدند.
|
||||
|
||||
هر تست همان سناریویی را اجرا میکند که پیشتر خراب بود. ایرادهایی که عمداً
|
||||
باز ماندند (تصمیمِ محصولی یا خطرِ شکستنِ فرانت) در docs/security-before-production.md
|
||||
و کامنتِ همان کدها ثبتاند.
|
||||
"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from django.core.cache import cache
|
||||
from django.test import TestCase, override_settings
|
||||
from django.utils import timezone
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from accounts.authentication import issue_access_token
|
||||
from accounts.models import User
|
||||
from content.models import Choice, Grade, Lesson, Node, Question, Unit
|
||||
from discount.models import Offer
|
||||
from family.models import FamilyLink
|
||||
from payment.models import Order
|
||||
from payment.services import apply_order_payment_result
|
||||
from subscription.models import Plan, Subscription
|
||||
|
||||
|
||||
def _client(user):
|
||||
client = APIClient()
|
||||
client.credentials(HTTP_AUTHORIZATION=f'Bearer {issue_access_token(user.id)}')
|
||||
return client
|
||||
|
||||
|
||||
class _Base(TestCase):
|
||||
def setUp(self):
|
||||
cache.clear()
|
||||
self.user = User.objects.create(phone='09120008001', is_guest=False)
|
||||
self.client = _client(self.user)
|
||||
self.year = Plan.objects.create(title='سالانه', price=299000, duration_days=365)
|
||||
|
||||
def tearDown(self):
|
||||
cache.clear()
|
||||
|
||||
def buy(self, client=None):
|
||||
response = (client or self.client).post(
|
||||
'/api/subscription/purchase', {'planId': str(self.year.id)}, format='json')
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
return Order.objects.get(pk=response.json()['orderId'])
|
||||
|
||||
def pay(self, order, ref):
|
||||
apply_order_payment_result(order=order, gateway='zarinpal', gateway_ref_id=ref,
|
||||
new_status='paid', event='test')
|
||||
|
||||
|
||||
class OfferNeverShortensSubscription(_Base):
|
||||
def test_trial_code_after_a_paid_year_keeps_the_year(self):
|
||||
self.pay(self.buy(), ref='R1')
|
||||
before = Subscription.objects.get(user_id=self.user.id).expires_at
|
||||
Offer.objects.create(name='هفته رایگان', kind='trial', duration_days=7, code='WEEK')
|
||||
response = self.client.post('/api/discount/offers/redeem', {'code': 'WEEK'}, format='json')
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
self.assertEqual(Subscription.objects.get(user_id=self.user.id).expires_at, before)
|
||||
|
||||
@override_settings(DEV_MASTER_OTP='000000')
|
||||
def test_guest_who_paid_keeps_the_year_after_registering(self):
|
||||
Offer.objects.create(name='هفته رایگان', kind='trial', duration_days=7,
|
||||
auto_assign_on_signup=True)
|
||||
guest = User.objects.create(device_id='audit-2-device', is_guest=True)
|
||||
guest_client = _client(guest)
|
||||
self.pay(self.buy(guest_client), ref='R2')
|
||||
response = guest_client.post('/api/auth/login', {'phone': '09125550001', 'otp': '000000'},
|
||||
format='json')
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
days = (Subscription.objects.get(user_id=guest.id).expires_at - timezone.now()).days
|
||||
self.assertGreater(days, 360)
|
||||
|
||||
def test_trial_still_works_for_a_user_without_subscription(self):
|
||||
Offer.objects.create(name='هفته رایگان', kind='trial', duration_days=7, code='WEEK')
|
||||
self.client.post('/api/discount/offers/redeem', {'code': 'WEEK'}, format='json')
|
||||
sub = Subscription.objects.get(user_id=self.user.id)
|
||||
self.assertEqual(sub.status, 'active')
|
||||
self.assertIn((sub.expires_at - timezone.now()).days, (6, 7))
|
||||
|
||||
def test_free_full_still_upgrades_a_paid_year_to_unlimited(self):
|
||||
self.pay(self.buy(), ref='R3')
|
||||
Offer.objects.create(name='رایگانِ کامل', kind='free_full', code='FULL')
|
||||
self.client.post('/api/discount/offers/redeem', {'code': 'FULL'}, format='json')
|
||||
self.assertIsNone(Subscription.objects.get(user_id=self.user.id).expires_at)
|
||||
|
||||
|
||||
@override_settings(ZARINPAL_MERCHANT_ID='x' * 36, ZARINPAL_REDIRECT_URL='https://app.example/')
|
||||
class ZarinpalErrorBodyReturnsToApp(_Base):
|
||||
def test_documented_error_body_redirects_instead_of_500(self):
|
||||
order = self.buy()
|
||||
Order.objects.filter(pk=order.pk).update(gateway_authority='A' * 36)
|
||||
fake = MagicMock(status_code=200)
|
||||
fake.json.return_value = {'data': [], 'errors': {'code': -51, 'message': 'failed'}}
|
||||
with patch('payment.zarinpal.requests.post', return_value=fake):
|
||||
response = APIClient().get('/api/payment/zarinpal/callback',
|
||||
{'Authority': 'A' * 36, 'Status': 'OK'})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertIn('status=failed', response['Location'])
|
||||
|
||||
|
||||
class WeeklyReportCountsIslands(TestCase):
|
||||
def test_island_quiz_xp_reaches_the_parent(self):
|
||||
cache.clear()
|
||||
grade = Grade.objects.create(title='پایه نهم', icon='', color='')
|
||||
node = Node.objects.create(unit=Unit.objects.create(grade=grade, title='فصل', order=1),
|
||||
title='جزیره', order=1)
|
||||
child = User.objects.create(phone='09120008002', grade_id=grade.id)
|
||||
child_client = _client(child)
|
||||
for i in range(4):
|
||||
question = Question.objects.create(
|
||||
lesson=Lesson.objects.create(node=node, title=f'درس {i}'),
|
||||
type='multiple_choice', prompt=f'سوال {i}')
|
||||
right = Choice.objects.create(question=question, value='الف', is_correct=True)
|
||||
Choice.objects.create(question=question, value='ب', is_correct=False)
|
||||
child_client.post(f'/api/questions/{question.id}/answer', {'selectedOptionId': right.id},
|
||||
format='json')
|
||||
child_client.post(f'/api/nodes/{node.id}/quiz/complete',
|
||||
{'correctCount': 4, 'totalQuestions': 4}, format='json')
|
||||
|
||||
parent = User.objects.create(phone='09120008003')
|
||||
FamilyLink.objects.create(parent_user_id=parent.id, child_user_id=child.id,
|
||||
child_phone=child.phone, invite_code='654321',
|
||||
status='accepted', accepted_at=timezone.now())
|
||||
report = _client(parent).get('/api/family/weekly-report').json()
|
||||
self.assertEqual(report['xpEarned'], 40)
|
||||
self.assertEqual(report['islandsCompleted'], 1)
|
||||
self.assertEqual(report['lessonsCompleted'], 0)
|
||||
|
||||
|
||||
class AskWithNonNumericQuestionId(TestCase):
|
||||
def test_answer_is_saved_not_500(self):
|
||||
cache.clear()
|
||||
user = User.objects.create(phone='09120008004')
|
||||
response = _client(user).post('/api/ai/ask',
|
||||
{'userQuestion': 'کسر چیست؟', 'questionId': 'q-12'},
|
||||
format='json')
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
from ai_tutor.models import Message
|
||||
self.assertIsNone(Message.objects.get(pk=response.json()['messageId']).question_id)
|
||||
Reference in New Issue
Block a user