diff --git a/src/strass/strass_app/forms.py b/src/strass/strass_app/forms.py index 6e922d16e9155f222eda0e2219458d5bf8fd4e6f..e74b9b096af4b62a31a6ccb9945c5213b7f69eb5 100644 --- a/src/strass/strass_app/forms.py +++ b/src/strass/strass_app/forms.py @@ -18,7 +18,9 @@ import datetime import json +import logging import smtplib +import traceback from basetheme_bootstrap.templatetags.sstatic import get_absolut_url from crispy_forms import layout @@ -30,7 +32,7 @@ from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.core.exceptions import ValidationError from django.core.files.uploadedfile import SimpleUploadedFile -from django.core.mail import EmailMultiAlternatives +from django.core.mail import EmailMultiAlternatives, mail_admins from django.core.validators import RegexValidator from django.db import transaction from django.db.models import Q, Case, When, Value, BooleanField @@ -42,6 +44,7 @@ from django.utils import timezone, translation from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _, gettext, ngettext +from tempfile import NamedTemporaryFile from language_override.translation import gettext_lazy as ogettext from live_settings import live_settings @@ -50,6 +53,8 @@ from strass_app.custom_layout_object import Formset from strass_app.templatetags.strass_tags import markdown from strass_app.utils import get_email_backend, validate_multiple_email, safe_pdf +logger = logging.getLogger(__name__) + class BoostrapSelectMultiple(forms.SelectMultiple): def __init__(self, attrs=None, *args, **kwargs): @@ -385,11 +390,27 @@ class CandidateForm(ModelFormWithReadOnly): raise ValidationError({'email': _("The email cannot be used to apply")}) if live_settings.cv_enabled__bool: - cleaned_data['cv'] = SimpleUploadedFile( - "cv.pdf", - safe_pdf(cleaned_data['cv']).read(), - content_type="application/pdf", - ) + try: + cleaned_data['cv'] = SimpleUploadedFile( + "cv.pdf", + safe_pdf(cleaned_data['cv']).read(), + content_type="application/pdf", + ) + except Exception as e: + logger.error(f"Failed while cleaning pdf...", exc_info=True) + cv_ko = NamedTemporaryFile( + prefix=f'StrassCV-{datetime.datetime.now().strftime("%Y-%m-%d--%H-%M-%S-")}', + suffix='.pdf', + delete=False, + ) + cleaned_data['cv'].seek(0) + with open(cv_ko.name, 'wb+') as fh: + for chunk in cleaned_data['cv'].chunks(): + fh.write(chunk) + logger.error(f"Failed while cleaning pdf, dump saved to {cv_ko.name}") + self.add_error('cv', _('Error while importing CV')) + tb = traceback.format_exc() + mail_admins("PDF cleanup failure", f"PDF file saved to {cv_ko.name}\n{tb}") return cleaned_data diff --git a/src/strass/strass_app/tests/test_forms.py b/src/strass/strass_app/tests/test_forms.py index 8a7c1217cb4036497887f094cebd986953e93bcf..22a408d9379f5c6cf7ee74ff4d8e5c64d9170156 100644 --- a/src/strass/strass_app/tests/test_forms.py +++ b/src/strass/strass_app/tests/test_forms.py @@ -17,10 +17,20 @@ # import logging +import os +import pathlib +import random +from tempfile import NamedTemporaryFile +from django.core import mail from crispy_forms import layout +from django.contrib.auth.models import AnonymousUser +from django.core.files.uploadedfile import SimpleUploadedFile from django.template import Template, Context +from django.test import RequestFactory +from freezegun import freeze_time +from strass_app import forms from strass_app.forms import EmptyForm from strass_app.tests.test_base_test_case import TooledTestCase @@ -45,3 +55,40 @@ class TestMain(TooledTestCase): self.assertNotEqual(r1, r2) self.assertIn('form1', r1) self.assertIn('form2', r2) + + +class TestCandidateForm(TooledTestCase): + def test_pdf_safe_crashes_log_collected(self): + mail_count = len(mail.outbox) + m = random.randint(1, 12) + d = random.randint(1, 28) + with freeze_time(f"1999-{m}-{d}"): + request_an = RequestFactory().get('/blabla') + request_an.user = AnonymousUser() + form = forms.CandidateForm( + request=request_an, + initial=dict(), + data={ + "first_name": "Ada", + "last_name": "Lovelace", + "email": "ada.lovelace@pasteur.fr", + "profiles": "2", + "motivation": "Yes I am !", + "lang": "en", + }, + files={ + "cv": SimpleUploadedFile('cv.pdf', b'zeazeazeaze', content_type="application/pdf"), + }, + ) + form.is_valid() + + with NamedTemporaryFile() as f: + files = list(pathlib.Path(f.name).parent.glob(f"*1999-{m:02d}-{d:02d}*.pdf")) + self.assertEqual( + 1, + len(list(pathlib.Path(f.name).parent.glob(f"*1999-{m:02d}-{d:02d}*.pdf"))), + "We must have one and only one file that have been created following the crash of the validation", + ) + os.remove(files[0]) + + self.assertEqual(1 + mail_count, len(mail.outbox))