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
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
"""
Sahih Islam - Subscription Security & Anti-Modding Test Suite
============================================================
14 Comprehensive Security Scenarios verifying:
1.  Server-authoritative Pro entitlement gating
2.  Tampered/spoofed client payload resistance
3.  Time-based subscription expiry enforcement
4.  Instant revocation on Google Play refunds
5.  Active subscriber access authorization
6.  Google Play In-App Purchase token verification
7.  Rejection of malformed/invalid Google Play purchase tokens
8.  Anti-Replay protection across multiple user accounts
9.  Idempotent purchase verification for the same user
10. RTDN Webhook renewal lifecycle updates in MongoDB
11. RTDN Webhook revocation/refund updates in MongoDB
12. IDOR access control protection (enforce_self_or_admin)
13. Prevention of unverified direct subscription activation
14. Production prohibition of mock/sandbox tokens
"""

import os
import sys
import hashlib
import asyncio
from datetime import datetime, timedelta
from unittest.mock import AsyncMock, patch, MagicMock
import pytest
from fastapi import HTTPException, status, Request

# Ensure backend root on sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from app.auth_deps import is_user_pro, require_pro, require_entitlement, enforce_self_or_admin
from app.rag_config import resolve_user_tier
from app.services.google_play_service import GooglePlayService, google_play_service
from app.core.config import settings
from app.models import SubscriptionCreate


def run_async(coro):
    """Executes asynchronous coroutine synchronously for pytest."""
    return asyncio.run(coro)


# ============================================================================
# 1. Server Authority & Tier Resolution Tests (Scenarios 1 - 5)
# ============================================================================

def test_free_user_pro_endpoint_denial():
    """Scenario 1: Free user attempting to access a Pro-protected endpoint receives 403 Forbidden."""
    async def _test():
        free_user = {"uid": "user_free_1", "role": "USER", "is_pro": False}
        assert await is_user_pro(free_user) is False

        with pytest.raises(HTTPException) as exc_info:
            await require_pro(current_user=free_user)
        assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
        assert "Pro subscription required" in exc_info.value.detail

        checker = require_entitlement("ai_deepseek_v3")
        with pytest.raises(HTTPException) as exc_info2:
            await checker(current_user=free_user)
        assert exc_info2.value.status_code == status.HTTP_403_FORBIDDEN
        assert "ai_deepseek_v3" in exc_info2.value.detail

    run_async(_test())


def test_client_spoofed_is_pro_ignored():
    """Scenario 2: Client passes spoofed 'is_pro': True in request, but DB record has is_pro: False."""
    async def _test():
        db_user_record = {
            "uid": "user_spoof_attacker",
            "role": "USER",
            "is_pro": False,
            "subscription": {"is_pro": False, "tier": "FREE", "status": "FREE"}
        }
        # Attacker's request body may claim whatever, but the authoritative user dict is evaluated
        assert await is_user_pro(db_user_record) is False
        assert resolve_user_tier(db_user_record) == "free"

    run_async(_test())


def test_expired_subscription_downgrade():
    """Scenario 3: User with is_pro=True whose expires_at is in the past is downgraded to free."""
    async def _test():
        past_expiry = datetime.utcnow() - timedelta(days=3)
        expired_user = {
            "uid": "user_expired_sub",
            "role": "USER",
            "is_pro": True,  # Stale flag left in DB
            "subscription": {
                "is_pro": True,
                "tier": "PRO",
                "status": "ACTIVE",
                "expires_at": past_expiry
            }
        }
        assert await is_user_pro(expired_user) is False
        assert resolve_user_tier(expired_user) == "free"

        with pytest.raises(HTTPException) as exc_info:
            await require_pro(current_user=expired_user)
        assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN

    run_async(_test())


def test_revoked_or_refunded_subscription():
    """Scenario 4: User with status=REFUNDED or REVOKED has Pro access revoked immediately."""
    async def _test():
        future_date = datetime.utcnow() + timedelta(days=20)
        refunded_user = {
            "uid": "user_refunded_1",
            "role": "USER",
            "is_pro": True,
            "subscription": {
                "is_pro": True,
                "tier": "PRO",
                "status": "REFUNDED",
                "expires_at": future_date
            }
        }
        assert await is_user_pro(refunded_user) is False
        assert resolve_user_tier(refunded_user) == "free"

        revoked_user = {
            "uid": "user_revoked_1",
            "role": "USER",
            "subscription": {
                "is_pro": True,
                "tier": "PRO",
                "status": "REVOKED",
                "expires_at": future_date
            }
        }
        assert await is_user_pro(revoked_user) is False
        assert resolve_user_tier(revoked_user) == "free"

    run_async(_test())


