|
1 | | -import os |
| 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. |
2 | 14 |
|
| 15 | +"""Stripe webhook handler with signature verification. |
| 16 | +
|
| 17 | +Receives and verifies Stripe webhook events. All events are logged |
| 18 | +for audit purposes. Signature verification is mandatory -- unsigned |
| 19 | +or forged requests are rejected with 400. |
| 20 | +
|
| 21 | +Security hardening (REN-69): |
| 22 | +- Catches ``stripe.error.SignatureVerificationError`` specifically |
| 23 | + (not a bare ``Exception``). |
| 24 | +- Validates that the ``stripe-signature`` header is present before |
| 25 | + attempting verification. |
| 26 | +- Uses ``core.config.get_settings()`` for Stripe secrets instead of |
| 27 | + module-level ``os.environ`` access (avoids import-time crashes). |
| 28 | +- Logs every webhook event with ``event_type`` and ``event_id`` for |
| 29 | + audit trail. |
| 30 | +- Does NOT log PII or payment details. |
| 31 | +
|
| 32 | +Testing: |
| 33 | + Use the Stripe CLI for local development:: |
| 34 | +
|
| 35 | + stripe listen --forward-to localhost:8000/api/v1/webhooks/stripe |
| 36 | + stripe trigger checkout.session.completed |
| 37 | +""" |
| 38 | + |
| 39 | +from __future__ import annotations |
| 40 | + |
| 41 | +import structlog |
3 | 42 | import stripe |
4 | | -from fastapi import APIRouter, HTTPException, Request |
5 | | -from ledger.credit import credit |
| 43 | +from fastapi import APIRouter, HTTPException, Request, status |
| 44 | + |
| 45 | +from core.config import get_settings |
| 46 | + |
| 47 | +logger = structlog.get_logger(__name__) |
6 | 48 |
|
7 | 49 | router = APIRouter() |
8 | | -stripe.api_key = os.environ["STRIPE_SECRET"] |
9 | | -ENDPOINT_SECRET = os.environ["STRIPE_WEBHOOK_SECRET"] |
10 | | -CREDIT_MAP = {"cred10": 100, "cred50": 550} |
| 50 | + |
| 51 | +# Credit SKU mapping. Kept here for backward compatibility; will be |
| 52 | +# moved to database-driven configuration in a future story. |
| 53 | +CREDIT_MAP: dict[str, int] = {"cred10": 100, "cred50": 550} |
11 | 54 |
|
12 | 55 |
|
13 | 56 | @router.post("/webhooks/stripe") |
14 | | -async def stripe_hook(req: Request): |
| 57 | +async def stripe_hook(req: Request) -> dict[str, object]: |
| 58 | + """Handle incoming Stripe webhook events. |
| 59 | +
|
| 60 | + Verifies the webhook signature using the endpoint secret, |
| 61 | + then dispatches the event based on its type. All events are |
| 62 | + acknowledged with ``{"received": True}`` to prevent Stripe |
| 63 | + retries for successfully received (but possibly unhandled) |
| 64 | + event types. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + dict: ``{"received": True}`` on successful processing. |
| 68 | +
|
| 69 | + Raises: |
| 70 | + HTTPException(400): If the signature header is missing, |
| 71 | + the signature is invalid, or the payload cannot be parsed. |
| 72 | + """ |
| 73 | + settings = get_settings() |
| 74 | + |
| 75 | + # -- 1. Validate signature header presence -- |
15 | 76 | sig = req.headers.get("stripe-signature") |
| 77 | + if not sig: |
| 78 | + logger.warning("stripe_webhook_missing_signature") |
| 79 | + raise HTTPException( |
| 80 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 81 | + detail="Missing stripe-signature header", |
| 82 | + ) |
| 83 | + |
16 | 84 | payload = await req.body() |
| 85 | + |
| 86 | + # -- 2. Verify signature with specific exception handling -- |
17 | 87 | try: |
18 | | - event = stripe.Webhook.construct_event(payload, sig, ENDPOINT_SECRET) |
19 | | - except Exception: |
20 | | - raise HTTPException(status_code=400) |
| 88 | + event = stripe.Webhook.construct_event( |
| 89 | + payload, |
| 90 | + sig, |
| 91 | + settings.stripe_webhook_secret, |
| 92 | + ) |
| 93 | + except stripe.error.SignatureVerificationError: |
| 94 | + logger.warning("stripe_webhook_invalid_signature") |
| 95 | + raise HTTPException( |
| 96 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 97 | + detail="Invalid signature", |
| 98 | + ) from None |
| 99 | + except ValueError: |
| 100 | + logger.warning("stripe_webhook_invalid_payload") |
| 101 | + raise HTTPException( |
| 102 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 103 | + detail="Invalid payload", |
| 104 | + ) from None |
| 105 | + |
| 106 | + # -- 3. Audit log: record every received event -- |
| 107 | + logger.info( |
| 108 | + "stripe_webhook_received", |
| 109 | + event_type=event["type"], |
| 110 | + event_id=event["id"], |
| 111 | + ) |
| 112 | + |
| 113 | + # -- 4. Route to event-specific handlers -- |
21 | 114 | if event["type"] == "checkout.session.completed": |
22 | | - sess = event["data"]["object"] |
23 | | - sku = sess["display_items"][0]["price"]["nickname"] |
24 | | - credits = CREDIT_MAP[sku] |
25 | | - creator_id = sess["client_reference_id"] |
26 | | - await credit(creator_id, credits) |
| 115 | + logger.info("stripe_checkout_completed", event_id=event["id"]) |
| 116 | + # TODO(REN-79): Implement credit allocation via event handler. |
| 117 | + # The previous implementation used `from ledger.credit import credit` |
| 118 | + # which no longer exists. Credit allocation with idempotency |
| 119 | + # checks will be implemented in REN-79. |
| 120 | + |
27 | 121 | return {"received": True} |
0 commit comments