Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.5] Throttle requests with Redis #20761

Merged
merged 2 commits into from
Aug 25, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions src/Illuminate/Redis/Limiters/DurationLimiter.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ class DurationLimiter
*/
private $decay;

/**
* The timestamp of the end of the current duration.
*
* @var int
*/
public $decaysAt;

/**
* The number of remaining slots.
*
* @var int
*/
public $remaining;

/**
* Create a new duration limiter instance.
*
Expand Down Expand Up @@ -81,13 +95,19 @@ public function block($timeout, $callback = null)
/**
* Attempt to acquire the lock.
*
* @return mixed
* @return bool
*/
protected function acquire()
public function acquire()
{
return $this->redis->eval($this->luaScript(), 1,
$results = $this->redis->eval($this->luaScript(), 1,
$this->name, microtime(true), time(), $this->decay, $this->maxLocks
);

$this->decaysAt = $results[1];

$this->remaining = max(0, $results[2]);

return (bool) $results[0];
}

/**
Expand All @@ -110,14 +130,18 @@ protected function luaScript()
end

if redis.call('EXISTS', KEYS[1]) == 0 then
return reset()
return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1}
end

if ARGV[1] >= redis.call('HGET', KEYS[1], 'start') and ARGV[1] <= redis.call('HGET', KEYS[1], 'end') then
return tonumber(redis.call('HINCRBY', KEYS[1], 'count', 1)) <= tonumber(ARGV[4])
return {
tonumber(redis.call('HINCRBY', KEYS[1], 'count', 1)) <= tonumber(ARGV[4]),
redis.call('HGET', KEYS[1], 'end'),
ARGV[4] - redis.call('HGET', KEYS[1], 'count')
}
end

return reset()
return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1}
LUA;
}
}
216 changes: 216 additions & 0 deletions src/Illuminate/Routing/Middleware/ThrottleRequestsWithRedis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
<?php

namespace Illuminate\Routing\Middleware;

use Closure;
use RuntimeException;
use Illuminate\Support\Str;
use Illuminate\Support\InteractsWithTime;
use Illuminate\Redis\Limiters\DurationLimiter;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Contracts\Redis\Factory as Redis;
use Symfony\Component\HttpKernel\Exception\HttpException;

class ThrottleRequestsWithRedis
{
use InteractsWithTime;

/**
* The Redis factory implementation.
*
* @var \Illuminate\Contracts\Redis\Factory
*/
protected $redis;

/**
* The timestamp of the end of the current duration.
*
* @var int
*/
public $decaysAt;

/**
* The number of remaining slots.
*
* @var int
*/
public $remaining;

/**
* Create a new request throttler.
*
* @param \Illuminate\Contracts\Redis\Factory $redis
* @return void
*/
public function __construct(Redis $redis)
{
$this->redis = $redis;
}

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int|string $maxAttempts
* @param float|int $decayMinutes
* @return mixed
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
{
$key = $this->resolveRequestSignature($request);

$maxAttempts = $this->resolveMaxAttempts($request, $maxAttempts);

if ($this->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
throw $this->buildException($key, $maxAttempts);
}

$response = $next($request);

return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
}

/**
* Resolve the number of attempts if the user is authenticated or not.
*
* @param \Illuminate\Http\Request $request
* @param int|string $maxAttempts
* @return int
*/
protected function resolveMaxAttempts($request, $maxAttempts)
{
if (Str::contains($maxAttempts, '|')) {
$maxAttempts = explode('|', $maxAttempts, 2)[$request->user() ? 1 : 0];
}

return (int) $maxAttempts;
}

/**
* Resolve request signature.
*
* @param \Illuminate\Http\Request $request
* @return string
* @throws \RuntimeException
*/
protected function resolveRequestSignature($request)
{
if ($user = $request->user()) {
return sha1($user->getAuthIdentifier());
}

if ($route = $request->route()) {
return sha1($route->getDomain().'|'.$request->ip());
}

throw new RuntimeException(
'Unable to generate the request signature. Route unavailable.'
);
}

/**
* Create a 'too many attempts' exception.
*
* @param string $key
* @param int $maxAttempts
* @return \Symfony\Component\HttpKernel\Exception\HttpException
*/
protected function buildException($key, $maxAttempts)
{
$retryAfter = $this->decaysAt - $this->currentTime();

$headers = $this->getHeaders(
$maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
$retryAfter
);

return new HttpException(
429, 'Too Many Attempts.', null, $headers
);
}

/**
* Add the limit header information to the given response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* @param int $maxAttempts
* @param int $remainingAttempts
* @param int|null $retryAfter
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null)
{
$response->headers->add(
$this->getHeaders($maxAttempts, $remainingAttempts, $retryAfter)
);

return $response;
}

/**
* Get the limit headers information.
*
* @param int $maxAttempts
* @param int $remainingAttempts
* @param int|null $retryAfter
* @return array
*/
protected function getHeaders($maxAttempts, $remainingAttempts, $retryAfter = null)
{
$headers = [
'X-RateLimit-Limit' => $maxAttempts,
'X-RateLimit-Remaining' => $remainingAttempts,
];

if (! is_null($retryAfter)) {
$headers['Retry-After'] = $retryAfter;
$headers['X-RateLimit-Reset'] = $this->availableAt($retryAfter);
}

return $headers;
}

/**
* Calculate the number of remaining attempts.
*
* @param string $key
* @param int $maxAttempts
* @param int|null $retryAfter
* @return int
*/
protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter = null)
{
if (is_null($retryAfter)) {
return $this->remaining;
}

return 0;
}