def test_valid_subscription_allows_access():
    """Scenario 5: Active subscriber with future expires_at passes require_pro and receives 'pro' tier."""
    async def _test():
        future_date = datetime.utcnow() + timedelta(days=25)
        valid_pro_user = {
            "uid": "user_valid_pro",
            "role": "USER",
            "is_pro": True,
            "subscription": {
                "is_pro": True,
                "tier": "PRO",
                "status": "ACTIVE",
                "expires_at": future_date
            }
        }
        assert await is_user_pro(valid_pro_user) is True
        assert resolve_user_tier(valid_pro_user) == "pro"

        # require_pro returns the user without raising
        result = await require_pro(current_user=valid_pro_user)
        assert result["uid"] == "user_valid_pro"

    run_async(_test())


# ============================================================================
# 2. Google Play Developer API Verification & Anti-Replay (Scenarios 6 - 9)
# ============================================================================

def test_google_play_purchase_verification_success():
    """Scenario 6: Valid Google Play purchase token verifies and activates subscription."""
    async def _test():
        from app.payment_routes import verify_google_play_purchase

        mock_user = {"uid": "user_gp_buyer_1"}
        token = "test_token_valid_purchase_1001"
        payload = {
            "purchase_token": token,
            "product_id": "sahih_pro_monthly",
            "package_name": "com.sahihislam.app",
            "purpose": "subscription",
            "amount": 199.0,
        }

        mock_gp_result = {
            "valid": True,
            "is_active": True,
            "product_id": "sahih_pro_monthly",
            "order_id": "GPA.test_order_123",
            "acknowledgement_state": 1,
        }
        with patch("app.payment_routes.subscriptions_collection.find_one", new_callable=AsyncMock) as mock_find_sub, \
             patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock, return_value=None), \
             patch("app.payment_routes.google_play_service.verify_purchase", new_callable=AsyncMock, return_value=mock_gp_result), \
             patch("app.payment_routes.execute_payment_fulfillment", new_callable=AsyncMock) as mock_fulfill, \
             patch("app.payment_routes.invalidate_user_cache", new_callable=AsyncMock):

            mock_find_sub.return_value = None  # Token not yet claimed
            mock_fulfill.return_value = {"is_pro": True, "tier": "PRO"}

            response = await verify_google_play_purchase(payload=payload, current_user=mock_user)
            assert response["success"] is True
            assert response["product_id"] == "sahih_pro_monthly"
            assert mock_fulfill.called
            call_kwargs = mock_fulfill.call_args[1]
            assert call_kwargs["metadata"]["purchase_token"] == token

    run_async(_test())


def test_google_play_purchase_verification_invalid_token():
    """Scenario 7: Malformed or fraudulent Google Play purchase token is rejected with 400."""
    async def _test():
        from app.payment_routes import verify_google_play_purchase

        mock_user = {"uid": "user_gp_fraud_1"}
        payload = {
            "purchase_token": "mock_invalid_fraud_token_xyz",
            "product_id": "sahih_pro_monthly",
            "package_name": "com.sahihislam.app",
            "purpose": "subscription",
        }

        with patch("app.payment_routes.subscriptions_collection.find_one", new_callable=AsyncMock) as mock_find_sub, \
             patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock, return_value=None):
            mock_find_sub.return_value = None

            with pytest.raises(HTTPException) as exc_info:
                await verify_google_play_purchase(payload=payload, current_user=mock_user)
            assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST
            assert "Invalid" in exc_info.value.detail or "inactive" in exc_info.value.detail

    run_async(_test())


def test_anti_replay_token_reuse_different_user():
    """Scenario 8: Token already claimed by User A is submitted by User B -> 409 Conflict."""
    async def _test():
        from app.payment_routes import verify_google_play_purchase

        token = "test_token_already_claimed_by_alice"
        existing_claim = {
            "purchase_token": token,
            "user_id": "user_alice",
            "plan_id": "sahih_pro_monthly",
            "renews_at": datetime.utcnow() + timedelta(days=20),
        }

        attacker_user = {"uid": "user_bob_attacker"}
        payload = {
            "purchase_token": token,
            "product_id": "sahih_pro_monthly",
            "package_name": "com.sahihislam.app",
            "purpose": "subscription",
        }

        with patch("app.payment_routes.subscriptions_collection.find_one", new_callable=AsyncMock) as mock_find_sub:
            mock_find_sub.return_value = existing_claim

            with pytest.raises(HTTPException) as exc_info:
                await verify_google_play_purchase(payload=payload, current_user=attacker_user)
            assert exc_info.value.status_code == status.HTTP_409_CONFLICT
            assert "already been claimed by another account" in exc_info.value.detail

    run_async(_test())


