diff --git a/core/api/v1/router.py b/core/api/v1/router.py index f188ee6..5acc06a 100644 --- a/core/api/v1/router.py +++ b/core/api/v1/router.py @@ -22,6 +22,7 @@ from core.api.v1.auth import router as auth_router from core.api.v1.health import router as health_router +from core.billing.stripe.stripe_webhook import router as stripe_webhook_router api_v1_router = APIRouter(prefix="/api/v1") @@ -30,3 +31,6 @@ # Authentication api_v1_router.include_router(auth_router, tags=["auth"]) + +# Billing webhooks +api_v1_router.include_router(stripe_webhook_router, tags=["billing"]) diff --git a/core/billing/stripe/stripe_webhook.py b/core/billing/stripe/stripe_webhook.py index 526d731..f945b5d 100644 --- a/core/billing/stripe/stripe_webhook.py +++ b/core/billing/stripe/stripe_webhook.py @@ -38,11 +38,21 @@ from __future__ import annotations +from decimal import Decimal +from typing import TYPE_CHECKING +from uuid import UUID + import stripe import structlog -from fastapi import APIRouter, HTTPException, Request, status +from fastapi import APIRouter, Depends, HTTPException, Request, status from core.config import get_settings +from core.database import get_db_session +from core.ledger.service import allocate_credits +from core.models.base import TransactionSource + +if TYPE_CHECKING: + from sqlalchemy.ext.asyncio import AsyncSession logger = structlog.get_logger(__name__) @@ -54,7 +64,10 @@ @router.post("/webhooks/stripe") -async def stripe_hook(req: Request) -> dict[str, object]: +async def stripe_hook( + req: Request, + session: AsyncSession = Depends(get_db_session), +) -> dict[str, object]: """Handle incoming Stripe webhook events. Verifies the webhook signature using the endpoint secret, @@ -63,6 +76,10 @@ async def stripe_hook(req: Request) -> dict[str, object]: retries for successfully received (but possibly unhandled) event types. + Credit allocation for ``checkout.session.completed`` events is + idempotent -- Stripe retries are safe because the ledger service + uses the checkout session ID as a deduplication key. + Returns: dict: ``{"received": True}`` on successful processing. @@ -112,10 +129,61 @@ async def stripe_hook(req: Request) -> dict[str, object]: # -- 4. Route to event-specific handlers -- if event["type"] == "checkout.session.completed": - logger.info("stripe_checkout_completed", event_id=event["id"]) - # TODO(REN-79): Implement credit allocation via event handler. - # The previous implementation used `from ledger.credit import credit` - # which no longer exists. Credit allocation with idempotency - # checks will be implemented in REN-79. + await _handle_checkout_completed(event, session) return {"received": True} + + +async def _handle_checkout_completed( + event: dict[str, object], + session: AsyncSession, +) -> None: + """Allocate credits after a successful Stripe checkout session. + + Extracts the user UUID from ``client_reference_id`` and the credit + SKU from session metadata, then delegates to the ledger service. + Unknown or missing SKUs are logged as warnings but do NOT cause + the webhook to fail (Stripe would retry indefinitely). + """ + sess_obj: dict[str, object] = event["data"]["object"] # type: ignore[index] + checkout_session_id: str = sess_obj.get("id", "") # type: ignore[assignment] + + # Extract user ID from Stripe's client_reference_id field. + client_reference_id = sess_obj.get("client_reference_id") + if not client_reference_id: + logger.warning( + "stripe_checkout_missing_client_reference_id", + event_id=event["id"], + ) + return + + # Determine the credit SKU from session metadata. + metadata: dict[str, str] = sess_obj.get("metadata") or {} # type: ignore[assignment] + sku = metadata.get("sku") + if not sku or sku not in CREDIT_MAP: + logger.warning( + "stripe_checkout_unknown_sku", + event_id=event["id"], + sku=sku, + ) + return + + credit_amount = CREDIT_MAP[sku] + + logger.info( + "stripe_checkout_completed", + event_id=event["id"], + sku=sku, + credit_amount=credit_amount, + user_id=client_reference_id, + ) + + await allocate_credits( + session=session, + user_id=UUID(str(client_reference_id)), + amount=Decimal(credit_amount), + source=TransactionSource.STRIPE, + reference_id=str(checkout_session_id), + description=f"Stripe checkout: {sku}", + ) + await session.commit() diff --git a/tests/test_stripe_webhook.py b/tests/test_stripe_webhook.py new file mode 100644 index 0000000..9d67688 --- /dev/null +++ b/tests/test_stripe_webhook.py @@ -0,0 +1,270 @@ +# Copyright 2025 ByBren, LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the Stripe webhook handler (REN-79). + +Verifies credit allocation wiring between the Stripe checkout.session.completed +event and the credit ledger service. All tests mock +``stripe.Webhook.construct_event`` since real Stripe signatures cannot be +generated in tests. +""" + +from __future__ import annotations + +from decimal import Decimal +from typing import TYPE_CHECKING +from unittest.mock import patch + +import pytest +import stripe + +from core.models.base import CreditLedgerEntry, TransactionDirection, TransactionSource + +if TYPE_CHECKING: + from httpx import AsyncClient + from sqlalchemy.ext.asyncio import AsyncSession + + from core.models.base import User + +WEBHOOK_URL = "/api/v1/webhooks/stripe" + + +def _checkout_event( + *, + event_id: str = "evt_test_123", + session_id: str = "cs_test_abc", + client_reference_id: str | None = "00000000-0000-0000-0000-000000000001", + sku: str | None = "cred10", +) -> dict: + """Build a minimal checkout.session.completed event payload.""" + metadata = {} + if sku is not None: + metadata["sku"] = sku + + session_obj: dict = { + "id": session_id, + "client_reference_id": client_reference_id, + "metadata": metadata, + } + + return { + "id": event_id, + "type": "checkout.session.completed", + "data": {"object": session_obj}, + } + + +# --------------------------------------------------------------------------- +# Happy path: credit allocation +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_checkout_completed_allocates_credits( + client: AsyncClient, + test_user: User, + db_session: AsyncSession, +) -> None: + """A valid checkout.session.completed event allocates credits.""" + event = _checkout_event( + client_reference_id=str(test_user.id), + sku="cred10", + session_id="cs_alloc_001", + ) + + with patch("stripe.Webhook.construct_event", return_value=event): + response = await client.post( + WEBHOOK_URL, + content=b"{}", + headers={"stripe-signature": "t=1,v1=sig"}, + ) + + assert response.status_code == 200 + assert response.json() == {"received": True} + + # Verify a ledger entry was created with the correct values. + from sqlalchemy import select + + result = await db_session.execute( + select(CreditLedgerEntry).where( + CreditLedgerEntry.reference_id == "cs_alloc_001", + ) + ) + entry = result.scalar_one_or_none() + assert entry is not None + assert entry.user_id == test_user.id + assert entry.amount == Decimal("100") + assert entry.direction == TransactionDirection.CREDIT + assert entry.source == TransactionSource.STRIPE + assert entry.description == "Stripe checkout: cred10" + + +# --------------------------------------------------------------------------- +# Idempotency: same event twice +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_checkout_completed_idempotent( + client: AsyncClient, + test_user: User, + db_session: AsyncSession, +) -> None: + """Replaying the same event does not create a duplicate ledger entry.""" + event = _checkout_event( + client_reference_id=str(test_user.id), + sku="cred10", + session_id="cs_idemp_001", + ) + + with patch("stripe.Webhook.construct_event", return_value=event): + r1 = await client.post( + WEBHOOK_URL, + content=b"{}", + headers={"stripe-signature": "t=1,v1=sig"}, + ) + r2 = await client.post( + WEBHOOK_URL, + content=b"{}", + headers={"stripe-signature": "t=1,v1=sig"}, + ) + + assert r1.status_code == 200 + assert r2.status_code == 200 + + # Only one ledger entry should exist for this reference_id. + from sqlalchemy import func, select + + result = await db_session.execute( + select(func.count()).where( + CreditLedgerEntry.reference_id == "cs_idemp_001", + ) + ) + assert result.scalar_one() == 1 + + +# --------------------------------------------------------------------------- +# Unknown SKU +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_checkout_completed_unknown_sku( + client: AsyncClient, + test_user: User, + db_session: AsyncSession, +) -> None: + """An unknown SKU logs a warning but still returns received: True.""" + event = _checkout_event( + client_reference_id=str(test_user.id), + sku="cred_unknown", + session_id="cs_unknown_001", + ) + + with patch("stripe.Webhook.construct_event", return_value=event): + response = await client.post( + WEBHOOK_URL, + content=b"{}", + headers={"stripe-signature": "t=1,v1=sig"}, + ) + + assert response.status_code == 200 + assert response.json() == {"received": True} + + # No ledger entry should have been created. + from sqlalchemy import func, select + + result = await db_session.execute( + select(func.count()).where( + CreditLedgerEntry.reference_id == "cs_unknown_001", + ) + ) + assert result.scalar_one() == 0 + + +# --------------------------------------------------------------------------- +# Missing metadata / SKU +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_checkout_completed_missing_metadata( + client: AsyncClient, + test_user: User, + db_session: AsyncSession, +) -> None: + """Missing metadata/sku logs a warning but still returns received: True.""" + event = _checkout_event( + client_reference_id=str(test_user.id), + sku=None, + session_id="cs_nometa_001", + ) + + with patch("stripe.Webhook.construct_event", return_value=event): + response = await client.post( + WEBHOOK_URL, + content=b"{}", + headers={"stripe-signature": "t=1,v1=sig"}, + ) + + assert response.status_code == 200 + assert response.json() == {"received": True} + + # No ledger entry should have been created. + from sqlalchemy import func, select + + result = await db_session.execute( + select(func.count()).where( + CreditLedgerEntry.reference_id == "cs_nometa_001", + ) + ) + assert result.scalar_one() == 0 + + +# --------------------------------------------------------------------------- +# Missing stripe-signature header +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_missing_signature_returns_400(client: AsyncClient) -> None: + """A request without a stripe-signature header is rejected with 400.""" + response = await client.post( + WEBHOOK_URL, + content=b"{}", + ) + assert response.status_code == 400 + assert "Missing stripe-signature" in response.json()["detail"] + + +# --------------------------------------------------------------------------- +# Invalid signature +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_invalid_signature_returns_400(client: AsyncClient) -> None: + """An invalid Stripe signature is rejected with 400.""" + with patch( + "stripe.Webhook.construct_event", + side_effect=stripe.error.SignatureVerificationError("bad sig", "sig_header"), + ): + response = await client.post( + WEBHOOK_URL, + content=b"{}", + headers={"stripe-signature": "t=1,v1=badsig"}, + ) + + assert response.status_code == 400 + assert "Invalid signature" in response.json()["detail"]