Completed
Pull Request — master (#3)
by Indra
02:35
created

RateLimitHandler::generateCacheKey()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 3
eloc 2
nc 1
nop 3
crap 12
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
    public function __construct(
73
        CacheItemPoolInterface $cacheItemPool,
74
        TokenStorageInterface $tokenStorage,
75
        AuthorizationCheckerInterface $authorizationChecker,
76
        array $throttleConfig
77
    ) {
78
        $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
        $this->tokenStorage = $tokenStorage;
80
        $this->authorizationChecker = $authorizationChecker;
81
        $this->throttleConfig = $throttleConfig;
82
    }
83
84
    public function isEnabled()
85
    {
86
        return $this->enabled;
87
    }
88
89
    public function isRateLimitExceeded()
90
    {
91
        return $this->rateLimitExceeded;
92
    }
93
94
    public function getRateLimitInfo(): array
95
    {
96
        return [
97
            'limit' => $this->limit,
98
            'remaining' => $this->remaining,
99
            'reset' => $this->reset,
100
        ];
101
    }
102
103
    public static function generateCacheKey(string $ip, string $userName = null, string $userRole = null): string
104
    {
105
        return sprintf('_api_rate_limit_metadata$%s', $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
    public function handle(Request $request)
109
    {
110
        list($key, $limit, $period) = $this->getThrottle($request);
111
112
        $annotationReader = new AnnotationReader();
113
        $annotation = $annotationReader->getClassAnnotation(new \ReflectionClass($request->attributes->get('_api_resource_class')), ApiRateLimit::class);
114
        if (null !== $annotation) {
115
            $this->enabled = $annotation->enabled;
116
        }
117
118
        if ($this->enabled) {
119
            $this->decreaseRateLimitRemaining($key, $limit, $period);
120
        }
121
    }
122
123
    protected function decreaseRateLimitRemaining(string $key, int $limit, int $period)
124
    {
125
        $cost = 1;
126
        $currentTime = gmdate('U');
127
128
        $rateLimitInfo = $this->cacheItemPool->getItem($key);
129
        $rateLimit = $rateLimitInfo->get();
130
        if ($rateLimitInfo->isHit() && $currentTime <= $rateLimit['reset']) {
131
            // decrease existing rate limit remaining
132
            if ($rateLimit['remaining'] - $cost >= 0) {
133
                $remaining = $rateLimit['remaining'] - $cost;
134
                $reset = $rateLimit['reset'];
135
                $ttl = $rateLimit['reset'] - $currentTime;
136
            } else {
137
                $this->rateLimitExceeded = true;
138
                $this->reset = $rateLimit['reset'];
139
                $this->limit = $limit;
140
                $this->remaining = 0;
141
142
                return;
143
            }
144
        } else {
145
            // add / reset new rate limit remaining
146
            $remaining = $limit - $cost;
147
            $reset = $currentTime + $period;
148
            $ttl = $period;
149
        }
150
151
        $rateLimit = [
152
            'limit' => $limit,
153
            'remaining' => $remaining,
154
            'reset' => $reset,
155
        ];
156
157
        $rateLimitInfo->set($rateLimit);
158
        $rateLimitInfo->expiresAfter($ttl);
159
160
        $this->cacheItemPool->save($rateLimitInfo);
161
162
        $this->limit = $limit;
163
        $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
        $this->reset = $reset;
165
    }
166
167
    private function getThrottle(Request $request)
168
    {
169
        $userName = null;
170
        $userRole = null;
171
        $limit = $this->throttleConfig['default']['limit'];
172
        $period = $this->throttleConfig['default']['limit'];
173
174
        foreach ($this->throttleConfig['roles'] as $role => $throttle) {
175
            try {
176
                if ($this->authorizationChecker->isGranted($role)) {
177
                    $userName = $this->tokenStorage->getToken()->getUsername();
178
                    $userRole = $role;
179
                    $limit = $throttle['limit'];
180
                    $period = $throttle['period'];
181
182
                    break;
183
                }
184
            } catch (AuthenticationCredentialsNotFoundException $e) {
0 ignored issues
show
Bug introduced by
The class Symfony\Component\Securi...ntialsNotFoundException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
185
                // do nothing
186
            }
187
        }
188
189
        return [self::generateCacheKey($request->getClientIp(), $userName, $userRole), $limit, $period];
190
    }
191
}
192