Completed
Push — master ( 185c3a...4e19f9 )
by Indra
01:19
created

RateLimitHandler::getThrottle()   B

Complexity

Conditions 4
Paths 7

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
ccs 14
cts 14
cp 1
rs 8.6845
cc 4
eloc 15
nc 7
nop 1
crap 4
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
        return sprintf('_api_rate_limit_metadata$%s', sha1($userName && $userRole ? sprintf('%s$%s', $userRole, $userName) : $ip));
0 ignored issues
show
Bug Best Practice introduced by
The expression $userName of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
Bug Best Practice introduced by
The expression $userRole of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
106
    }
107
108 6
    public function handle(Request $request)
109
    {
110 6
        list($key, $limit, $period) = $this->getThrottle($request);
111
112 6
        $annotationReader = new AnnotationReader();
113 6
        $annotation = $annotationReader->getClassAnnotation(new \ReflectionClass($request->attributes->get('_api_resource_class')), ApiRateLimit::class);
114 6
        if (null !== $annotation) {
115 6
            $this->enabled = $annotation->enabled;
116
        }
117
118 6
        if ($this->enabled) {
119 5
            $this->decreaseRateLimitRemaining($key, $limit, $period);
120
        }
121 6
    }
122
123 5
    protected function decreaseRateLimitRemaining(string $key, int $limit, int $period)
124
    {
125 5
        $cost = 1;
126 5
        $currentTime = gmdate('U');
127
128 5
        $rateLimitInfo = $this->cacheItemPool->getItem($key);
129 5
        $rateLimit = $rateLimitInfo->get();
130 5
        if ($rateLimitInfo->isHit() && $currentTime <= $rateLimit['reset']) {
131
            // decrease existing rate limit remaining
132 2
            if ($rateLimit['remaining'] - $cost >= 0) {
133 1
                $remaining = $rateLimit['remaining'] - $cost;
134 1
                $reset = $rateLimit['reset'];
135 1
                $ttl = $rateLimit['reset'] - $currentTime;
136
            } else {
137 1
                $this->rateLimitExceeded = true;
138 1
                $this->reset = $rateLimit['reset'];
139 1
                $this->limit = $limit;
140 1
                $this->remaining = 0;
141
142 2
                return;
143
            }
144
        } else {
145
            // add / reset new rate limit remaining
146 3
            $remaining = $limit - $cost;
147 3
            $reset = $currentTime + $period;
148 3
            $ttl = $period;
149
        }
150
151
        $rateLimit = [
152 4
            'limit' => $limit,
153 4
            'remaining' => $remaining,
154 4
            'reset' => $reset,
155
        ];
156
157 4
        $rateLimitInfo->set($rateLimit);
158 4
        $rateLimitInfo->expiresAfter($ttl);
159
160 4
        $this->cacheItemPool->save($rateLimitInfo);
161
162 4
        $this->limit = $limit;
163 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...
164 4
        $this->reset = $reset;
165 4
    }
166
167 6
    private function getThrottle(Request $request)
168
    {
169 6
        $userName = null;
170 6
        $userRole = null;
171 6
        $limit = $this->throttleConfig['default']['limit'];
172 6
        $period = $this->throttleConfig['default']['period'];
173
174 6
        foreach ($this->throttleConfig['roles'] as $role => $throttle) {
175
            try {
176 2
                if ($this->authorizationChecker->isGranted($role)) {
177 1
                    $userName = $this->tokenStorage->getToken()->getUsername();
178 1
                    $userRole = $role;
179 1
                    $limit = $throttle['limit'];
180 1
                    $period = $throttle['period'];
181
182 1
                    break;
183
                }
184 1
            } catch (AuthenticationCredentialsNotFoundException $e) {
185
                // do nothing
186
            }
187
        }
188
189 6
        return [self::generateCacheKey($request->getClientIp(), $userName, $userRole), $limit, $period];
190
    }
191
}
192