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

feature: Rate limit actions #15192

Merged
merged 1 commit into from
Dec 27, 2024
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
104 changes: 104 additions & 0 deletions packages/actions/docs/07-advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,107 @@ function (Request $request, array $arguments) {
// ...
}
```

## Rate limiting actions

You can rate limit actions by using the `rateLimit()` method. This method accepts the number of attempts per minute that a user IP address can make. If the user exceeds this limit, the action will not run and a notification will be shown:

```php
use Filament\Actions\Action;

Action::make('delete')
->rateLimit(5)
```

If the action opens a modal, the rate limit will be applied when the modal is submitted.

If an action is opened with arguments or for a specific Eloquent record, the rate limit will apply to each unique combination of arguments or record for each action. The rate limit is also unique to the current Livewire component / page in a panel.

## Customizing the rate limited notification

When an action is rate limited, a notification is dispatched to the user, which indicates the rate limit.

To customize the title of this notification, use the `rateLimitedNotificationTitle()` method:

```php
use Filament\Actions\DeleteAction;

DeleteAction::make()
->rateLimit(5)
->rateLimitedNotificationTitle('Slow down!')
```

You may customize the entire notification using the `rateLimitedNotification()` method:

```php
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;

DeleteAction::make()
->rateLimit(5)
->rateLimitedNotification(
fn (TooManyRequestsException $exception): Notification => Notification::make()
->warning()
->title('Slow down!')
->body("You can try deleting again in {$exception->secondsUntilAvailable} seconds."),
)
```

### Customizing the rate limit behaviour

If you wish to customize the rate limit behaviour, you can use Laravel's [rate limiting](https://laravel.com/docs/rate-limiting#basic-usage) features and Filament's [flash notifications](../notifications/sending-notifications) together in the action.

If you want to rate limit immediately when an action modal is opened, you can do so in the `mountUsing()` method:

```php
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\RateLimiter;

Action::make('delete')
->mountUsing(function () {
if (RateLimiter::tooManyAttempts(
$rateLimitKey = 'delete:' . auth()->id(),
maxAttempts: 5,
)) {
Notification::make()
->title('Too many attempts')
->body('Please try again in ' . RateLimiter::availableIn($rateLimitKey) . ' seconds.')
->danger()
->send();

return;
}

RateLimiter::hit($rateLimitKey);
})
```

If you want to rate limit when an action is run, you can do so in the `action()` method:

```php
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\RateLimiter;

