Passed
Push — master ( 44ae05...a9392a )
by MusikAnimal
11:19
created

RateLimitSubscriber::onKernelController()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 50
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 36.2741

Importance

Changes 0
Metric Value
cc 9
eloc 23
nc 6
nop 1
dl 0
loc 50
ccs 7
cts 23
cp 0.3043
crap 36.2741
rs 8.0555
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the RateLimitSubscriber class.
4
 */
5
6
declare(strict_types = 1);
7
8
namespace AppBundle\EventSubscriber;
9
10
use AppBundle\Helper\I18nHelper;
11
use DateInterval;
12
use Symfony\Component\DependencyInjection\ContainerInterface;
13
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
16
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
17
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
18
use Symfony\Component\HttpKernel\KernelEvents;
19
20
/**
21
 * A RateLimitSubscriber checks to see if users are exceeding usage limitations.
22
 */
23
class RateLimitSubscriber implements EventSubscriberInterface
24
{
25
26
    /** @var ContainerInterface The DI container. */
27
    protected $container;
28
29
    /** @var I18nHelper For i18n and l10n. */
30
    protected $i18n;
31
32
    /** @var int Number of requests allowed in time period */
33
    protected $rateLimit;
34
35
    /** @var int Number of minutes during which $rateLimit requests are permitted */
36
    protected $rateDuration;
37
38
    /**
39
     * Save the container for later use.
40
     * @param ContainerInterface $container The DI container.
41
     * @param I18nHelper $i18n
42
     */
43 15
    public function __construct(ContainerInterface $container, I18nHelper $i18n)
44
    {
45 15
        $this->container = $container;
46 15
        $this->i18n = $i18n;
47 15
    }
48
49
    /**
50
     * Register our interest in the kernel.controller event.
51
     * @return string[]
52
     */
53 1
    public static function getSubscribedEvents(): array
54
    {
55
        return [
56 1
            KernelEvents::CONTROLLER => 'onKernelController',
57
        ];
58
    }
59
60
    /**
61
     * Check if the current user has exceeded the configured usage limitations.
62
     * @param FilterControllerEvent $event The event.
63
     */
64 15
    public function onKernelController(FilterControllerEvent $event): void
65
    {
66 15
        $this->rateLimit = (int) $this->container->getParameter('app.rate_limit_count');
67 15
        $this->rateDuration = (int) $this->container->getParameter('app.rate_limit_time');
68 15
        $request = $event->getRequest();
69
70 15
        $this->checkBlacklist($request);
71
72
        // Zero values indicate the rate limiting feature should be disabled.
73 15
        if (0 === $this->rateLimit || 0 === $this->rateDuration) {
74 15
            return;
75
        }
76
77
        $controller = $event->getController();
78
        $loggedIn = (bool) $this->container->get('session')->get('logged_in_user');
79
        $isApi = substr($controller[1], -3);
80
81
        /**
82
         * Rate limiting will not apply to these actions
83
         * @var array
84
         */
85
        $actionWhitelist = [
86
            'indexAction', 'showAction', 'aboutAction', 'recordUsageAction', 'loginAction', 'oauthCallbackAction',
87
        ];
88
89
        // No rate limits on lightweight pages, logged in users, subrequests or API requests.
90
        if (in_array($controller[1], $actionWhitelist) || $loggedIn || false === $event->isMasterRequest() || $isApi) {
91
            return;
92
        }
93
94
        // Build and fetch cache key based on session ID.
95
        $sessionId = $request->getSession()->getId();
96
        $cacheKey = 'ratelimit.'.$sessionId;
97
98
        /** @var \Symfony\Component\Cache\Adapter\TraceableAdapter $cache */
99
        $cache = $this->container->get('cache.app');
100
        $cacheItem = $cache->getItem($cacheKey);
101
102
        // If increment value already in cache, or start with 1.
103
        $count = $cacheItem->isHit() ? (int) $cacheItem->get() + 1 : 1;
104
105
        // Check if limit has been exceeded, and if so, throw an error.
106
        if ($count > $this->rateLimit) {
107
            $this->denyAccess('Exceeded rate limitation');
108
        }
109
110
        // Reset the clock on every request.
111
        $cacheItem->set($count)
112
            ->expiresAfter(new DateInterval('PT'.$this->rateDuration.'M'));
113
        $cache->save($cacheItem);
114
    }
115
116
    /**
117
     * Check the request against blacklisted URIs and user agents
118
     * @param Request $request
119
     */
120 15
    private function checkBlacklist(Request $request): void
121
    {
122
        // First check user agent and URI blacklists
123 15
        if (!$this->container->hasParameter('request_blacklist')) {
124 15
            return;
125
        }
126
127
        $blacklist = $this->container->getParameter('request_blacklist');
128
        $ua = (string)$request->headers->get('User-Agent');
129
        $referer = (string)$request->headers->get('referer');
130
        $uri = $request->getRequestUri();
131
132
        foreach ($blacklist as $name => $item) {
133
            $match = false;
134
135
            if (isset($item['user_agent'])) {
136
                $match = $item['user_agent'] === $ua;
137
            }
138
            if (isset($item['user_agent_pattern'])) {
139
                $match = 1 === preg_match('/'.$item['user_agent_pattern'].'/', $ua);
140
            }
141
            if (isset($item['referer'])) {
142
                $match = $item['referer'] === $referer;
143
            }
144
            if (isset($item['referer_pattern'])) {
145
                $match = 1 === preg_match('/'.$item['referer_pattern'].'/', $referer);
146
            }
147
            if (isset($item['uri'])) {
148
                $match = $item['uri'] === $uri;
149
            }
150
            if (isset($item['uri_pattern'])) {
151
                $match = 1 === preg_match('/'.$item['uri_pattern'].'/', $uri);
152
            }
153
154
            if ($match) {
155
                $this->denyAccess("Matched blacklist entry `$name`", true);
156
            }
157
        }
158
    }
159
160
    /**
161
     * Throw exception for denied access due to spider crawl or hitting usage limits.
162
     * @param string $logComment Comment to include with the log entry.
163
     * @param bool $blacklist Changes the messaging to say access was denied due to abuse, rather than rate limiting.
164
     * @throws TooManyRequestsHttpException
165
     * @throws AccessDeniedHttpException
166
     */
167
    private function denyAccess(string $logComment, bool $blacklist = false): void
168
    {
169
        // Log the denied request
170
        $logger = $this->container->get($blacklist ? 'monolog.logger.blacklist' : 'monolog.logger.rate_limit');
171
        $logger->info($logComment);
172
173
        if ($blacklist) {
174
            $message = $this->i18n->msg('error-denied', ['[email protected]']);
175
            throw new AccessDeniedHttpException($message, null, 999);
176
        }
177
178
        $message = $this->i18n->msg('error-rate-limit', [
179
            $this->rateDuration,
180
            "<a href='/login'>".$this->i18n->msg('error-rate-limit-login')."</a>",
181
            "<a href='https://xtools.readthedocs.io/en/stable/api' target='_blank'>" .
182
                $this->i18n->msg('api') .
183
            "</a>",
184
        ]);
185
186
        /**
187
         * TODO: Find a better way to do this.
188
         * 999 is a random, complete hack to tell error.html.twig file to treat these exceptions as having
189
         * fully safe messages that can be display with |raw. (In this case we authored the message).
190
         */
191
        throw new TooManyRequestsHttpException(600, $message, null, 999);
192
    }
193
}
194