File size: 15,358 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6437539
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""G1 entitlement, G2 receipts and G3 webhooks, with fake store clients."""

import base64
import json
import uuid
from datetime import UTC, datetime, timedelta

import pytest
from sqlalchemy import select

from app.core.config import get_settings
from app.core.database import get_session_factory
from app.integrations.app_store import AppleNotification, AppleTransaction, InvalidSignedData, get_app_store
from app.integrations.play_store import (
    InvalidPurchase,
    InvalidPushToken,
    PlayLineItem,
    PlaySubscription,
    get_play_store,
    get_pubsub_verifier,
)
from app.modules.billing.models import Subscription
from tests import factories
from tests.helpers import bearer

NOW = datetime.now(UTC)
LATER, MUCH_LATER, EARLIER = NOW + timedelta(days=30), NOW + timedelta(days=60), NOW - timedelta(days=1)
PACKAGE = "com.example.app"
OIDC = "good-oidc-token"


class FakeAppStore:
    def __init__(self):
        self.transactions: dict[str, AppleTransaction] = {}
        self.notifications: dict[str, AppleNotification] = {}

    def verify_signed_transaction(self, signed_transaction: str) -> AppleTransaction:
        if signed_transaction not in self.transactions:
            raise InvalidSignedData("unknown")
        return self.transactions[signed_transaction]

    def decode_notification(self, signed_payload: str) -> AppleNotification:
        if signed_payload not in self.notifications:
            raise InvalidSignedData("unknown")
        return self.notifications[signed_payload]


class FakePlayStore:
    def __init__(self):
        self.subscriptions: dict[str, PlaySubscription] = {}
        self.acknowledged: list[str] = []

    async def get_subscription(self, purchase_token: str) -> PlaySubscription:
        if purchase_token not in self.subscriptions:
            raise InvalidPurchase("unknown")
        return self.subscriptions[purchase_token]

    async def acknowledge(self, product_id: str, purchase_token: str) -> None:
        self.acknowledged.append(purchase_token)


class FakePubSub:
    async def verify(self, token: str) -> None:
        if token != OIDC:
            raise InvalidPushToken("bad")


@pytest.fixture
def stores(app, monkeypatch):
    apple, play = FakeAppStore(), FakePlayStore()
    app.dependency_overrides.update({get_app_store: lambda: apple, get_play_store: lambda: play,
                                     get_pubsub_verifier: FakePubSub})
    monkeypatch.setattr(get_settings(), "google_package_name", PACKAGE)
    yield apple, play
    for dep in (get_app_store, get_play_store, get_pubsub_verifier):
        app.dependency_overrides.pop(dep, None)


async def _account() -> tuple[uuid.UUID, dict[str, str]]:
    account = await factories.make_account()
    return account["id"], account["headers"]


async def _insert(account_id, *, otid="1000", status="active", expires=LATER, platform="ios") -> None:
    async with get_session_factory()() as db:
        db.add(Subscription(account_id=account_id, platform=platform, product_id="pro_monthly",
                            original_transaction_id=otid, status=status, expires_at=expires))
        await db.commit()


async def _rows() -> list[Subscription]:
    async with get_session_factory()() as db:
        return list((await db.execute(select(Subscription).order_by(Subscription.original_transaction_id))).scalars())


def _ios(token="jws-1", **extra) -> dict:
    return {"platform": "ios", "product_id": "pro_monthly", "signed_transaction": token, **extra}


def _android(token="play-token-1") -> dict:
    return {"platform": "android", "product_id": "pro_monthly", "purchase_token": token}


def _play(state="ACTIVE", expires=LATER, order="GPA.1111-2222..0", linked=None, ack=False) -> PlaySubscription:
    return PlaySubscription(state, (PlayLineItem("pro_monthly", expires),), order, linked, ack)


def _pubsub(notification: dict) -> dict:
    data = base64.b64encode(json.dumps({"packageName": PACKAGE, **notification}).encode()).decode()
    return {"message": {"data": data, "messageId": "1", "attributes": {}}, "subscription": "projects/p/subs/s"}


# G1

async def test_entitlement_free_then_pro(client):
    account_id, headers = await _account()
    response = await client.get("/v1/me/entitlement", headers=headers)
    assert response.status_code == 200
    assert response.json() == {"plan": "free", "weekly_limit": 20, "used_this_week": 0, "left": 20, "window_days": 7}

    await _insert(account_id, otid="old", status="active", expires=EARLIER)
    assert (await client.get("/v1/me/entitlement", headers=headers)).json()["plan"] == "free"

    await _insert(account_id, otid="current")
    body = (await client.get("/v1/me/entitlement", headers=headers)).json()
    assert body == {"plan": "pro", "weekly_limit": None, "used_this_week": 0, "left": None, "window_days": 7}


async def test_billing_endpoints_require_bearer(client, stores):
    assert (await client.get("/v1/me/entitlement")).json()["error"]["code"] == "UNAUTHENTICATED"
    response = await client.post("/v1/billing/receipts", json=_ios())
    assert response.status_code == 401
    assert (await client.get("/v1/me/entitlement", headers=bearer("nope"))).status_code == 401


# G2

async def test_ios_receipt_makes_account_pro_and_is_idempotent(client, stores):
    apple, _ = stores
    account_id, headers = await _account()
    apple.transactions["jws-1"] = AppleTransaction("1000", "pro_monthly", LATER, None)

    for _ in range(2):
        response = await client.post("/v1/billing/receipts", json=_ios(), headers=headers)
        assert response.status_code == 200, response.text
        assert response.json()["entitlement"]["plan"] == "pro"
    [row] = await _rows()
    assert (row.account_id, row.platform, row.original_transaction_id, row.status) == (account_id, "ios", "1000",
                                                                                       "active")


async def test_ios_receipt_for_expired_subscription_stays_free(client, stores):
    apple, _ = stores
    _, headers = await _account()
    apple.transactions["jws-1"] = AppleTransaction("1000", "pro_monthly", EARLIER, None)
    response = await client.post("/v1/billing/receipts", json=_ios(), headers=headers)
    assert response.json()["entitlement"]["plan"] == "free"
    assert (await _rows())[0].status == "expired"


async def test_android_receipt_makes_account_pro_and_acknowledges(client, stores):
    _, play = stores
    account_id, headers = await _account()
    play.subscriptions["play-token-1"] = _play()
    response = await client.post("/v1/billing/receipts", json=_android(), headers=headers)
    assert response.status_code == 200, response.text
    assert response.json()["entitlement"]["plan"] == "pro"
    [row] = await _rows()
    assert (row.platform, row.original_transaction_id, row.status) == ("android", "GPA.1111-2222", "active")
    assert play.acknowledged == ["play-token-1"]

    # A renewal changes the order suffix but not the row.
    play.subscriptions["play-token-1"] = _play(expires=MUCH_LATER, order="GPA.1111-2222..1", ack=True)
    assert (await client.post("/v1/billing/receipts", json=_android(), headers=headers)).status_code == 200
    [row] = await _rows()
    assert row.expires_at == MUCH_LATER


async def test_receipt_with_unknown_product_is_400(client, stores):
    _, headers = await _account()
    response = await client.post("/v1/billing/receipts", json=_ios(product_id="pro_lifetime"), headers=headers)
    assert response.status_code == 400
    assert response.json()["error"]["fields"] == {"product_id": "Unknown product."}


async def test_receipt_missing_platform_field_is_400(client, stores):
    _, headers = await _account()
    body = {"platform": "android", "product_id": "pro_monthly", "signed_transaction": "jws-1"}
    response = await client.post("/v1/billing/receipts", json=body, headers=headers)
    assert response.status_code == 400
    assert "purchase_token" in response.json()["error"]["fields"]


async def test_receipt_that_does_not_verify_is_422(client, stores):
    apple, play = stores
    _, headers = await _account()
    for body in (_ios("forged"), _android("unknown-token")):
        response = await client.post("/v1/billing/receipts", json=body, headers=headers)
        assert response.status_code == 422
        assert response.json()["error"]["code"] == "RECEIPT_INVALID"

    apple.transactions["jws-other"] = AppleTransaction("1000", "pro_yearly", LATER, None)
    response = await client.post("/v1/billing/receipts", json=_ios("jws-other"), headers=headers)
    assert response.json()["error"]["code"] == "RECEIPT_INVALID"

    play.subscriptions["pending"] = _play(state="PENDING")
    response = await client.post("/v1/billing/receipts", json=_android("pending"), headers=headers)
    assert response.json()["error"]["code"] == "RECEIPT_INVALID"
    assert await _rows() == []


async def test_receipt_linked_to_another_account_is_409(client, stores):
    apple, _ = stores
    owner_id, _ = await _account()
    await _insert(owner_id, otid="1000")
    _, headers = await _account()
    apple.transactions["jws-1"] = AppleTransaction("1000", "pro_monthly", LATER, None)
    response = await client.post("/v1/billing/receipts", json=_ios(), headers=headers)
    assert response.status_code == 409
    assert response.json()["error"]["code"] == "RECEIPT_IN_USE"
    assert (await _rows())[0].account_id == owner_id


# G3 apple

async def _apple_event(client, apple, kind, tx, subtype=None) -> int:
    apple.notifications["signed"] = AppleNotification(kind, subtype, tx, None)
    response = await client.post("/v1/billing/webhooks/apple", json={"signedPayload": "signed"})
    return response.status_code


async def test_apple_renew_refund_and_expiry(client, stores):
    apple, _ = stores
    account_id, headers = await _account()
    await _insert(account_id, otid="1000", expires=LATER)

    renewed = AppleTransaction("1000", "pro_monthly", MUCH_LATER, None)
    assert await _apple_event(client, apple, "DID_RENEW", renewed) == 200
    [row] = await _rows()
    assert (row.status, row.expires_at) == ("active", MUCH_LATER)

    # A stale event for the previous period is ignored.
    assert await _apple_event(client, apple, "EXPIRED", AppleTransaction("1000", "pro_monthly", LATER, None)) == 200
    assert (await _rows())[0].status == "active"

    assert await _apple_event(client, apple, "REFUND", AppleTransaction("1000", "pro_monthly", MUCH_LATER, NOW)) == 200
    assert (await _rows())[0].status == "refunded"
    assert (await client.get("/v1/me/entitlement", headers=headers)).json()["plan"] == "free"


async def test_apple_expired(client, stores):
    apple, _ = stores
    account_id, headers = await _account()
    await _insert(account_id, otid="1000", expires=LATER)
    tx = AppleTransaction("1000", "pro_monthly", LATER, None)
    assert await _apple_event(client, apple, "EXPIRED", tx, "VOLUNTARY") == 200
    assert (await _rows())[0].status == "expired"
    assert (await client.get("/v1/me/entitlement", headers=headers)).json()["plan"] == "free"


async def test_apple_unknown_transaction_is_ignored(client, stores):
    apple, _ = stores
    assert await _apple_event(client, apple, "DID_RENEW", AppleTransaction("999", "pro_monthly", LATER, None)) == 200
    response = await client.post("/v1/billing/webhooks/apple", json={"signedPayload": "signed"})
    assert response.json() == {}
    assert await _rows() == []


async def test_apple_bad_signature_is_401(client, stores):
    response = await client.post("/v1/billing/webhooks/apple", json={"signedPayload": "forged"})
    assert response.status_code == 401
    assert response.json()["error"]["code"] == "UNAUTHENTICATED"


async def test_unknown_provider_is_404(client, stores):
    response = await client.post("/v1/billing/webhooks/stripe", json={})
    assert response.status_code == 404


# G3 google

async def test_google_push_updates_subscription(client, stores):
    _, play = stores
    account_id, headers = await _account()
    await _insert(account_id, otid="GPA.1111-2222", platform="android", expires=LATER)
    play.subscriptions["play-token-1"] = _play(state="EXPIRED", expires=LATER, order="GPA.1111-2222..0", ack=True)

    body = _pubsub({"subscriptionNotification": {"notificationType": 13, "purchaseToken": "play-token-1"}})
    response = await client.post("/v1/billing/webhooks/google", json=body, headers=bearer(OIDC))
    assert response.status_code == 200
    assert response.json() == {}
    assert (await _rows())[0].status == "expired"
    assert (await client.get("/v1/me/entitlement", headers=headers)).json()["plan"] == "free"


async def test_google_cancel_keeps_pro_and_revoke_refunds(client, stores):
    _, play = stores
    account_id, headers = await _account()
    await _insert(account_id, otid="GPA.1111-2222", platform="android", expires=LATER)
    play.subscriptions["play-token-1"] = _play(state="CANCELED", expires=LATER, ack=True)

    body = _pubsub({"subscriptionNotification": {"notificationType": 3, "purchaseToken": "play-token-1"}})
    assert (await client.post("/v1/billing/webhooks/google", json=body, headers=bearer(OIDC))).status_code == 200
    assert (await _rows())[0].status == "active"
    assert (await client.get("/v1/me/entitlement", headers=headers)).json()["plan"] == "pro"

    body = _pubsub({"subscriptionNotification": {"notificationType": 12, "purchaseToken": "play-token-1"}})
    assert (await client.post("/v1/billing/webhooks/google", json=body, headers=bearer(OIDC))).status_code == 200
    assert (await _rows())[0].status == "refunded"


async def test_google_new_linked_token_follows_the_old_owner(client, stores):
    _, play = stores
    account_id, headers = await _account()
    await _insert(account_id, otid="GPA.1111-2222", platform="android", expires=EARLIER, status="expired")
    play.subscriptions["old-token"] = _play(state="EXPIRED", expires=EARLIER, ack=True)
    play.subscriptions["new-token"] = _play(order="GPA.3333-4444", linked="old-token", ack=True)

    body = _pubsub({"subscriptionNotification": {"notificationType": 4, "purchaseToken": "new-token"}})
    assert (await client.post("/v1/billing/webhooks/google", json=body, headers=bearer(OIDC))).status_code == 200
    rows = await _rows()
    assert [(r.original_transaction_id, r.account_id, r.status) for r in rows] == [
        ("GPA.1111-2222", account_id, "expired"), ("GPA.3333-4444", account_id, "active")]


async def test_google_unknown_token_and_test_notification_are_ignored(client, stores):
    for note in ({"testNotification": {"version": "1.0"}},
                 {"subscriptionNotification": {"notificationType": 2, "purchaseToken": "unknown"}}):
        response = await client.post("/v1/billing/webhooks/google", json=_pubsub(note), headers=bearer(OIDC))
        assert response.status_code == 200
    assert await _rows() == []


@pytest.mark.parametrize("headers", [{}, bearer("forged-oidc")])
async def test_google_push_without_valid_oidc_is_401(client, stores, headers):
    body = _pubsub({"subscriptionNotification": {"notificationType": 2, "purchaseToken": "play-token-1"}})
    response = await client.post("/v1/billing/webhooks/google", json=body, headers=headers)
    assert response.status_code == 401
    assert response.json()["error"]["code"] == "UNAUTHENTICATED"