def test_idempotent_token_submission_same_user():
    """Scenario 9: Same user re-submitting an already verified token receives idempotent 200 OK without duplicate billing."""
    async def _test():
        from app.payment_routes import verify_google_play_purchase

        token = "test_token_same_user_repeat"
        user_alice = {"uid": "user_alice"}
        expiry = datetime.utcnow() + timedelta(days=20)
        existing_claim = {
            "purchase_token": token,
            "user_id": "user_alice",
            "transaction_id": "GPA.PREVIOUS_TXN_001",
            "plan_id": "sahih_pro_monthly",
            "renews_at": expiry,
        }

        payload = {
            "purchase_token": token,
            "product_id": "sahih_pro_monthly",
            "package_name": "com.sahihislam.app",
            "purpose": "subscription",
        }

        with patch("app.payment_routes.subscriptions_collection.find_one", new_callable=AsyncMock) as mock_find_sub, \
             patch("app.payment_routes.execute_payment_fulfillment", new_callable=AsyncMock) as mock_fulfill:

            mock_find_sub.return_value = existing_claim

            res = await verify_google_play_purchase(payload=payload, current_user=user_alice)
            assert res["success"] is True
            assert res["status"] == "already_verified"
            assert res["order_id"] == "GPA.PREVIOUS_TXN_001"
            assert not mock_fulfill.called

    run_async(_test())


# ============================================================================
# 3. Google RTDN Webhook Tests (Scenarios 10 - 11)
# ============================================================================

def test_rtdn_renewal_webhook_updates_user():
    """Scenario 10: RTDN notificationType=2 (SUBSCRIPTION_RENEWED) updates subscription and user expiry in MongoDB."""
    async def _test():
        from app.payment_routes import google_play_rtdn_webhook

        token = "test_rtdn_renew_token_55"
        sub_record = {
            "purchase_token": token,
            "user_id": "user_subscriber_99",
            "plan_id": "sahih_pro_monthly",
            "status": "active"
        }

        mock_request = AsyncMock(spec=Request)
        mock_request.json = AsyncMock(return_value={
            "subscriptionNotification": {
                "notificationType": 2,  # RENEWED
                "purchaseToken": token,
                "subscriptionId": "sahih_pro_monthly",
            }
        })

        with patch("app.payment_routes.subscriptions_collection.find_one", new_callable=AsyncMock) as mock_find_sub, \
             patch("app.payment_routes.subscriptions_collection.update_one", new_callable=AsyncMock) as mock_sub_update, \
             patch("app.payment_routes.users_collection.update_one", new_callable=AsyncMock) as mock_user_update, \
             patch("app.payment_routes.transactions_collection.find_one", new_callable=AsyncMock, return_value=None), \
             patch("app.payment_routes.transactions_collection.insert_one", new_callable=AsyncMock), \
             patch("app.payment_routes.audit_logs_collection.find_one", new_callable=AsyncMock, return_value=None), \
             patch("app.payment_routes.audit_logs_collection.insert_one", new_callable=AsyncMock), \
             patch("app.payment_routes.invalidate_user_cache", new_callable=AsyncMock) as mock_invalidate:

            mock_find_sub.return_value = sub_record

            res = await google_play_rtdn_webhook(request=mock_request)
            assert res["status"] == "acknowledged"

            assert mock_sub_update.called
            sub_update_call = mock_sub_update.call_args[0]
            token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
            assert sub_update_call[0] in ({"purchase_token": token}, {"$or": [{"purchase_token_hash": token_hash}, {"purchase_token": token}]})
            assert sub_update_call[1]["$set"]["status"] == "active"

            assert mock_user_update.called
            user_update_call = mock_user_update.call_args[0]
            assert user_update_call[0] == {"uid": "user_subscriber_99"}
            assert user_update_call[1]["$set"]["is_pro"] is True
            assert user_update_call[1]["$set"]["subscription.status"] == "ACTIVE"

            mock_invalidate.assert_called_with("user_subscriber_99")

    run_async(_test())


