"""The provider's callback. Unauthenticated by necessity — a payment provider has no session — so the signature is the only thing standing between this endpoint and an attacker creating orders. It is verified before the body is parsed, let alone acted on, and an unverified delivery is recorded and refused rather than retried. """ from fastapi import APIRouter, HTTPException, Request from .. import payments from ..core import db from ..core.auth import audit, client_ip, rate_limit from ..runtime import payment router = APIRouter() # Generous: a provider legitimately retries, and a signature check is cheap. # This exists so an unsigned flood cannot keep the database busy. WEBHOOK_LIMIT = 600 @router.post('/api/payments/webhook') async def webhook(request: Request): rate_limit('payment-webhook', client_ip(request), WEBHOOK_LIMIT, 900) body = await request.body() if not payment.verify(request.headers, body): audit('payment_webhook_rejected', ip=client_ip(request), reason='signature') raise HTTPException(403, 'Invalid signature') event = payment.parse(body) if event is None: # Verified, so genuinely from the provider, but not about a payment. # Acknowledge it: refusing would make the provider retry for ever. return {'status': 'ignored'} with db.connect() as c: stored = payments.record(c, event_provider(), event) if stored is None: # Already delivered. Acknowledge without acting again. return {'status': 'duplicate'} outcome = payments.apply(c, event) c.execute('UPDATE dtf_local.payment_events SET processed_at=now(), outcome=%s WHERE id=%s', (outcome, stored['id'])) # audit()'s own first parameter is named `event`, so the id goes under another key. audit('payment_webhook_applied', payment_event=event.event_id, status=event.status, outcome=outcome) return {'status': 'applied', 'outcome': outcome} def event_provider(): return getattr(payment, 'name', payment.__class__.__name__.replace('Payment', '').lower() or 'fake')