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] Make the requests throttler less aggressive #20759

Merged
merged 7 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
38 changes: 13 additions & 25 deletions src/Illuminate/Cache/RateLimiter.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,35 +37,19 @@ public function __construct(Cache $cache)
*/
public function tooManyAttempts($key, $maxAttempts, $decayMinutes = 1)
{
if ($this->cache->has($key.':lockout')) {
return true;
}

if ($this->attempts($key) >= $maxAttempts) {
$this->lockout($key, $decayMinutes);
if ($this->cache->has($key.':timer')) {
return true;
} else {
$this->resetAttempts($key);

$this->resetAttempts($key);

return true;
return false;
}
}

return false;
}

/**
* Add the lockout key to the cache.
*
* @param string $key
* @param int $decayMinutes
* @return void
*/
protected function lockout($key, $decayMinutes)
{
$this->cache->add(
$key.':lockout', $this->availableAt($decayMinutes * 60), $decayMinutes
);
}

/**
* Increment the counter for a given key for a given decay time.
*
Expand All @@ -75,6 +59,10 @@ protected function lockout($key, $decayMinutes)
*/
public function hit($key, $decayMinutes = 1)
{
$this->cache->add($key.':timer', $this->availableAt($decayMinutes * 60),
$decayMinutes
);

$added = $this->cache->add($key, 0, $decayMinutes);

$hits = (int) $this->cache->increment($key);
Expand Down Expand Up @@ -123,7 +111,7 @@ public function retriesLeft($key, $maxAttempts)
}

/**
* Clear the hits and lockout for the given key.
* Clear the hits and lockout timer for the given key.
*
* @param string $key
* @return void
Expand All @@ -132,7 +120,7 @@ public function clear($key)
{
$this->resetAttempts($key);

$this->cache->forget($key.':lockout');
$this->cache->forget($key.':timer');
}

/**
Expand All @@ -143,6 +131,6 @@ public function clear($key)
*/
public function availableIn($key)
{
return $this->cache->get($key.':lockout') - $this->currentTime();
return $this->cache->get($key.':timer') - $this->currentTime();
}
}
19 changes: 5 additions & 14 deletions tests/Cache/CacheRateLimiterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,18 @@ public function tearDown()
public function testTooManyAttemptsReturnTrueIfAlreadyLockedOut()
{
$cache = m::mock(Cache::class);
$cache->shouldReceive('has')->once()->with('key:lockout')->andReturn(true);
$cache->shouldReceive('get')->once()->with('key', 0)->andReturn(1);
$cache->shouldReceive('has')->once()->with('key:timer')->andReturn(true);
$cache->shouldReceive('add')->never();
$rateLimiter = new RateLimiter($cache);

$this->assertTrue($rateLimiter->tooManyAttempts('key', 1, 1));
}

public function testTooManyAttemptsReturnsTrueIfMaxAttemptsExceeded()
{
$cache = m::mock(Cache::class);
$cache->shouldReceive('get')->once()->with('key', 0)->andReturn(10);
$cache->shouldReceive('has')->once()->with('key:lockout')->andReturn(false);
$cache->shouldReceive('add')->once()->with('key:lockout', m::type('int'), 1);
$cache->shouldReceive('forget')->once()->with('key');
$rateLimiter = new RateLimiter($cache);

$this->assertTrue($rateLimiter->tooManyAttempts('key', 1, 1));
}

public function testHitProperlyIncrementsAttemptCount()
{
$cache = m::mock(Cache::class);
$cache->shouldReceive('add')->once()->with('key:timer', m::type('int'), 1)->andReturn(true);
$cache->shouldReceive('add')->once()->with('key', 0, 1)->andReturn(true);
$cache->shouldReceive('increment')->once()->with('key')->andReturn(1);
$rateLimiter = new RateLimiter($cache);
Expand All @@ -49,6 +39,7 @@ public function testHitProperlyIncrementsAttemptCount()
public function testHitHasNoMemoryLeak()
{
$cache = m::mock(Cache::class);
$cache->shouldReceive('add')->once()->with('key:timer', m::type('int'), 1)->andReturn(true);
$cache->shouldReceive('add')->once()->with('key', 0, 1)->andReturn(false);
$cache->shouldReceive('increment')->once()->with('key')->andReturn(1);
$cache->shouldReceive('put')->once()->with('key', 1, 1);
Expand All @@ -70,7 +61,7 @@ public function testClearClearsTheCacheKeys()
{
$cache = m::mock(Cache::class);
$cache->shouldReceive('forget')->once()->with('key');
$cache->shouldReceive('forget')->once()->with('key:lockout');
$cache->shouldReceive('forget')->once()->with('key:timer');
$rateLimiter = new RateLimiter($cache);

$rateLimiter->clear('key');
Expand Down
57 changes: 57 additions & 0 deletions tests/Integration/Http/ThrottleRequestsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace Illuminate\Tests\Integration\Http;

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

/**
* @group integration
*/
class ThrottleRequestsTest extends TestCase
{
protected function getEnvironmentSetUp($app)
{
$app['config']->set('cache.default', 'redis');
}

public function setup()
{
parent::setup();

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

public function test_lock_opens_immediately_after_decay()
{
Route::get('/', function () {
return 'yes';
})->middleware(ThrottleRequests::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->assertEquals(2, $e->getHeaders()['Retry-After']);
$this->assertEquals(now()->timestamp + 2, $e->getHeaders()['X-RateLimit-Reset']);
}
}
}