def test_rtdn_refund_webhook_revokes_pro():
    """Scenario 11: RTDN notificationType=12 (SUBSCRIPTION_REVOKED) immediately strips Pro in user record."""
    async def _test():
        from app.payment_routes import google_play_rtdn_webhook

        token = "test_rtdn_refund_token_77"
        sub_record = {
            "purchase_token": token,
            "user_id": "user_refund_target",
            "plan_id": "sahih_pro_monthly",
            "status": "active"
        }

        mock_request = AsyncMock(spec=Request)
        mock_request.json = AsyncMock(return_value={
            "subscriptionNotification": {
                "notificationType": 12,  # REVOKED / REFUND
                "purchaseToken": token,
                "subscriptionId": "sahih_pro_monthly",
            }
        })

        with patch("app.payment_routes.subscriptions_collection.find_one", new_callable=AsyncMock) as mock_find_sub, \
             patch("app.payment_routes.subscriptions_collection.update_one", new_callable=AsyncMock) as mock_sub_update, \
             patch("app.payment_routes.users_collection.update_one", new_callable=AsyncMock) as mock_user_update, \
             patch("app.payment_routes.transactions_collection.insert_one", new_callable=AsyncMock), \
             patch("app.payment_routes.invalidate_user_cache", new_callable=AsyncMock) as mock_invalidate:

            mock_find_sub.return_value = sub_record

            res = await google_play_rtdn_webhook(request=mock_request)
            assert res["status"] == "acknowledged"

            assert mock_sub_update.called
            assert mock_sub_update.call_args[0][1]["$set"]["status"] in ("refunded", "revoked")

            assert mock_user_update.called
            user_update_doc = mock_user_update.call_args[0][1]["$set"]
            assert user_update_doc["is_pro"] is False
            assert user_update_doc["subscription.is_pro"] is False
            assert user_update_doc["subscription.status"] == "REVOKED"

            mock_invalidate.assert_called_with("user_refund_target")

    run_async(_test())


# ============================================================================
# 4. Access Control, IDOR & Production Isolation (Scenarios 12 - 14)
# ============================================================================

def test_idor_protection_enforce_self_or_admin():
    """Scenario 12: enforce_self_or_admin prevents User A from acting on User B's resource."""
    user_a = {"uid": "user_alpha", "role": "USER"}
    user_b_uid = "user_beta"
    admin_user = {"uid": "superadmin_1", "role": "ADMIN"}

    # User A acting on own resource -> OK
    enforce_self_or_admin(user_a, target_uid="user_alpha")

    # User A acting on User B -> 403 Forbidden
    with pytest.raises(HTTPException) as exc_info:
        enforce_self_or_admin(user_a, target_uid=user_b_uid)
    assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
    assert "Cannot act on another user's resource" in exc_info.value.detail

    # Admin acting on User B -> OK
    enforce_self_or_admin(admin_user, target_uid=user_b_uid)


def test_direct_subscribe_endpoint_locked():
    """Scenario 13: Direct unverified subscription payload is rejected with 400 Bad Request."""
    async def _test():
        from app.payment_routes import subscribe_user

        mock_user = {"uid": "user_direct_cheat"}
        payload = SubscriptionCreate(
            plan_id="sahih_pro_annual",
            billing_cycle="annual",
            payment_method="direct_cheat_bypass",
            amount_paid=0.0,
        )

        with pytest.raises(HTTPException) as exc_info:
            await subscribe_user(payload=payload, current_user=mock_user)
        assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST
        assert "Direct unverified subscription activation is disabled" in exc_info.value.detail

    run_async(_test())


def test_production_mock_token_forbidden():
    """Scenario 14: In production mode (settings.IS_PROD=True), mock purchase tokens are rejected with 403."""
    async def _test():
        gps = GooglePlayService()

        with patch.object(settings, "IS_PROD", True), \
             patch.dict(os.environ, {"TEST_MODE": "0", "ALLOW_MOCK_GOOGLE_PLAY": "0"}):

            with pytest.raises(HTTPException) as exc_info:
                await gps.verify_purchase(
                    package_name="com.sahihislam.app",
                    product_id="sahih_pro_monthly",
                    purchase_token="mock_cheat_token_123",
                    is_subscription=True
                )
            assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
            assert "Mock purchase tokens are strictly forbidden in production" in exc_info.value.detail

    run_async(_test())