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] Fix RateLimiter callback return substitution (#44820) #45611

Merged
merged 2 commits into from
Jan 12, 2023

Conversation

a-bashtannik
Copy link
Contributor

This breaking update allows users to control return values explicitly without converting to boolean and fixes the substitution of false with true.

Bug description:

The RateLimiter::attempt method contains ?: operator and casts the return value of $callback function to true for all list of values considered as false.

    public function attempt($key, $maxAttempts, Closure $callback, $decaySeconds = 60)
    {
        if ($this->tooManyAttempts($key, $maxAttempts)) {
            return false;
        }

        return tap($callback() ?: true, function () use ($key, $decaySeconds) {
            $this->hit($key, $decaySeconds);
        });
    }

Steps To Reproduce:

$return = RateLimiter::attempt('key', 10, fn() => false, 1); // $return = true, not false

$return = RateLimiter::attempt('key', 10, fn() => [], 1); // $return = true, not []
$return = RateLimiter::attempt('key', 10, fn() => 0, 1); // $return = true, not 0
$return = RateLimiter::attempt('key', 10, fn() => 0.0, 1); // $return = true, not 0.0
$return = RateLimiter::attempt('key', 10, fn() => "", 1); // $return = true, not an empty string

// etc.

Case: 3rd-party APIs may return empty arrays as a successful response.

Brings backward incompatibility to those who depend on true return.

This breaking update allows users to control return values explicitly without converting to bool.
@cheros989
Copy link

We had a problem already because attempt returns not exact value you return from closure. It does cast! But from the documentation it SHOULD return exactly the value you return from closure (3d parameter).

@taylorotwell taylorotwell merged commit 7a57619 into laravel:10.x Jan 12, 2023
@a-bashtannik a-bashtannik deleted the 10.x branch January 12, 2023 16:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants