Completed
Push — master ( 4e19f9...2956a0 )
by Indra
01:30
created

RateLimitHandler::isRateLimitExceeded()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the ApiRateLimitBundle
5
 *
6
 * (c) Indra Gunawan <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Indragunawan\ApiRateLimitBundle\Service;
13
14
use Doctrine\Common\Annotations\AnnotationReader;
15
use Indragunawan\ApiRateLimitBundle\Annotation\ApiRateLimit;
16
use Psr\Cache\CacheItemPoolInterface;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
19
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
20
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
21
22
/**
23
 * @author Indra Gunawan <[email protected]>
24
 */
25
class RateLimitHandler
26
{
27
    /**
28
     * @var Cache
29
     */
30
    private $cacheItemPool;
31
32
    /**
33
     * @var TokenStorageInterface
34
     */
35
    private $tokenStorage;
36
37
    /**
38
     * @var AuthorizationCheckerInterface
39
     */
40
    private $authorizationChecker;
41
42
    /**
43
     * @var array
44
     */
45
    private $throttleConfig;
46
47
    /**
48
     * @var int
49
     */
50
    private $limit;
51
52
    /**
53
     * @var int
54
     */
55
    private $remaining;
56
57
    /**
58
     * @var int
59
     */
60
    private $reset;
61
62
    /**
63
     * @var
64
     */
65
    private $enabled = true;
66
67
    /**
68
     * @var bool
69
     */
70
    private $rateLimitExceeded = false;
71
72 6
    public function __construct(
73
        CacheItemPoolInterface $cacheItemPool,
74
        TokenStorageInterface $tokenStorage,
75
        AuthorizationCheckerInterface $authorizationChecker,
76
        array $throttleConfig
77
    ) {
78 6
        $this->cacheItemPool = $cacheItemPool;
0 ignored issues
show
Documentation Bug introduced by
It seems like $cacheItemPool of type object<Psr\Cache\CacheItemPoolInterface> is incompatible with the declared type object<Indragunawan\ApiR...itBundle\Service\Cache> of property $cacheItemPool.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
79 6
        $this->tokenStorage = $tokenStorage;
80 6
        $this->authorizationChecker = $authorizationChecker;
81 6
        $this->throttleConfig = $throttleConfig;
82 6
    }
83
84 6
    public function isEnabled()
85
    {
86 6
        return $this->enabled;
87
    }
88
89 4
    public function isRateLimitExceeded()
90
    {
91 4
        return $this->rateLimitExceeded;
92
    }
93
94 5
    public function getRateLimitInfo(): array
95
    {
96
        return [
97 5
            'limit' => $this->limit,
98 5
            'remaining' => $this->remaining,
99 5
            'reset' => $this->reset,
100
        ];
101
    }
102
103 6
    public static function generateCacheKey(string $ip, string $userName = null, string $userRole = null): string
104
    {
105 6
        if (!empty($userName) && !empty($userRole)) {
106
            return sprintf('_api_rate_limit_metadata$%s', sha1($userRole.$userName));
107
        }
108
109 6
        return sprintf('_api_rate_limit_metadata$%s', sha1($ip));
110
    }
111
112 6
    public function handle(Request $request)
113
    {
114 6
        list($key, $limit, $period) = $this->getThrottle($request);
115
116 6
        $annotationReader = new AnnotationReader();
117 6
        $annotation = $annotationReader->getClassAnnotation(new \ReflectionClass($request->attributes->get('_api_resource_class')), ApiRateLimit::class);
118 6
        if (null !== $annotation) {
119 6
            $this->enabled = $annotation->enabled;
120
        }
121
122 6
        if ($this->enabled) {
123 5
            $this->decreaseRateLimitRemaining($key, $limit, $period);
124
        }
125 6
    }
126
127 5
    protected function decreaseRateLimitRemaining(string $key, int $limit, int $period)
128
    {
129 5
        $cost = 1;
130 5
        $currentTime = gmdate('U');
131
132 5
        $rateLimitInfo = $this->cacheItemPool->getItem($key);
133 5
        $rateLimit = $rateLimitInfo->get();
134 5
        if ($rateLimitInfo->isHit() && $currentTime <= $rateLimit['reset']) {
135
            // decrease existing rate limit remaining
136 2
            if ($rateLimit['remaining'] - $cost >= 0) {
137 1
                $remaining = $rateLimit['remaining'] - $cost;
138 1
                $reset = $rateLimit['reset'];
139 1
                $ttl = $rateLimit['reset'] - $currentTime;
140
            } else {
141 1
                $this->rateLimitExceeded = true;
142 1
                $this->reset = $rateLimit['reset'];
143 1
                $this->limit = $limit;
144 1
                $this->remaining = 0;
145
146 1
                return;
147
            }
148
        } else {
149
            // add / reset new rate limit remaining
150 3
            $remaining = $limit - $cost;
151 3
            $reset = $currentTime + $period;
152 3
            $ttl = $period;
153
        }
154
155
        $rateLimit = [
156 4
            'limit' => $limit,
157 4
            'remaining' => $remaining,
158 4
            'reset' => $reset,
159
        ];
160
161 4
        $rateLimitInfo->set($rateLimit);
162 4
        $rateLimitInfo->expiresAfter($ttl);
163
164 4
        $this->cacheItemPool->save($rateLimitInfo);
165
166 4
        $this->limit = $limit;
167 4
        $this->remaining = $remaining;
0 ignored issues
show
Documentation Bug introduced by
It seems like $remaining can also be of type double. However, the property $remaining is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
168 4
        $this->reset = $reset;
169 4
    }
170
171 6
    private function getThrottle(Request $request)
172
    {
173 6
        if (null !== $token = $this->tokenStorage->getToken()) {
174
            // no anonymous
175 1
            if (is_object($token->getUser())) {
176 1
                foreach ($this->throttleConfig['roles'] as $role => $throttle) {
177
                    try {
178 1
                        if ($this->authorizationChecker->isGranted($role)) {
179 1
                            $userName = $token->getUsername();
180 1
                            $userRole = $role;
181 1
                            $limit = $throttle['limit'];
182 1
                            $period = $throttle['period'];
183
184 1
                            return [self::generateCacheKey($request->getClientIp(), $userName, $userRole), $limit, $period];
185
                        }
186
                    } catch (AuthenticationCredentialsNotFoundException $e) {
187
                        // do nothing
188
                    }
189
                }
190
            }
191
        }
192
193 5
        $limit = $this->throttleConfig['default']['limit'];
194 5
        $period = $this->throttleConfig['default']['period'];
195
196 5
        return [self::generateCacheKey($request->getClientIp()), $limit, $period];
197
    }
198
}
199