From 1101f0d701462e2b1697d363210e4e54b511f929 Mon Sep 17 00:00:00 2001 From: Maxime Date: Mon, 30 Nov 2026 11:17:03 +0100 Subject: [PATCH] =?UTF-8?q?Remplace=20excelwebzone/recaptcha-bundle=20pour?= =?UTF-8?q?=20pr=C3=A9parer=20Symfony=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le bundle est archivé et n'accepte pas Symfony 8 : c'était la dernière dépendance qui bloquait la bascule du cœur en 8.1. Il est remplacé par une implémentation reCAPTCHA v2 maison dans AppBundle\Recaptcha, sans changement pour les visiteurs : mêmes clés RECAPTCHA_PUBLIC_KEY / RECAPTCHA_PRIVATE_KEY, même case à cocher, toujours désactivée en env test. - RecaptchaType affiche le widget Google (bloc recaptcha_widget du form theme) et porte la contrainte par défaut. - IsValidRecaptchaValidator vérifie le jeton auprès de siteverify via HttpClient. Un jeton absent, refusé, ou une erreur côté Google refusent le formulaire ; l'erreur est loguée. - Le formulaire de suggestion de conférencier affiche désormais l'erreur du captcha, qui était jusqu'ici invisible. excelwebzone/recaptcha-bundle et google/recaptcha sont retirés des dépendances. Refs #2441 --- composer.json | 1 - composer.lock | 118 +------------- config/bundles.php | 1 - config/packages/ewz_recaptcha.yaml | 7 - config/packages/recaptcha.yaml | 6 + config/reference.php | 31 ---- .../Association/Form/CompanyMemberType.php | 11 +- sources/AppBundle/Event/Form/LeadType.php | 11 +- .../Event/Form/SpeakerSuggestionType.php | 11 +- .../AppBundle/Recaptcha/IsValidRecaptcha.php | 19 +++ .../Recaptcha/IsValidRecaptchaValidator.php | 69 +++++++++ sources/AppBundle/Recaptcha/RecaptchaType.php | 51 +++++++ .../event/speaker-suggestion/index.html.twig | 1 + templates/form_theme.html.twig | 7 + .../Form/CompanyMemberTypeTest.php | 13 +- .../IsValidRecaptchaValidatorTest.php | 144 ++++++++++++++++++ translations/validators.fr.yml | 1 + 17 files changed, 308 insertions(+), 194 deletions(-) delete mode 100644 config/packages/ewz_recaptcha.yaml create mode 100644 config/packages/recaptcha.yaml create mode 100644 sources/AppBundle/Recaptcha/IsValidRecaptcha.php create mode 100644 sources/AppBundle/Recaptcha/IsValidRecaptchaValidator.php create mode 100644 sources/AppBundle/Recaptcha/RecaptchaType.php create mode 100644 tests/unit/AppBundle/Recaptcha/IsValidRecaptchaValidatorTest.php diff --git a/composer.json b/composer.json index d094fdf09..5d1382edf 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,6 @@ "doctrine/orm": "^3.6", "drewm/mailchimp-api": "^2.5", "erusev/parsedown": "^1.8", - "excelwebzone/recaptcha-bundle": "^1.5", "geocoder-php/google-maps-provider": "^4.8", "jms/serializer-bundle": "^5.5", "knpuniversity/oauth2-client-bundle": "^2.20", diff --git a/composer.lock b/composer.lock index a4f7b551c..bfe3df3c8 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "3aa100a4d728c31fba5d662a01f194b9", + "content-hash": "d69af157f3b1ea57f3d3313eee7bcecc", "packages": [ { "name": "algolia/algoliasearch-client-php", @@ -2400,67 +2400,6 @@ ], "time": "2026-02-16T11:41:01+00:00" }, - { - "name": "excelwebzone/recaptcha-bundle", - "version": "v1.5.42", - "source": { - "type": "git", - "url": "https://github.com/excelwebzone/EWZRecaptchaBundle.git", - "reference": "c1728fab6dc1a880e1b76298c5092f2ca25dac8f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/excelwebzone/EWZRecaptchaBundle/zipball/c1728fab6dc1a880e1b76298c5092f2ca25dac8f", - "reference": "c1728fab6dc1a880e1b76298c5092f2ca25dac8f", - "shasum": "" - }, - "require": { - "google/recaptcha": "^1.1", - "php": "^7.1 || ^8.0", - "symfony/form": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0", - "symfony/framework-bundle": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0", - "symfony/security-bundle": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0", - "symfony/validator": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0", - "symfony/yaml": "^2.8 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0", - "twig/twig": "^1.40 || ^2.9 || ^3.0" - }, - "require-dev": { - "phpunit/phpunit": "^7 || ^8 || ^9.5" - }, - "type": "symfony-bundle", - "extra": { - "symfony": { - "allow-contrib": "true" - } - }, - "autoload": { - "psr-4": { - "EWZ\\Bundle\\RecaptchaBundle\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael H. Arieli", - "email": "excelwebzone@gmail.com", - "homepage": "http://excelwebzone.com/" - } - ], - "description": "This bundle provides easy reCAPTCHA form field integration", - "homepage": "https://github.com/excelwebzone/EWZRecaptchaBundle", - "keywords": [ - "recaptcha" - ], - "support": { - "issues": "https://github.com/excelwebzone/EWZRecaptchaBundle/issues", - "source": "https://github.com/excelwebzone/EWZRecaptchaBundle/tree/v1.5.42" - }, - "abandoned": true, - "time": "2025-02-03T20:57:06+00:00" - }, { "name": "geocoder-php/common-http", "version": "4.7.0", @@ -2581,59 +2520,6 @@ }, "time": "2025-04-15T13:24:32+00:00" }, - { - "name": "google/recaptcha", - "version": "1.5", - "source": { - "type": "git", - "url": "https://github.com/google/recaptcha.git", - "reference": "c57f0b96babc8c9fb64cb555cd7b2c5aadfbe58d" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/google/recaptcha/zipball/c57f0b96babc8c9fb64cb555cd7b2c5aadfbe58d", - "reference": "c57f0b96babc8c9fb64cb555cd7b2c5aadfbe58d", - "shasum": "" - }, - "require": { - "php": ">=8.4" - }, - "require-dev": { - "friendsofphp/php-cs-fixer": "^3.95", - "php-coveralls/php-coveralls": "^2.9.1", - "phpstan/phpstan": "^2.1.51", - "phpunit/phpunit": "^13.1" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.4.x-dev" - } - }, - "autoload": { - "psr-4": { - "ReCaptcha\\": "src/ReCaptcha" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "description": "Client library for reCAPTCHA, a free service that protects websites from spam and abuse.", - "homepage": "https://www.google.com/recaptcha/", - "keywords": [ - "Abuse", - "captcha", - "recaptcha", - "spam" - ], - "support": { - "forum": "https://groups.google.com/forum/#!forum/recaptcha", - "issues": "https://github.com/google/recaptcha/issues", - "source": "https://github.com/google/recaptcha" - }, - "time": "2026-04-27T09:26:38+00:00" - }, { "name": "guzzlehttp/guzzle", "version": "7.11.0", @@ -16915,5 +16801,5 @@ "ext-zip": "*" }, "platform-dev": {}, - "plugin-api-version": "2.9.0" + "plugin-api-version": "2.11.0" } diff --git a/config/bundles.php b/config/bundles.php index 9b999c1cf..80477f888 100644 --- a/config/bundles.php +++ b/config/bundles.php @@ -13,7 +13,6 @@ AppBundle\AppBundle::class => ['all' => true], JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true], Presta\SitemapBundle\PrestaSitemapBundle::class => ['all' => true], - EWZ\Bundle\RecaptchaBundle\EWZRecaptchaBundle::class => ['all' => true], Tiime\NewRelicBundle\TiimeNewRelicBundle::class => ['all' => true], Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true], Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true], diff --git a/config/packages/ewz_recaptcha.yaml b/config/packages/ewz_recaptcha.yaml deleted file mode 100644 index 45a52fa2d..000000000 --- a/config/packages/ewz_recaptcha.yaml +++ /dev/null @@ -1,7 +0,0 @@ -ewz_recaptcha: - public_key: '%env(RECAPTCHA_PUBLIC_KEY)%' - private_key: '%env(RECAPTCHA_PRIVATE_KEY)%' - -when@test: - ewz_recaptcha: - enabled: false diff --git a/config/packages/recaptcha.yaml b/config/packages/recaptcha.yaml new file mode 100644 index 000000000..cd097ad6e --- /dev/null +++ b/config/packages/recaptcha.yaml @@ -0,0 +1,6 @@ +parameters: + app.recaptcha.enabled: true + +when@test: + parameters: + app.recaptcha.enabled: false diff --git a/config/reference.php b/config/reference.php index 8208413ad..d83f4d590 100644 --- a/config/reference.php +++ b/config/reference.php @@ -1494,33 +1494,6 @@ * i18n?: "symfony"|"jms"|Param, // Strategy used to create your i18n routes. // Default: "symfony" * }, * } - * @psalm-type EwzRecaptchaConfig = array{ - * public_key?: scalar|Param|null, - * private_key?: scalar|Param|null, - * enabled?: bool|Param, // Default: true - * verify_host?: bool|Param, // Default: false - * ajax?: bool|Param, // Default: false - * locale_key?: scalar|Param|null, // Default: "%kernel.default_locale%" - * api_host?: scalar|Param|null, // Default: "www.google.com" - * locale_from_request?: bool|Param, // Default: false - * version?: int|Param, // Default: 2 - * hide_badge?: bool|Param, // Default: false - * score_threshold?: float|Param, // Default: 0.5 - * timeout?: int|Param, // Default: null - * trusted_roles?: list, - * http_proxy?: array{ - * host?: scalar|Param|null, // Default: null - * port?: scalar|Param|null, // Default: null - * auth?: scalar|Param|null, // Default: null - * }, - * service_definition?: list, - * } * @psalm-type TiimeNewRelicConfig = array{ * enabled?: bool|Param, // Default: true * interactor?: scalar|Param|null, @@ -1835,7 +1808,6 @@ * knpu_oauth2_client?: KnpuOauth2ClientConfig, * jms_serializer?: JmsSerializerConfig, * presta_sitemap?: PrestaSitemapConfig, - * ewz_recaptcha?: EwzRecaptchaConfig, * tiime_new_relic?: TiimeNewRelicConfig, * valinor?: ValinorConfig, * doctrine?: DoctrineConfig, @@ -1856,7 +1828,6 @@ * knpu_oauth2_client?: KnpuOauth2ClientConfig, * jms_serializer?: JmsSerializerConfig, * presta_sitemap?: PrestaSitemapConfig, - * ewz_recaptcha?: EwzRecaptchaConfig, * tiime_new_relic?: TiimeNewRelicConfig, * debug?: DebugConfig, * web_profiler?: WebProfilerConfig, @@ -1880,7 +1851,6 @@ * knpu_oauth2_client?: KnpuOauth2ClientConfig, * jms_serializer?: JmsSerializerConfig, * presta_sitemap?: PrestaSitemapConfig, - * ewz_recaptcha?: EwzRecaptchaConfig, * tiime_new_relic?: TiimeNewRelicConfig, * valinor?: ValinorConfig, * doctrine?: DoctrineConfig, @@ -1902,7 +1872,6 @@ * knpu_oauth2_client?: KnpuOauth2ClientConfig, * jms_serializer?: JmsSerializerConfig, * presta_sitemap?: PrestaSitemapConfig, - * ewz_recaptcha?: EwzRecaptchaConfig, * tiime_new_relic?: TiimeNewRelicConfig, * debug?: DebugConfig, * web_profiler?: WebProfilerConfig, diff --git a/sources/AppBundle/Association/Form/CompanyMemberType.php b/sources/AppBundle/Association/Form/CompanyMemberType.php index 1406482ce..5db85785e 100644 --- a/sources/AppBundle/Association/Form/CompanyMemberType.php +++ b/sources/AppBundle/Association/Form/CompanyMemberType.php @@ -7,8 +7,7 @@ use AppBundle\Association\CompanyMembership\SubscriptionManagement; use AppBundle\Association\Entity\CompanyMemberInvitation; use AppBundle\Association\Entity\CompanyMember; -use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType; -use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrue as RecaptchaIsValid; +use AppBundle\Recaptcha\RecaptchaType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\CollectionType; @@ -118,13 +117,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void }), ], ]) - ->add('recaptcha', EWZRecaptchaType::class, [ - 'label' => false, - 'mapped' => false, - 'constraints' => [ - new RecaptchaIsValid(), - ], - ]) + ->add('recaptcha', RecaptchaType::class, ['label' => false]) ->add('save', SubmitType::class, ['label' => 'saveMembership']) ; diff --git a/sources/AppBundle/Event/Form/LeadType.php b/sources/AppBundle/Event/Form/LeadType.php index 26ffd0cba..010005e9d 100644 --- a/sources/AppBundle/Event/Form/LeadType.php +++ b/sources/AppBundle/Event/Form/LeadType.php @@ -5,8 +5,7 @@ namespace AppBundle\Event\Form; use AppBundle\Event\Model\Lead; -use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType; -use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrue as RecaptchaIsValid; +use AppBundle\Recaptcha\RecaptchaType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\EmailType; @@ -31,13 +30,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'choices' => ['fr' => 'fr', 'en' => 'en'], 'multiple' => false, ]) - ->add('recaptcha', EWZRecaptchaType::class, [ - 'label' => 'Vérification', - 'mapped' => false, - 'constraints' => [ - new RecaptchaIsValid(), - ], - ]) + ->add('recaptcha', RecaptchaType::class, ['label' => 'Vérification']) ; } diff --git a/sources/AppBundle/Event/Form/SpeakerSuggestionType.php b/sources/AppBundle/Event/Form/SpeakerSuggestionType.php index 5697e86d9..a82af0ca0 100644 --- a/sources/AppBundle/Event/Form/SpeakerSuggestionType.php +++ b/sources/AppBundle/Event/Form/SpeakerSuggestionType.php @@ -4,8 +4,7 @@ namespace AppBundle\Event\Form; -use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType; -use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrue as RecaptchaIsValid; +use AppBundle\Recaptcha\RecaptchaType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; @@ -66,13 +65,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ], ], ) - ->add('recaptcha', EWZRecaptchaType::class, [ - 'label' => 'Vérification', - 'mapped' => false, - 'constraints' => [ - new RecaptchaIsValid(), - ], - ]) + ->add('recaptcha', RecaptchaType::class, ['label' => 'Vérification']) ->add('save', SubmitType::class, ['label' => 'Suggérer']) ; } diff --git a/sources/AppBundle/Recaptcha/IsValidRecaptcha.php b/sources/AppBundle/Recaptcha/IsValidRecaptcha.php new file mode 100644 index 000000000..af0c3f042 --- /dev/null +++ b/sources/AppBundle/Recaptcha/IsValidRecaptcha.php @@ -0,0 +1,19 @@ +enabled) { + return; + } + + $request = $this->requestStack->getMainRequest(); + $token = $request?->request->getString(self::TOKEN_FIELD) ?? ''; + + if ($token === '') { + $this->context->buildViolation($constraint->message)->addViolation(); + + return; + } + + try { + $result = $this->httpClient->request('POST', self::VERIFY_URL, [ + 'body' => [ + 'secret' => $this->secretKey, + 'response' => $token, + 'remoteip' => $request?->getClientIp(), + ], + ])->toArray(); + } catch (HttpClientExceptionInterface $e) { + $this->logger->error('Vérification reCAPTCHA impossible', ['exception' => $e]); + $result = []; + } + + if (($result['success'] ?? false) !== true) { + $this->context->buildViolation($constraint->message)->addViolation(); + } + } +} diff --git a/sources/AppBundle/Recaptcha/RecaptchaType.php b/sources/AppBundle/Recaptcha/RecaptchaType.php new file mode 100644 index 000000000..ee7416fda --- /dev/null +++ b/sources/AppBundle/Recaptcha/RecaptchaType.php @@ -0,0 +1,51 @@ + + */ +class RecaptchaType extends AbstractType +{ + public function __construct( + #[Autowire('%env(RECAPTCHA_PUBLIC_KEY)%')] + private readonly string $publicKey, + #[Autowire('%app.recaptcha.enabled%')] + private readonly bool $enabled, + ) {} + + #[\Override] + public function buildView(FormView $view, FormInterface $form, array $options): void + { + $view->vars['recaptcha_enabled'] = $this->enabled; + $view->vars['recaptcha_public_key'] = $this->publicKey; + } + + #[\Override] + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'mapped' => false, + 'constraints' => [new IsValidRecaptcha()], + ]); + } + + #[\Override] + public function getParent(): string + { + return TextType::class; + } +} diff --git a/templates/event/speaker-suggestion/index.html.twig b/templates/event/speaker-suggestion/index.html.twig index 19c6c5149..43a12bef0 100644 --- a/templates/event/speaker-suggestion/index.html.twig +++ b/templates/event/speaker-suggestion/index.html.twig @@ -48,6 +48,7 @@
+ {{ form_errors(form.recaptcha) }} {{ form_widget(form.recaptcha) }}
diff --git a/templates/form_theme.html.twig b/templates/form_theme.html.twig index 352a281b2..b71beabf0 100644 --- a/templates/form_theme.html.twig +++ b/templates/form_theme.html.twig @@ -55,3 +55,10 @@ {%- endif -%} {%- endblock form_errors -%} + +{% block recaptcha_widget %} + {% if recaptcha_enabled %} + +
+ {% endif %} +{% endblock recaptcha_widget %} diff --git a/tests/unit/AppBundle/Association/Form/CompanyMemberTypeTest.php b/tests/unit/AppBundle/Association/Form/CompanyMemberTypeTest.php index c9af9fca0..183fcee38 100644 --- a/tests/unit/AppBundle/Association/Form/CompanyMemberTypeTest.php +++ b/tests/unit/AppBundle/Association/Form/CompanyMemberTypeTest.php @@ -7,15 +7,13 @@ use AppBundle\Association\Entity\CompanyMemberInvitation; use AppBundle\Association\Form\CompanyMemberType; use AppBundle\Association\Entity\CompanyMember; -use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType; -use EWZ\Bundle\RecaptchaBundle\Locale\LocaleResolver; +use AppBundle\Recaptcha\RecaptchaType; use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; use PHPUnit\Framework\Attributes\Test; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\PreloadedExtension; use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Form\Test\TypeTestCase; -use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Validator\Validation; /** @@ -27,15 +25,8 @@ class CompanyMemberTypeTest extends TypeTestCase { protected function getExtensions(): array { - $recaptcha = new EWZRecaptchaType( - 'public-key', - false, - false, - new LocaleResolver('fr', false, new RequestStack()), - ); - return [ - new PreloadedExtension([$recaptcha], []), + new PreloadedExtension([new RecaptchaType('public-key', false)], []), // TypeTestCase ne la charge pas, or l'option `constraints` en dépend. new ValidatorExtension(Validation::createValidatorBuilder()->enableAttributeMapping()->getValidator()), ]; diff --git a/tests/unit/AppBundle/Recaptcha/IsValidRecaptchaValidatorTest.php b/tests/unit/AppBundle/Recaptcha/IsValidRecaptchaValidatorTest.php new file mode 100644 index 000000000..9d6e88bd6 --- /dev/null +++ b/tests/unit/AppBundle/Recaptcha/IsValidRecaptchaValidatorTest.php @@ -0,0 +1,144 @@ + + */ +#[AllowMockObjectsWithoutExpectations] // ConstraintValidatorTestCase mocke le validator contextuel en interne +final class IsValidRecaptchaValidatorTest extends ConstraintValidatorTestCase +{ + private MockHttpClient $httpClient; + private RequestStack $requestStack; + private BufferingLogger $logger; + + protected function createValidator(): IsValidRecaptchaValidator + { + $this->httpClient = new MockHttpClient(); + $this->requestStack = new RequestStack(); + $this->logger = new BufferingLogger(); + + return new IsValidRecaptchaValidator($this->httpClient, $this->requestStack, 'cle-secrete', true, $this->logger); + } + + #[Test] + public function unJetonAccepteParGoogleNeProduitAucuneViolation(): void + { + $response = new JsonMockResponse(['success' => true]); + $this->httpClient->setResponseFactory([$response]); + $this->submitToken('jeton-du-widget'); + + $this->validator->validate(null, new IsValidRecaptcha()); + + $this->assertNoViolation(); + self::assertSame('POST', $response->getRequestMethod()); + self::assertSame('https://www.google.com/recaptcha/api/siteverify', $response->getRequestUrl()); + parse_str($response->getRequestOptions()['body'], $body); + self::assertSame( + ['secret' => 'cle-secrete', 'response' => 'jeton-du-widget', 'remoteip' => '203.0.113.7'], + $body, + ); + } + + #[Test] + public function unJetonRefuseParGoogleProduitUneViolation(): void + { + $this->httpClient->setResponseFactory([ + new JsonMockResponse(['success' => false, 'error-codes' => ['invalid-input-response']]), + ]); + $this->submitToken('jeton-expire'); + + $this->validator->validate(null, new IsValidRecaptcha()); + + $this->buildViolation((new IsValidRecaptcha())->message)->assertRaised(); + } + + /** + * Formulaire posté sans passer par le widget (robot, JS bloqué) : inutile d'interroger Google. + */ + #[Test] + public function sansJetonOnProduitUneViolationSansAppelerGoogle(): void + { + $this->submitToken(''); + + $this->validator->validate(null, new IsValidRecaptcha()); + + self::assertSame(0, $this->httpClient->getRequestsCount()); + $this->buildViolation((new IsValidRecaptcha())->message)->assertRaised(); + } + + /** + * Désactivé en env test : le widget n'est pas affiché, le formulaire doit passer quand même. + */ + #[Test] + public function desactiveOnAccepteToutSansAppelerGoogle(): void + { + $this->validator = new IsValidRecaptchaValidator($this->httpClient, $this->requestStack, 'cle-secrete', false, $this->logger); + $this->validator->initialize($this->context); + $this->submitToken(''); + + $this->validator->validate(null, new IsValidRecaptcha()); + + self::assertSame(0, $this->httpClient->getRequestsCount()); + $this->assertNoViolation(); + } + + /** + * Si on ne peut pas vérifier le captcha, on refuse le formulaire plutôt que de laisser passer + * un robot, sans pour autant afficher une page d'erreur 500. L'erreur est loguée pour + * qu'une panne côté Google se voie en prod. + */ + #[Test] + #[DataProvider('errorResponses')] + public function googleEnErreurProduitUneViolationEtLogueLErreur(MockResponse $response): void + { + $this->httpClient->setResponseFactory([$response]); + $this->submitToken('jeton-du-widget'); + + $this->validator->validate(null, new IsValidRecaptcha()); + + $this->buildViolation((new IsValidRecaptcha())->message)->assertRaised(); + $logs = $this->logger->cleanLogs(); + self::assertCount(1, $logs); + [$level, $message, $context] = $logs[0]; + self::assertSame(LogLevel::ERROR, $level); + self::assertSame('Vérification reCAPTCHA impossible', $message); + self::assertInstanceOf(\Throwable::class, $context['exception'] ?? null); + } + + /** + * @return iterable + */ + public static function errorResponses(): iterable + { + yield 'erreur réseau' => [new MockResponse(info: ['error' => 'Could not resolve host: www.google.com'])]; + yield 'erreur serveur' => [new MockResponse('', ['http_code' => 503])]; + yield 'réponse illisible' => [new MockResponse('Service Unavailable')]; + } + + private function submitToken(string $token): void + { + $this->requestStack->push(Request::create( + '/formulaire', + 'POST', + [IsValidRecaptchaValidator::TOKEN_FIELD => $token], + server: ['REMOTE_ADDR' => '203.0.113.7'], + )); + } +} diff --git a/translations/validators.fr.yml b/translations/validators.fr.yml index f3e4bfe18..d4d688c41 100644 --- a/translations/validators.fr.yml +++ b/translations/validators.fr.yml @@ -9,3 +9,4 @@ 'Please, upload a photo.': "Veuillez ajouter une photo de profil." 'You can only order one ticket "{{ ticket_pretty_name }}".': Vous ne pouvez commander qu'un seul billet "{{ ticket_pretty_name }}" 'You can only order one early bird ticket "{{ ticket_pretty_name }}".': Vous ne pouvez commander qu'un seul billet early bird "{{ ticket_pretty_name }}" +'This value is not a valid captcha.': 'Le captcha est invalide.'