Completed
Pull Request — master (#37)
by Thierry
05:33
created

VerifyRequestSubscriber::getVerifyingKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace lepiaf\SapientBundle\EventSubscriber;
5
6
use lepiaf\SapientBundle\Exception\VerifySignatureException;
7
use lepiaf\SapientBundle\Service\PublicKeyGetter;
8
use ParagonIE\ConstantTime\Base64UrlSafe;
9
use ParagonIE\Sapient\CryptographyKeys\SigningPublicKey;
10
use ParagonIE\Sapient\Sapient;
11
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
12
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
15
use Symfony\Component\HttpKernel\KernelEvents;
16
17
class VerifyRequestSubscriber implements EventSubscriberInterface
18
{
19
    /**
20
     * @var PublicKeyGetter
21
     */
22
    private $publicKeyGetter;
23
24
    /**
25
     * @var Sapient
26
     */
27
    private $sapient;
28
29
    /**
30
     * @var DiactorosFactory
31
     */
32
    private $diactorosFactory;
33
34 2
    public function __construct(DiactorosFactory $diactorosFactory, Sapient $sapient, PublicKeyGetter $publicKeyGetter)
35
    {
36 2
        $this->diactorosFactory = $diactorosFactory;
37 2
        $this->sapient = $sapient;
38 2
        $this->publicKeyGetter = $publicKeyGetter;
39 2
    }
40
41 1
    public static function getSubscribedEvents()
42
    {
43
        return [
44 1
            KernelEvents::REQUEST => ['verifyRequest', -110],
45
        ];
46
    }
47
48 2
    public function verifyRequest(GetResponseEvent $event): void
49
    {
50 2
        $publicKey = $this->getVerifyingKey($event->getRequest());
51 2
        $psrRequest = $this->diactorosFactory->createRequest($event->getRequest());
52
        try {
53 2
            $this->sapient->verifySignedRequest(
54 2
                $psrRequest,
55 2
                new SigningPublicKey(Base64UrlSafe::decode($publicKey))
56
            );
57 1
        } catch (\SodiumException $sodiumException) {
58
            throw new VerifySignatureException('Cannot verify signature in request.');
59
        }
60 1
    }
61
62 2
    private function getVerifyingKey(Request $request): string
63
    {
64 2
        $psrRequest = $this->diactorosFactory->createRequest($request);
65
66 2
        return $this->publicKeyGetter->getVerifyingKeyFromRequest($psrRequest);
67
    }
68
}
69