src/EventSubscriber/ServiceKeySubscriber.php line 40

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Security\ServiceKey;
  4. use Psr\Log\LoggerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. /**
  10.  * Refuses, with a JSON 401, every request under /internal/ that does not carry our key
  11.  * (see ServiceKey).
  12.  *
  13.  * It runs before the router and before the firewalls, so an address that names no route
  14.  * answers 401 too, and nothing about the routes can be learnt without the key. The routes
  15.  * under /internal/ have no login of their own: security.yaml leaves them out of every
  16.  * firewall, and this check is their only door.
  17.  */
  18. final class ServiceKeySubscriber implements EventSubscriberInterface
  19. {
  20.     private const PREFIX = '/internal/';
  21.     public function __construct(private ServiceKey $key, private LoggerInterface $logger)
  22.     {
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         // The router listens at priority 32 and the firewalls at 8: this runs before both.
  27.         return [KernelEvents::REQUEST => ['onKernelRequest', 512]];
  28.     }
  29.     public static function isInternal(string $path): bool
  30.     {
  31.         return $path === '/internal' || str_starts_with($path, self::PREFIX);
  32.     }
  33.     public function onKernelRequest(RequestEvent $event): void
  34.     {
  35.         if (!$event->isMainRequest()) {
  36.             return;
  37.         }
  38.         $request = $event->getRequest();
  39.         if (!self::isInternal($request->getPathInfo())) {
  40.             return;
  41.         }
  42.         if ($this->key->matches($request->headers->get(ServiceKey::HEADER))) {
  43.             return;
  44.         }
  45.         if (!$this->key->isConfigured()) {
  46.             $this->logger->error('SOCIAL_SERVICE_KEY is empty: every route under /internal/ refuses');
  47.         }
  48.         $event->setResponse(new JsonResponse(
  49.             ['error' => sprintf('A valid %s header is required', ServiceKey::HEADER)],
  50.             JsonResponse::HTTP_UNAUTHORIZED
  51.         ));
  52.     }
  53. }