Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions contentcuration/contentcuration/tests/views/test_subscription.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import hashlib
import hmac
import json
import time
from unittest import mock

import stripe
Expand Down Expand Up @@ -433,3 +437,75 @@ def test_idempotent_checkout_processing(self, mock_construct, mock_retrieve):
self.assertEqual(response.status_code, 200)
# Should still only have one subscription
self.assertEqual(UserSubscription.objects.filter(user=self.user).count(), 1)


def _signed_subscription_updated(secret, subscription_id, quantity):
payload = json.dumps(
{
"id": "evt_test",
"object": "event",
"type": "customer.subscription.updated",
"data": {
"object": {
"id": subscription_id,
"status": "active",
"cancel_at_period_end": False,
"items": {"data": [{"quantity": quantity}]},
}
},
}
)
timestamp = int(time.time())
signature = hmac.new(
secret.encode(), f"{timestamp}.{payload}".encode(), hashlib.sha256
).hexdigest()
return payload, f"t={timestamp},v1={signature}"


class StripeWebhookSignatureTest(StudioAPITestCase):
Comment thread
adibmbrk marked this conversation as resolved.
Resolved
"""Exercise real signature verification, without mocking construct_event."""

def setUp(self):
self.user = testdata.user(email="webhook-signature@test.com")
self.subscription = UserSubscription.objects.create(
user=self.user,
stripe_customer_id="cus_test123",
stripe_subscription_id="sub_test123",
stripe_subscription_status="active",
subscription_disk_space=0,
)
self.webhook_url = reverse("stripe_webhook")

def _post(self, secret):
payload, signature = _signed_subscription_updated(secret, "sub_test123", 50)
return self.client.post(
self.webhook_url,
data=payload,
content_type="application/json",
HTTP_STRIPE_SIGNATURE=signature,
)

@override_settings(STRIPE_WEBHOOK_SECRET="")
def test_rejects_event_signed_with_empty_secret_when_none_configured(self):
with self.assertLogs("contentcuration.views.subscription", "ERROR"):
response = self._post("")

self.assertEqual(response.status_code, 400)
self.subscription.refresh_from_db()
self.assertEqual(self.subscription.subscription_disk_space, 0)

@override_settings(STRIPE_WEBHOOK_SECRET="whsec_test_fake")
def test_handles_correctly_signed_event_when_secret_configured(self):
response = self._post("whsec_test_fake")

self.assertEqual(response.status_code, 200)
self.subscription.refresh_from_db()
self.assertEqual(self.subscription.subscription_disk_space, 50 * 10 ** 9)

@override_settings(STRIPE_WEBHOOK_SECRET="whsec_test_fake")
def test_rejects_event_signed_with_wrong_secret(self):
response = self._post("")

self.assertEqual(response.status_code, 400)
self.subscription.refresh_from_db()
self.assertEqual(self.subscription.subscription_disk_space, 0)
4 changes: 4 additions & 0 deletions contentcuration/contentcuration/views/subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,10 @@ def save(self):
@csrf_exempt
@require_POST
def stripe_webhook(request):
if not settings.STRIPE_WEBHOOK_SECRET:
logger.error("Stripe webhook secret is not configured; rejecting webhook.")
return JsonResponse({"error": "Webhook is not configured"}, status=400)

try:
event = stripe.Webhook.construct_event(
request.body,
Expand Down
Loading