Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[RateLimiter] Throws strange error about DateTimeImmutable when using sliding_window since Symfony 5.4 #45254

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

Closed
wornet-aer opened this issue Jan 31, 2022 · 2 comments

Comments

@wornet-aer
Copy link

wornet-aer commented Jan 31, 2022

Symfony version(s) affected

5.4.*

Description

We've currently updated our environment from Symfony 5.3 to 5.4 and are expieriencing strange RateLimiter errors when using sliding_window setting. When using Symfony 5.3 there were zero problems with using sliding_window.

We are using Symfony for an API backend and the error occurs after 1-2h of runtime. Which is really strange... :(

The logfile states the following error:

Exception occurred: Return value of Symfony\Component\RateLimiter\Policy\SlidingWindow::getRetryAfter() must be an instance of DateTimeImmutable, bool returned (Class: TypeError) Trace: #0 /var/www/vhosts/backend/sources/vendor/symfony/rate-limiter/Policy/SlidingWindowLimiter.php(77): Symfony\Component\RateLimiter\Policy\SlidingWindow->getRetryAfter()

How to reproduce

rate_limiter.yaml:

framework:
    rate_limiter:
        authentication_failed_api:
            policy: 'fixed_window'
            limit: 5
            interval: '60 minutes'

RateLimiter in CustomAuthenticator:

class BasicAuthAuthenticator extends AbstractAuthenticator
{

    /**
     * @var UserPasswordHasherInterface
     */
    protected $passwordHasher;

    /**
     * @var ParameterBagInterface
     */
    private $params;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var EntityManagerInterface
     */
    protected $em;

    /**
     * @var RateLimiterFactory
     */
    protected $rateLimiter;


    public function __construct(
        UserPasswordHasherInterface $passwordHasher,
        ParameterBagInterface $params,
        LoggerInterface $logger,
        EntityManagerInterface $entityManagerInterface,
        RateLimiterFactory $authenticationFailedApiLimiter
    ) {
        $this->passwordHasher = $passwordHasher;
        $this->params = $params;
        $this->logger = $logger;
        $this->em = $entityManagerInterface;
        $this->rateLimiter = $authenticationFailedApiLimiter;
    }

    /**    
     *@see AuthenticatorInterface#authenticate(Request)
     * @throws AuthenticationException
     * @throws TooManyRequestsException If Client-IP hit rate-limit
     * @return Passport
     */
    public function authenticate(Request $request): Passport
    {
        $clientIp = $request->getClientIp();
        $limiter = $this->rateLimiter->create($clientIp);

        $ipWhitelist = explode(',', $this->params->get(ConfigurationKeys::AUTH_BRUTEFORCE_WHITELIST_NETS));

        if (!IpUtils::checkIp($clientIp, $ipWhitelist) && false === $limiter->consume(1)->isAccepted()) {
            $this->logger->warning("Authentication failed: Brute-Force limit for IP " . $clientIp . " reached. IP-Address has been temporary blocked/banned now.");
            throw new TooManyRequestsException("Too many failed login attempts. Please try again later!");
        }

        # [...]

        return new Passport(new UserBadge($username), new PasswordCredentials($password));
    }

    /**
     * @see AuthenticatorInterface#onAuthenticationSuccess(Request,TokenInterface,string)
     * @param string $providerKey The provider (i.e. firewall) key
     * @return Response|null Immer null, weil dann der Request einfach weitergeführt wird.
     */
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): ?Response
    {
        /** @var PortalUserInterface $user  */
        $user = $token->getUser();
        $realUser = $user->getUser();
        $clientIp = $request->getClientIp();

        $limiter = $this->rateLimiter->create($clientIp);
        $limiter->reset();

        # [...]

        return null;
    }
    
}

Possible Solution

When using fixed_window instead, the error doesn't occur and everything works smooth.

Additional Context

No response

@wouterj
Copy link
Member

wouterj commented Jan 31, 2022

Hi!

This looks a lot like the error that was fixed by #44941 (released in 5.4.3). Can you please check you're using the latest 5.4 release?

@wornet-aer
Copy link
Author

Hi wouterj!

Thanks a lot for your blazingly fast response. I had updated our environment before the weekend, so it might be that I didn't have the 5.4.3 version yet - well, I wasn't: symfony/rate-limiter v5.4.2 ! v5.4.3.

Sorry for the duplicate Issue. I've searched several times but may have used the wrong keywords.
I think we can consider this as fixed then. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants