Compare commits

..
Author SHA1 Message Date
Lukas Bockstaller e4b65ba49d drop pycrytodome as a dependency from pyproject.toml 2026-11-18 14:53:01 +01:00
Lukas Bockstaller 071b8baf61 remove temporary test & Crypto from test_oidc_op.py 2026-11-18 14:51:22 +01:00
Lukas Bockstaller ff6922e2ce remove Crypto from test_oidc_op.py::test_keys_endpoint
switch out Crypto.PublicKey.RSA with
cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicNumbers in test_keys_endopoint
2026-11-18 14:48:32 +01:00
Lukas Bockstaller 428d28e744 remove Crypto from oidc_op.py
switch out Crypto.PublicKey.RSA with
cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey and from cryptography.hazmat.primitives.serialization.load_pem_public_key which we already need
2026-11-18 14:42:35 +01:00
Lukas Bockstaller 0de0ad6cae add temporary test to show that Crypto.RSA and cryptography...RSAPublicKey produce identical output 2026-11-18 14:39:57 +01:00
Lukas Bockstaller 7f046e16a2 fix: pass request object to the request parameter of the form (#6786) 2026-11-18 12:04:34 +01:00
7 changed files with 173 additions and 11 deletions

No files matched your search

-1
View File
@@ -80,7 +80,6 @@ dependencies = [
"psycopg2-binary",
"pycountry",
"pycparser==3.12",
"pycryptodome==3.24.*",
"pypdf==6.21.*",
"python-bidi==0.6.*", # Support for Arabic in reportlab
"python-dateutil==4.0.*",
+3 -2
View File
@@ -24,13 +24,14 @@ from django.urls import include, re_path
from pretix.multidomain import event_url
from .views import (
OrganizerSettingsFormView, ScaReturnView, ScaView, oauth_disconnect,
oauth_return, webhook,
OrganizerSettingsFormView, ReturnView, ScaReturnView, ScaView,
oauth_disconnect, oauth_return, webhook,
)
event_patterns = [
re_path(r'^stripe/', include([
event_url(r'^webhook/$', webhook, name='webhook', require_live=False),
re_path(r'^return/(?P<order>[^/]+)/(?P<hash>[^/]+)/(?P<payment>[0-9]+)/$', ReturnView.as_view(), name='return'),
re_path(r'^sca/(?P<order>[^/]+)/(?P<hash>[^/]+)/(?P<payment>[0-9]+)/$', ScaView.as_view(), name='sca'),
re_path(r'^sca/(?P<order>[^/]+)/(?P<hash>[^/]+)/(?P<payment>[0-9]+)/return/$',
ScaReturnView.as_view(), name='sca.return'),
+21
View File
@@ -0,0 +1,21 @@
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation in version 3 of the License.
#
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
# this file, see <https://pretix.eu/about/en/license>.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
+130
View File
@@ -193,6 +193,10 @@ def webhook(request, *args, **kwargs):
func = charge_webhook
objid = event_json['data']['object']['charge']
lookup_ids = [objid]
elif event_json['data']['object']['object'] == "source":
func = source_webhook
objid = event_json['data']['object']['id']
lookup_ids = [objid]
elif event_json['data']['object']['object'] == "payment_intent":
func = paymentintent_webhook
objid = event_json['data']['object']['id']
@@ -346,6 +350,79 @@ def charge_webhook(event, event_json, charge_id, rso):
return HttpResponse(status=200)
def source_webhook(event, event_json, source_id, rso):
import stripe
from pretix.plugins.stripe.payment import StripeCC
prov = StripeCC(event)
prov._init_api()
try:
src = stripe.Source.retrieve(source_id, **prov.api_kwargs)
except stripe.error.StripeError:
logger.exception('Stripe error on webhook. Event data: %s' % str(event_json))
return HttpResponse('Charge not found', status=500)
metadata = src['metadata']
if 'event' not in metadata:
return HttpResponse('Event not given in charge metadata', status=200)
if int(metadata['event']) != event.pk:
return HttpResponse('Not interested in this event', status=200)
with transaction.atomic():
if rso and rso.payment:
order = rso.payment.order
payment = rso.payment
elif rso:
order = rso.order
payment = None
else:
try:
order = event.orders.get(id=metadata['order'])
except Order.DoesNotExist:
return HttpResponse('Order not found', status=200)
payment = None
if payment:
payment = OrderPayment.objects.select_for_update(of=OF_SELF).get(pk=payment.pk)
else:
payment = order.payments.filter(
info__icontains=src['id'],
provider__startswith='stripe',
amount=prov._amount_to_decimal(src['amount']) if src['amount'] is not None else order.total,
).select_for_update(of=OF_SELF).last()
if not payment:
payment = order.payments.create(
state=OrderPayment.PAYMENT_STATE_CREATED,
provider=SOURCE_TYPES.get(src['type'], 'stripe'),
amount=prov._amount_to_decimal(src['amount']) if src['amount'] is not None else order.total,
info=str(src),
)
if payment.provider != prov.identifier:
prov = payment.payment_provider
prov._init_api()
order.log_action('pretix.plugins.stripe.event', data=event_json)
go = (event_json['type'] == 'source.chargeable' and
payment.state in (OrderPayment.PAYMENT_STATE_PENDING, OrderPayment.PAYMENT_STATE_CREATED) and
src.status == 'chargeable')
if go:
try:
prov._charge_source(None, source_id, payment)
except PaymentException:
logger.exception('Webhook error')
elif src.status == 'failed':
payment.fail(info=str(src))
elif src.status == 'canceled' and payment.state in (OrderPayment.PAYMENT_STATE_PENDING, OrderPayment.PAYMENT_STATE_CREATED):
payment.info = str(src)
payment.state = OrderPayment.PAYMENT_STATE_CANCELED
payment.save()
return HttpResponse(status=200)
def paymentintent_webhook(event, event_json, paymentintent_id, rso):
import stripe
@@ -419,6 +496,59 @@ class StripeOrderView:
}) + ('?paid=yes' if self.order.status == Order.STATUS_PAID else ''))
@method_decorator(xframe_options_exempt, 'dispatch')
class ReturnView(StripeOrderView, View):
def get(self, request, *args, **kwargs):
import stripe
prov = self.pprov
prov._init_api()
try:
src = stripe.Source.retrieve(request.GET.get('source'), **prov.api_kwargs)
except stripe.error.InvalidRequestError:
logger.exception('Could not retrieve source')
messages.error(self.request, _('Sorry, there was an error in the payment process. Please check the link '
'in your emails to continue.'))
return redirect_to_url(eventreverse(self.request.event, 'presale:event.index'))
if src.client_secret != request.GET.get('client_secret'):
messages.error(self.request, _('Sorry, there was an error in the payment process. Please check the link '
'in your emails to continue.'))
return redirect_to_url(eventreverse(self.request.event, 'presale:event.index'))
with transaction.atomic():
self.order.refresh_from_db()
self.payment = OrderPayment.objects.select_for_update(of=OF_SELF).get(pk=self.payment.pk)
if self.payment.state == OrderPayment.PAYMENT_STATE_CONFIRMED:
if 'payment_stripe_token' in request.session:
del request.session['payment_stripe_token']
return self._redirect_to_order()
if src.status == 'chargeable':
try:
prov._charge_source(request, src.id, self.payment)
except PaymentException as e:
messages.error(request, str(e))
return self._redirect_to_order()
finally:
if 'payment_stripe_token' in request.session:
del request.session['payment_stripe_token']
elif src.status == 'consumed':
# Webhook was faster, wow! ;)
if 'payment_stripe_token' in request.session:
del request.session['payment_stripe_token']
return self._redirect_to_order()
elif src.status == 'pending':
self.payment.state = OrderPayment.PAYMENT_STATE_PENDING
self.payment.info = str(src)
self.payment.save()
else: # failed or canceled
self.payment.fail(info=str(src))
messages.error(self.request, _('We had trouble authorizing your card payment. Please try again and '
'get in touch with us if this problem persists.'))
return self._redirect_to_order()
@method_decorator(xframe_options_exempt, 'dispatch')
class ScaView(StripeOrderView, View):
+1 -1
View File
@@ -267,7 +267,7 @@ class CustomerStep(CartMixin, TemplateFlowStep):
else None
),
prefix='login',
request=self.request.event,
request=self.request,
)
for field in f.fields.values():
field._show_required = field.required
+7 -4
View File
@@ -26,7 +26,8 @@ from binascii import unhexlify
from datetime import timedelta
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
from Crypto.PublicKey import RSA
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from django.db import transaction
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import redirect, render
@@ -498,7 +499,9 @@ class KeysView(View):
def get(self, request, *args, **kwargs):
privkey, pubkey = _get_or_create_server_keypair(request.organizer)
kid = hashlib.sha256(pubkey.encode()).hexdigest()[:16]
pubkey = RSA.import_key(pubkey)
public_key = load_pem_public_key(pubkey.encode())
assert isinstance(public_key, RSAPublicKey)
public_numbers = public_key.public_numbers()
return JsonResponse({
'keys': [
@@ -507,8 +510,8 @@ class KeysView(View):
'alg': 'RS256',
'kid': kid,
'use': 'sig',
'e': self._encode_int(pubkey.e).decode().rstrip("="),
'n': self._encode_int(pubkey.n).decode().rstrip("="),
'e': self._encode_int(public_numbers.e).decode().rstrip("="),
'n': self._encode_int(public_numbers.n).decode().rstrip("="),
}
]
})
+11 -3
View File
@@ -30,7 +30,10 @@ from urllib.parse import quote
import jwt
import pytest
from bs4 import BeautifulSoup
from Crypto.PublicKey import RSA
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPublicKey, RSAPublicNumbers,
)
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from django.utils.timezone import now
from django_scopes import scopes_disabled
from freezegun import freeze_time
@@ -691,6 +694,11 @@ def test_keys_endpoint(env, client, ssoclient):
e = decode_int(data['keys'][0]['e'])
n = decode_int(data['keys'][0]['n'])
pubkey = RSA.construct((n, e))
representation = pubkey.export_key('PEM').decode()
pubkey = RSAPublicNumbers(e, n).public_key()
assert isinstance(pubkey, RSAPublicKey)
representation = pubkey.public_bytes(
Encoding.PEM, PublicFormat.SubjectPublicKeyInfo
).decode()
assert representation.strip() == env[0].settings.sso_server_signing_key_rsa256_public.strip()