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

[10.x] Add shouldHashKeys to ThrottleRequests middleware #47368

Merged
merged 7 commits into from Jun 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 32 additions & 3 deletions src/Illuminate/Routing/Middleware/ThrottleRequests.php
Expand Up @@ -23,6 +23,13 @@ class ThrottleRequests
*/
protected $limiter;

/**
* Indicates if the rate limiter keys should be hashed.
*
* @var bool
*/
protected static $shouldHashKeys = true;

/**
* Create a new request throttler.
*
Expand Down Expand Up @@ -120,7 +127,7 @@ protected function handleRequestUsingNamedLimiter($request, Closure $next, $limi
$next,
collect(Arr::wrap($limiterResponse))->map(function ($limit) use ($limiterName) {
return (object) [
'key' => md5($limiterName.$limit->key),
'key' => self::$shouldHashKeys ? md5($limiterName.$limit->key) : $limiterName.':'.$limit->key,
'maxAttempts' => $limit->maxAttempts,
'decayMinutes' => $limit->decayMinutes,
'responseCallback' => $limit->responseCallback,
Expand Down Expand Up @@ -193,9 +200,9 @@ protected function resolveMaxAttempts($request, $maxAttempts)
protected function resolveRequestSignature($request)
{
if ($user = $request->user()) {
return sha1($user->getAuthIdentifier());
return $this->formatIdentifier($user->getAuthIdentifier());
} elseif ($route = $request->route()) {
return sha1($route->getDomain().'|'.$request->ip());
return $this->formatIdentifier($route->getDomain().'|'.$request->ip());
}

throw new RuntimeException('Unable to generate the request signature. Route unavailable.');
Expand Down Expand Up @@ -299,4 +306,26 @@ protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter =
{
return is_null($retryAfter) ? $this->limiter->retriesLeft($key, $maxAttempts) : 0;
}

/**
* Format the given identifier based on the configured hashing settings.
*
* @param string $value
* @return string
*/
private function formatIdentifier($value)
{
return self::$shouldHashKeys ? sha1($value) : $value;
}

/**
* Specify whether rate limiter keys should be hashed.
*
* @param bool $shouldHashKeys
* @return void
*/
public static function shouldHashKeys(bool $shouldHashKeys = true)
{
self::$shouldHashKeys = $shouldHashKeys;
}
}