-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathRateLimitAnnotationListener.php
More file actions
215 lines (175 loc) · 7.46 KB
/
Copy pathRateLimitAnnotationListener.php
File metadata and controls
215 lines (175 loc) · 7.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?php
namespace Noxlogic\RateLimitBundle\EventListener;
use Noxlogic\RateLimitBundle\Annotation\RateLimit;
use Noxlogic\RateLimitBundle\Events\BlockEvent;
use Noxlogic\RateLimitBundle\Events\GenerateKeyEvent;
use Noxlogic\RateLimitBundle\Events\GetResponseEvent;
use Noxlogic\RateLimitBundle\Events\RateLimitEvents;
use Noxlogic\RateLimitBundle\Service\RateLimitService;
use Noxlogic\RateLimitBundle\Util\PathLimitProcessor;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Route;
class RateLimitAnnotationListener extends BaseListener
{
/**
* @var eventDispatcherInterface
*/
protected $eventDispatcher;
/**
* @var \Noxlogic\RateLimitBundle\Service\RateLimitService
*/
protected $rateLimitService;
/**
* @var \Noxlogic\RateLimitBundle\Util\PathLimitProcessor
*/
protected $pathLimitProcessor;
/**
* @param RateLimitService $rateLimitService
*/
public function __construct(
EventDispatcherInterface $eventDispatcher,
RateLimitService $rateLimitService,
PathLimitProcessor $pathLimitProcessor
) {
//todo:use an event dispatcher passed into onKernelController
$this->eventDispatcher = $eventDispatcher;
$this->rateLimitService = $rateLimitService;
$this->pathLimitProcessor = $pathLimitProcessor;
}
/**
* @param FilterControllerEvent $event
*/
public function onKernelController(FilterControllerEvent $event)
{
// Skip if the bundle isn't enabled (for instance in test environment)
if( ! $this->getParameter('enabled', true)) {
return;
}
// Skip if we aren't the main request
if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
return;
}
// Find the best match
$annotations = $event->getRequest()->attributes->get('_x-rate-limit', array());
$rateLimit = $this->findBestMethodMatch($event->getRequest(), $annotations);
// No matching annotation found
if (! $rateLimit) {
return;
}
$key = $this->getKey($event, $rateLimit, $annotations);
// Ratelimit the call
$rateLimitInfo = $this->rateLimitService->limitRate($key);
if (! $rateLimitInfo) {
// Create new rate limit entry for this call
$rateLimitInfo = $this->rateLimitService->createRate($key, $rateLimit->getLimit(), $rateLimit->getPeriod());
if (! $rateLimitInfo) {
// @codeCoverageIgnoreStart
return;
// @codeCoverageIgnoreEnd
}
}
// Store the current rating info in the request attributes
$request = $event->getRequest();
$request->attributes->set('rate_limit_info', $rateLimitInfo);
// Reset the rate limits
if(!$rateLimitInfo->isBlocked() && time() >= $rateLimitInfo->getResetTimestamp()) {
$this->rateLimitService->resetRate($key);
$rateLimitInfo = $this->rateLimitService->createRate($key, $rateLimit->getLimit(), $rateLimit->getPeriod());
if (! $rateLimitInfo) {
// @codeCoverageIgnoreStart
return;
// @codeCoverageIgnoreEnd
}
}
// When we exceeded our limit, return a custom error response
if (!$rateLimitInfo->isBlocked() && $rateLimitInfo->getCalls() > $rateLimitInfo->getLimit()) {
$this->rateLimitService->setBlock(
$rateLimitInfo,
$rateLimit->getBlockPeriod() > 0 ? $rateLimit->getBlockPeriod() : $rateLimit->getPeriod()
);
$this->eventDispatcher->dispatch(RateLimitEvents::BLOCK_AFTER, new BlockEvent($rateLimitInfo, $request));
}
if ($rateLimitInfo->isBlocked()) {
// Throw an exception if configured.
if ($this->getParameter('rate_response_exception')) {
$class = $this->getParameter('rate_response_exception');
throw new $class($this->getParameter('rate_response_message'), $this->getParameter('rate_response_code'));
}
$response = new Response(
$this->getParameter('rate_response_message'),
$this->getParameter('rate_response_code')
);
$eventResponse = new GetResponseEvent($request, $rateLimitInfo);
$this->eventDispatcher->dispatch(RateLimitEvents::RESPONSE_SENDING_BEFORE, $eventResponse);
if ($eventResponse->hasResponse()) {
$response = $eventResponse->getResponse();
}
$event->setController(function () use ($response) {
// @codeCoverageIgnoreStart
return $response;
// @codeCoverageIgnoreEnd
});
$event->stopPropagation();
}
}
/**
* @param RateLimit[] $annotations
*/
protected function findBestMethodMatch(Request $request, array $annotations)
{
// Empty array, check the path limits
if (count($annotations) == 0) {
return $this->pathLimitProcessor->getRateLimit($request);
}
$best_match = null;
foreach ($annotations as $annotation) {
// cast methods to array, even method holds a string
$methods = is_array($annotation->getMethods()) ? $annotation->getMethods() : array($annotation->getMethods());
if (in_array($request->getMethod(), $methods)) {
$best_match = $annotation;
}
// Only match "default" annotation when we don't have a best match
if (count($annotation->getMethods()) == 0 && $best_match == null) {
$best_match = $annotation;
}
}
return $best_match;
}
private function getKey(FilterControllerEvent $event, RateLimit $rateLimit, array $annotations)
{
// Let listeners manipulate the key
$keyEvent = new GenerateKeyEvent($event->getRequest());
$rateLimitMethods = join('.', $rateLimit->getMethods());
$keyEvent->addToKey($rateLimitMethods);
$rateLimitAlias = count($annotations) === 0
? str_replace('/', '.', $this->pathLimitProcessor->getMatchedPath($event->getRequest()))
: $this->getAliasForRequest($event);
$keyEvent->addToKey($rateLimitAlias);
$this->eventDispatcher->dispatch(RateLimitEvents::GENERATE_KEY, $keyEvent);
return $keyEvent->getKey();
}
private function getAliasForRequest(FilterControllerEvent $event)
{
if (($route = $event->getRequest()->attributes->get('_route'))) {
return $route;
}
$controller = $event->getController();
if (is_string($controller) && false !== strpos($controller, '::')) {
$controller = explode('::', $controller);
}
if (is_array($controller)) {
return str_replace('\\', '.', is_string($controller[0]) ? $controller[0] : get_class($controller[0])) . '.' . $controller[1];
}
if ($controller instanceof \Closure) {
return 'closure';
}
if (is_object($controller)) {
return str_replace('\\', '.', get_class($controller[0]));
}
return 'other';
}
}