feat: add Retry-After header if needed

This commit is contained in:
Maël Gangloff
2024-08-05 22:05:32 +02:00
parent 4e6649fc68
commit 686d39da62
3 changed files with 33 additions and 10 deletions

View File

@@ -64,12 +64,13 @@ class DomainRefreshController extends AbstractController
if (false === $kernel->isDebug() && true === $this->getParameter('limited_features')) {
$limiter = $this->rdapRequestsLimiter->create($userId);
$limit = $limiter->consume();
if (false === $limiter->consume()->isAccepted()) {
if (false === $limit->isAccepted()) {
$this->logger->warning('User {username} was rate limited by the API.', [
'username' => $this->getUser()->getUserIdentifier(),
]);
throw new TooManyRequestsHttpException();
throw new TooManyRequestsHttpException($limit->getRetryAfter()->getTimestamp() - time());
}
}

View File

@@ -3,12 +3,30 @@
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\Serializer\SerializerInterface;
class MeController extends AbstractController
{
public function __invoke(): UserInterface
public function __construct(
private readonly SerializerInterface $serializer,
private readonly RateLimiterFactory $rdapRequestsLimiter,
) {
}
public function __invoke(): Response
{
return $this->getUser();
$user = $this->getUser();
$limiter = $this->rdapRequestsLimiter->create($user->getUserIdentifier());
$limit = $limiter->consume(0);
$data = $this->serializer->serialize($user, 'json', ['groups' => 'user:list']);
return new JsonResponse($data, Response::HTTP_OK, [
'eu.domainwatchdog.ratelimiter.rdap.remaining' => $limit->getRemainingTokens(),
'eu.domainwatchdog.ratelimiter.rdap.limit' => $limit->getLimit(),
], true);
}
}

View File

@@ -56,12 +56,16 @@ class RegistrationController extends AbstractController
$limiter = $this->userRegisterLimiter->create($request->getClientIp());
if (false === $this->kernel->isDebug() && false === $limiter->consume()->isAccepted()) {
$this->logger->warning('IP address {ip} was rate limited by the Registration API.', [
'ip' => $request->getClientIp(),
]);
if (false === $this->kernel->isDebug()) {
$limit = $limiter->consume();
throw new TooManyRequestsHttpException();
if (false === $limit->isAccepted()) {
$this->logger->warning('IP address {ip} was rate limited by the Registration API.', [
'ip' => $request->getClientIp(),
]);
throw new TooManyRequestsHttpException($limit->getRetryAfter()->getTimestamp() - time());
}
}
$user = $this->serializer->deserialize($request->getContent(), User::class, 'json', ['groups' => 'user:register']);