/**
* Determine if the given key has been "accessed" too many times.
*
* @param string $key
* @param int $maxAttempts
* @param int $decayMinutes
* @return mixed
*/
protected function tooManyAttempts($key, $maxAttempts, $decayMinutes)
{
$limiter = (new DurationLimiter($this->redis, $key, $maxAttempts, $decayMinutes * 60));

$attempt = $limiter->acquire();

$this->decaysAt = $limiter->decaysAt;

$this->remaining = $limiter->remaining;

return !$attempt;
}
}
2 changes: 2 additions & 0 deletions tests/Integration/Http/ThrottleRequestsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public function setup()

public function test_lock_opens_immediately_after_decay()
{
Carbon::setTestNow(null);

Route::get('/', function () {
return 'yes';
})->middleware(ThrottleRequests::class.':2,1');
Expand Down
49 changes: 49 additions & 0 deletions tests/Integration/Http/ThrottleRequestsWithRedisTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Illuminate\Tests\Integration\Http;

use Illuminate\Support\Carbon;
use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Route;
use Illuminate\Routing\Middleware\ThrottleRequestsWithRedis;

/**
* @group integration
*/
class ThrottleRequestsWithRedisTest extends TestCase
{
public function test_lock_opens_immediately_after_decay()
{
Carbon::setTestNow(null);

resolve('redis')->flushall();

Route::get('/', function () {
return 'yes';
})->middleware(ThrottleRequestsWithRedis::class.':2,1');

$response = $this->withoutExceptionHandling()->get('/');
$this->assertEquals('yes', $response->getContent());
$this->assertEquals(2, $response->headers->get('X-RateLimit-Limit'));
$this->assertEquals(1, $response->headers->get('X-RateLimit-Remaining'));

$response = $this->withoutExceptionHandling()->get('/');
$this->assertEquals('yes', $response->getContent());
$this->assertEquals(2, $response->headers->get('X-RateLimit-Limit'));
$this->assertEquals(0, $response->headers->get('X-RateLimit-Remaining'));

Carbon::setTestNow(
Carbon::now()->addSeconds(58)
);

try {
$response = $this->withoutExceptionHandling()->get('/');
} catch (\Throwable $e) {
$this->assertEquals(429, $e->getStatusCode());
$this->assertEquals(2, $e->getHeaders()['X-RateLimit-Limit']);
$this->assertEquals(0, $e->getHeaders()['X-RateLimit-Remaining']);
$this->assertTrue(in_array($e->getHeaders()['Retry-After'], [2, 3]));
$this->assertTrue(in_array($e->getHeaders()['X-RateLimit-Reset'], [now()->timestamp + 2, now()->timestamp + 3]));
}
}
}