Action::make('delete')
->action(function () {
if (RateLimiter::tooManyAttempts(
$rateLimitKey = 'delete:' . auth()->id(),
maxAttempts: 5,
)) {
Notification::make()
->title('Too many attempts')
->body('Please try again in ' . RateLimiter::availableIn($rateLimitKey) . ' seconds.')
->danger()
->send();

return;
}

RateLimiter::hit($rateLimitKey);

// ...
})
```
10 changes: 10 additions & 0 deletions packages/actions/resources/lang/en/notifications.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

return [

'throttled' => [
'title' => 'Too many attempts',
'body' => 'Please try again in :seconds seconds.',
],

];
1 change: 1 addition & 0 deletions packages/actions/src/Action.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class Action extends ViewComponent implements Arrayable
use Concerns\CanBeLabeledFrom;
use Concerns\CanBeMounted;
use Concerns\CanBeOutlined;
use Concerns\CanBeRateLimited;
use Concerns\CanBeSorted;
use Concerns\CanCallParentAction;
use Concerns\CanClose;
Expand Down
22 changes: 22 additions & 0 deletions packages/actions/src/Concerns/CanBeRateLimited.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Filament\Actions\Concerns;

use Closure;

trait CanBeRateLimited
{
protected int | Closure | null $rateLimit = null;

public function rateLimit(int | Closure | null $maxAttempts): static
{
$this->rateLimit = $maxAttempts;

return $this;
}

public function getRateLimit(): ?int
{
return $this->evaluate($this->rateLimit);
}
}
60 changes: 57 additions & 3 deletions packages/actions/src/Concerns/CanNotify.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Filament\Actions\Concerns;

use Closure;
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use Filament\Notifications\Notification;
use Illuminate\Auth\Access\Response;

Expand All @@ -14,12 +15,16 @@ trait CanNotify

protected Notification | Closure | null $unauthorizedNotification = null;

protected Notification | Closure | null $rateLimitedNotification = null;

protected string | Closure | null $failureNotificationTitle = null;

protected string | Closure | null $successNotificationTitle = null;

protected string | Closure | null $unauthorizedNotificationTitle = null;

protected string | Closure | null $rateLimitedNotificationTitle = null;

protected string | Closure | null $failureNotificationBody = null;

protected string | Closure | null $failureNotificationMissingMessage = null;
Expand Down Expand Up @@ -131,8 +136,9 @@ public function sendUnauthorizedNotification(Response $response): static
$notification = $this->evaluate($this->unauthorizedNotification, [
'notification' => $notification = Notification::make()
->danger()
->title($this->getUnauthorizedNotificationTitle() ?? $response->message())
->title($this->getUnauthorizedNotificationTitle($response) ?? $response->message())
->persistent(),
'response' => $response,
]) ?? $notification;

if (filled($notification?->getTitle())) {
Expand All @@ -156,6 +162,43 @@ public function unauthorizedNotificationTitle(string | Closure | null $title): s
return $this;
}

public function sendRateLimitedNotification(TooManyRequestsException $exception): static
{
$notification = $this->evaluate($this->rateLimitedNotification, [
'exception' => $exception,
'minutes' => $exception->minutesUntilAvailable,
'notification' => $notification = Notification::make()
->danger()
->title($this->getRateLimitedNotificationTitle($exception) ?? __('filament-actions::notifications.throttled.title', [
'seconds' => $exception->secondsUntilAvailable,
'minutes' => $exception->minutesUntilAvailable,
]))
->body(__('filament-actions::notifications.throttled.body', [
'seconds' => $exception->secondsUntilAvailable,
'minutes' => $exception->minutesUntilAvailable,
])),
'seconds' => $exception->secondsUntilAvailable,
]) ?? $notification;

$notification->send();

return $this;
}

public function rateLimitedNotification(Notification | Closure | null $notification): static
{
$this->rateLimitedNotification = $notification;

return $this;
}

public function rateLimitedNotificationTitle(string | Closure | null $title): static
{
$this->rateLimitedNotificationTitle = $title;

return $this;
}

public function getSuccessNotificationTitle(): ?string
{
return $this->evaluate($this->successNotificationTitle);
Expand Down Expand Up @@ -209,8 +252,19 @@ public function getFailureNotificationMissingMessage(int $successCount = 0, int
]);
}

public function getUnauthorizedNotificationTitle(): ?string
public function getUnauthorizedNotificationTitle(Response $response): ?string
{
return $this->evaluate($this->unauthorizedNotificationTitle, [
'response' => $response,
]);
}

public function getRateLimitedNotificationTitle(TooManyRequestsException $exception): ?string
{
return $this->evaluate($this->unauthorizedNotificationTitle);
return $this->evaluate($this->rateLimitedNotificationTitle, [
'exception' => $exception,
'minutes' => $exception->minutesUntilAvailable,
'seconds' => $exception->secondsUntilAvailable,
]);
}
}
16 changes: 15 additions & 1 deletion packages/actions/src/Concerns/InteractsWithActions.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Filament\Actions\Concerns;

use Closure;
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use DanHarrin\LivewireRateLimiting\WithRateLimiting;
use Filament\Actions\Action;
use Filament\Actions\Exceptions\ActionNotResolvableException;
use Filament\Schemas\Components\Contracts\ExposesStateToActionData;
Expand All @@ -24,6 +26,8 @@

trait InteractsWithActions
{
use WithRateLimiting;

/**
* @var array<array<string, mixed>> | null
*/
Expand Down Expand Up @@ -161,6 +165,8 @@ public function callMountedAction(array $arguments = []): mixed
return null;
}

$action->mergeArguments($arguments);

if ($action->isDisabled()) {
return null;
}
Expand All @@ -172,7 +178,15 @@ public function callMountedAction(array $arguments = []): mixed
return null;
}

$action->mergeArguments($arguments);
if ($rateLimit = $action->getRateLimit()) {
try {
$this->rateLimit($rateLimit, method: json_encode(array_map(fn (array $action): array => Arr::except($action, ['data']), $this->mountedActions)));
} catch (TooManyRequestsException $exception) {
$action->sendRateLimitedNotification($exception);

return null;
}
}

$schema = $this->getMountedActionSchema(mountedAction: $action);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ public static function make(EmailCodeAuthentication $emailCodeAuthentication): A
->success()
->icon('heroicon-o-lock-open')
->send();
});
})
->rateLimit(5);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ public static function make(EmailCodeAuthentication $emailCodeAuthentication): A
->success()
->icon('heroicon-o-lock-closed')
->send();
});
})
->rateLimit(5);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public static function make(GoogleTwoFactorAuthentication $googleTwoFactorAuthen
->color('danger'))
->modalCancelAction(false)
->cancelParentActions(),
]);
])
->rateLimit(5);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public static function make(GoogleTwoFactorAuthentication $googleTwoFactorAuthen
->success()
->icon('heroicon-o-lock-open')
->send();
});
})
->rateLimit(5);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ public static function make(GoogleTwoFactorAuthentication $googleTwoFactorAuthen
->success()
->icon('heroicon-o-lock-closed')
->send();
});
})
->rateLimit(5);
}
}
42 changes: 42 additions & 0 deletions tests/src/Actions/RateLimitingTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

use Filament\Tests\Actions\TestCase;
use Filament\Tests\Fixtures\Pages\Actions;

use function Filament\Tests\livewire;

uses(TestCase::class);

it('can rate limit an action', function () {
livewire(Actions::class)
->callAction('rate-limited')
->assertDispatched('rate-limited-called')
->assertNotNotified('Too many attempts')
->callAction('rate-limited')
->assertDispatched('rate-limited-called')
->assertNotNotified('Too many attempts')
->callAction('rate-limited')
->assertDispatched('rate-limited-called')
->assertNotNotified('Too many attempts')
->callAction('rate-limited')
->assertDispatched('rate-limited-called')
->assertNotNotified('Too many attempts')
->callAction('rate-limited')
->assertDispatched('rate-limited-called')
->assertNotNotified('Too many attempts')
->callAction('rate-limited')
->assertNotDispatched('rate-limited-called')
->assertNotified('Too many attempts');

livewire(Actions::class)
->callAction('rate-limited')
->assertNotDispatched('rate-limited-called')
->assertNotified('Too many attempts');

cache()->clear();

livewire(Actions::class)
->callAction('rate-limited')
->assertDispatched('rate-limited-called')
->assertNotNotified('Too many attempts');
});
Loading
Loading