|
| 1 | +# Copyright 2025 ByBren, LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Tests for the Stripe webhook handler (REN-79). |
| 16 | +
|
| 17 | +Verifies credit allocation wiring between the Stripe checkout.session.completed |
| 18 | +event and the credit ledger service. All tests mock |
| 19 | +``stripe.Webhook.construct_event`` since real Stripe signatures cannot be |
| 20 | +generated in tests. |
| 21 | +""" |
| 22 | + |
| 23 | +from __future__ import annotations |
| 24 | + |
| 25 | +from decimal import Decimal |
| 26 | +from typing import TYPE_CHECKING |
| 27 | +from unittest.mock import patch |
| 28 | + |
| 29 | +import pytest |
| 30 | +import stripe |
| 31 | + |
| 32 | +from core.models.base import CreditLedgerEntry, TransactionDirection, TransactionSource |
| 33 | + |
| 34 | +if TYPE_CHECKING: |
| 35 | + from httpx import AsyncClient |
| 36 | + from sqlalchemy.ext.asyncio import AsyncSession |
| 37 | + |
| 38 | + from core.models.base import User |
| 39 | + |
| 40 | +WEBHOOK_URL = "/api/v1/webhooks/stripe" |
| 41 | + |
| 42 | + |
| 43 | +def _checkout_event( |
| 44 | + *, |
| 45 | + event_id: str = "evt_test_123", |
| 46 | + session_id: str = "cs_test_abc", |
| 47 | + client_reference_id: str | None = "00000000-0000-0000-0000-000000000001", |
| 48 | + sku: str | None = "cred10", |
| 49 | +) -> dict: |
| 50 | + """Build a minimal checkout.session.completed event payload.""" |
| 51 | + metadata = {} |
| 52 | + if sku is not None: |
| 53 | + metadata["sku"] = sku |
| 54 | + |
| 55 | + session_obj: dict = { |
| 56 | + "id": session_id, |
| 57 | + "client_reference_id": client_reference_id, |
| 58 | + "metadata": metadata, |
| 59 | + } |
| 60 | + |
| 61 | + return { |
| 62 | + "id": event_id, |
| 63 | + "type": "checkout.session.completed", |
| 64 | + "data": {"object": session_obj}, |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | +# --------------------------------------------------------------------------- |
| 69 | +# Happy path: credit allocation |
| 70 | +# --------------------------------------------------------------------------- |
| 71 | + |
| 72 | + |
| 73 | +@pytest.mark.asyncio |
| 74 | +async def test_checkout_completed_allocates_credits( |
| 75 | + client: AsyncClient, |
| 76 | + test_user: User, |
| 77 | + db_session: AsyncSession, |
| 78 | +) -> None: |
| 79 | + """A valid checkout.session.completed event allocates credits.""" |
| 80 | + event = _checkout_event( |
| 81 | + client_reference_id=str(test_user.id), |
| 82 | + sku="cred10", |
| 83 | + session_id="cs_alloc_001", |
| 84 | + ) |
| 85 | + |
| 86 | + with patch("stripe.Webhook.construct_event", return_value=event): |
| 87 | + response = await client.post( |
| 88 | + WEBHOOK_URL, |
| 89 | + content=b"{}", |
| 90 | + headers={"stripe-signature": "t=1,v1=sig"}, |
| 91 | + ) |
| 92 | + |
| 93 | + assert response.status_code == 200 |
| 94 | + assert response.json() == {"received": True} |
| 95 | + |
| 96 | + # Verify a ledger entry was created with the correct values. |
| 97 | + from sqlalchemy import select |
| 98 | + |
| 99 | + result = await db_session.execute( |
| 100 | + select(CreditLedgerEntry).where( |
| 101 | + CreditLedgerEntry.reference_id == "cs_alloc_001", |
| 102 | + ) |
| 103 | + ) |
| 104 | + entry = result.scalar_one_or_none() |
| 105 | + assert entry is not None |
| 106 | + assert entry.user_id == test_user.id |
| 107 | + assert entry.amount == Decimal("100") |
| 108 | + assert entry.direction == TransactionDirection.CREDIT |
| 109 | + assert entry.source == TransactionSource.STRIPE |
| 110 | + assert entry.description == "Stripe checkout: cred10" |
| 111 | + |
| 112 | + |
| 113 | +# --------------------------------------------------------------------------- |
| 114 | +# Idempotency: same event twice |
| 115 | +# --------------------------------------------------------------------------- |
| 116 | + |
| 117 | + |
| 118 | +@pytest.mark.asyncio |
| 119 | +async def test_checkout_completed_idempotent( |
| 120 | + client: AsyncClient, |
| 121 | + test_user: User, |
| 122 | + db_session: AsyncSession, |
| 123 | +) -> None: |
| 124 | + """Replaying the same event does not create a duplicate ledger entry.""" |
| 125 | + event = _checkout_event( |
| 126 | + client_reference_id=str(test_user.id), |
| 127 | + sku="cred10", |
| 128 | + session_id="cs_idemp_001", |
| 129 | + ) |
| 130 | + |
| 131 | + with patch("stripe.Webhook.construct_event", return_value=event): |
| 132 | + r1 = await client.post( |
| 133 | + WEBHOOK_URL, |
| 134 | + content=b"{}", |
| 135 | + headers={"stripe-signature": "t=1,v1=sig"}, |
| 136 | + ) |
| 137 | + r2 = await client.post( |
| 138 | + WEBHOOK_URL, |
| 139 | + content=b"{}", |
| 140 | + headers={"stripe-signature": "t=1,v1=sig"}, |
| 141 | + ) |
| 142 | + |
| 143 | + assert r1.status_code == 200 |
| 144 | + assert r2.status_code == 200 |
| 145 | + |
| 146 | + # Only one ledger entry should exist for this reference_id. |
| 147 | + from sqlalchemy import func, select |
| 148 | + |
| 149 | + result = await db_session.execute( |
| 150 | + select(func.count()).where( |
| 151 | + CreditLedgerEntry.reference_id == "cs_idemp_001", |
| 152 | + ) |
| 153 | + ) |
| 154 | + assert result.scalar_one() == 1 |
| 155 | + |
| 156 | + |
| 157 | +# --------------------------------------------------------------------------- |
| 158 | +# Unknown SKU |
| 159 | +# --------------------------------------------------------------------------- |
| 160 | + |
| 161 | + |
| 162 | +@pytest.mark.asyncio |
| 163 | +async def test_checkout_completed_unknown_sku( |
| 164 | + client: AsyncClient, |
| 165 | + test_user: User, |
| 166 | + db_session: AsyncSession, |
| 167 | +) -> None: |
| 168 | + """An unknown SKU logs a warning but still returns received: True.""" |
| 169 | + event = _checkout_event( |
| 170 | + client_reference_id=str(test_user.id), |
| 171 | + sku="cred_unknown", |
| 172 | + session_id="cs_unknown_001", |
| 173 | + ) |
| 174 | + |
| 175 | + with patch("stripe.Webhook.construct_event", return_value=event): |
| 176 | + response = await client.post( |
| 177 | + WEBHOOK_URL, |
| 178 | + content=b"{}", |
| 179 | + headers={"stripe-signature": "t=1,v1=sig"}, |
| 180 | + ) |
| 181 | + |
| 182 | + assert response.status_code == 200 |
| 183 | + assert response.json() == {"received": True} |
| 184 | + |
| 185 | + # No ledger entry should have been created. |
| 186 | + from sqlalchemy import func, select |
| 187 | + |
| 188 | + result = await db_session.execute( |
| 189 | + select(func.count()).where( |
| 190 | + CreditLedgerEntry.reference_id == "cs_unknown_001", |
| 191 | + ) |
| 192 | + ) |
| 193 | + assert result.scalar_one() == 0 |
| 194 | + |
| 195 | + |
| 196 | +# --------------------------------------------------------------------------- |
| 197 | +# Missing metadata / SKU |
| 198 | +# --------------------------------------------------------------------------- |
| 199 | + |
| 200 | + |
| 201 | +@pytest.mark.asyncio |
| 202 | +async def test_checkout_completed_missing_metadata( |
| 203 | + client: AsyncClient, |
| 204 | + test_user: User, |
| 205 | + db_session: AsyncSession, |
| 206 | +) -> None: |
| 207 | + """Missing metadata/sku logs a warning but still returns received: True.""" |
| 208 | + event = _checkout_event( |
| 209 | + client_reference_id=str(test_user.id), |
| 210 | + sku=None, |
| 211 | + session_id="cs_nometa_001", |
| 212 | + ) |
| 213 | + |
| 214 | + with patch("stripe.Webhook.construct_event", return_value=event): |
| 215 | + response = await client.post( |
| 216 | + WEBHOOK_URL, |
| 217 | + content=b"{}", |
| 218 | + headers={"stripe-signature": "t=1,v1=sig"}, |
| 219 | + ) |
| 220 | + |
| 221 | + assert response.status_code == 200 |
| 222 | + assert response.json() == {"received": True} |
| 223 | + |
| 224 | + # No ledger entry should have been created. |
| 225 | + from sqlalchemy import func, select |
| 226 | + |
| 227 | + result = await db_session.execute( |
| 228 | + select(func.count()).where( |
| 229 | + CreditLedgerEntry.reference_id == "cs_nometa_001", |
| 230 | + ) |
| 231 | + ) |
| 232 | + assert result.scalar_one() == 0 |
| 233 | + |
| 234 | + |
| 235 | +# --------------------------------------------------------------------------- |
| 236 | +# Missing stripe-signature header |
| 237 | +# --------------------------------------------------------------------------- |
| 238 | + |
| 239 | + |
| 240 | +@pytest.mark.asyncio |
| 241 | +async def test_missing_signature_returns_400(client: AsyncClient) -> None: |
| 242 | + """A request without a stripe-signature header is rejected with 400.""" |
| 243 | + response = await client.post( |
| 244 | + WEBHOOK_URL, |
| 245 | + content=b"{}", |
| 246 | + ) |
| 247 | + assert response.status_code == 400 |
| 248 | + assert "Missing stripe-signature" in response.json()["detail"] |
| 249 | + |
| 250 | + |
| 251 | +# --------------------------------------------------------------------------- |
| 252 | +# Invalid signature |
| 253 | +# --------------------------------------------------------------------------- |
| 254 | + |
| 255 | + |
| 256 | +@pytest.mark.asyncio |
| 257 | +async def test_invalid_signature_returns_400(client: AsyncClient) -> None: |
| 258 | + """An invalid Stripe signature is rejected with 400.""" |
| 259 | + with patch( |
| 260 | + "stripe.Webhook.construct_event", |
| 261 | + side_effect=stripe.error.SignatureVerificationError("bad sig", "sig_header"), |
| 262 | + ): |
| 263 | + response = await client.post( |
| 264 | + WEBHOOK_URL, |
| 265 | + content=b"{}", |
| 266 | + headers={"stripe-signature": "t=1,v1=badsig"}, |
| 267 | + ) |
| 268 | + |
| 269 | + assert response.status_code == 400 |
| 270 | + assert "Invalid signature" in response.json()["detail"] |
0 commit comments