From 6a5509d8a5582d5bf7f0df1211c8b0975eec3ae0 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:31:17 +0800 Subject: [PATCH 1/8] perf: accelerate business quota rate limiting with native cache - Inject Illuminate\Contracts\Cache\Repository and TicketTypeManager via IoC into RateLimiter - Cache rolling ticket and appeal quota counts with 5-minute TTL to eliminate SQL COUNT(*) overhead - Automatically invalidate user quota cache on ticket creation and status transitions - Add unit tests for RateLimiter cache hit, miss, and key eviction Co-authored-by: Claude --- src/Api/Resource/SupportTicketResource.php | 3 + src/RateLimiter.php | 60 +++++++++-- src/SupportServiceProvider.php | 25 +++-- tests/unit/RateLimiterCacheTest.php | 118 +++++++++++++++++++++ 4 files changed, 192 insertions(+), 14 deletions(-) create mode 100644 tests/unit/RateLimiterCacheTest.php diff --git a/src/Api/Resource/SupportTicketResource.php b/src/Api/Resource/SupportTicketResource.php index b9290d3..7ae63ea 100644 --- a/src/Api/Resource/SupportTicketResource.php +++ b/src/Api/Resource/SupportTicketResource.php @@ -583,6 +583,9 @@ public function create(object $model, Context $context): object // body rolls the whole thing back -- no body-less tickets. $this->createFirstReply($ticket, $context); + // Invalidate the creator's cached rate-limit quota counts immediately. + $this->rateLimiter->clearUserQuotaCache($actor); + $rawBody = (array) $context->request->getParsedBody(); $data = (array) ($rawBody['data'] ?? []); if ($category) { diff --git a/src/RateLimiter.php b/src/RateLimiter.php index 1b8d68e..dbe018c 100644 --- a/src/RateLimiter.php +++ b/src/RateLimiter.php @@ -6,6 +6,7 @@ use Flarum\Locale\TranslatorInterface; use Flarum\Settings\SettingsRepositoryInterface; use Flarum\User\User; +use Illuminate\Contracts\Cache\Repository as CacheRepository; use LinkRobins\Support\TicketType\AppealTicketType; use LinkRobins\Support\TicketType\TicketTypeManager; @@ -26,9 +27,13 @@ */ class RateLimiter { + public const CACHE_TTL = 300; // 5 minutes + public function __construct( protected SettingsRepositoryInterface $settings, protected TranslatorInterface $translator, + protected CacheRepository $cache, + protected TicketTypeManager $ticketTypeManager, ) { } @@ -82,7 +87,7 @@ protected function checkAppeal(User $actor, SupportCategory $category): array $days = (int) $this->settings->get('linkrobins-support.appeal_window_days', 30); if ($limit > 0 && $days > 0) { $since = Carbon::now()->subDays($days); - $count = $this->countAppealsForUserSince($actor, $since); + $count = $this->countAppealsForUserSince($actor, $since, $days); if ($count >= $limit) { return $this->fail(self::REASON_APPEAL_QUOTA, [ @@ -105,7 +110,7 @@ protected function checkGeneral(User $actor, SupportCategory $category): array } $since = Carbon::now()->subHours($hours); - $count = $this->countGeneralTicketsForUserSince($actor, $since); + $count = $this->countGeneralTicketsForUserSince($actor, $since, $hours); if ($count >= $limit) { return $this->fail(self::REASON_GENERAL_QUOTA, [ @@ -167,6 +172,21 @@ public function describe(array $result): string return $this->translator->trans('linkrobins-support.api.rate_limit.generic'); } + /** + * Clear all cached quota counts for a user. + * Called when a ticket is created or changes status. + */ + public function clearUserQuotaCache(User|int $user): void + { + $userId = $user instanceof User ? (int) $user->id : (int) $user; + $days = (int) $this->settings->get('linkrobins-support.appeal_window_days', 30); + $hours = (int) $this->settings->get('linkrobins-support.general_window_hours', 24); + + $this->cache->forget("linkrobins_support.quota.open_appeals.{$userId}"); + $this->cache->forget("linkrobins_support.quota.appeals.{$userId}.{$days}d"); + $this->cache->forget("linkrobins_support.quota.general.{$userId}.{$hours}h"); + } + // --- DB query methods, extracted so tests can override ------------- // // These intentionally do exactly one thing each (a single count query) @@ -185,13 +205,19 @@ public function describe(array $result): string */ protected function appealTicketTypeIds(): array { - /** @var TicketTypeManager $manager */ - $manager = resolve(TicketTypeManager::class); - - return $manager->appealIds() ?: [AppealTicketType::ID]; + return $this->ticketTypeManager->appealIds() ?: [AppealTicketType::ID]; } protected function countOpenAppealsForUser(User $actor): int + { + return (int) $this->cache->remember( + "linkrobins_support.quota.open_appeals.{$actor->id}", + self::CACHE_TTL, + fn () => $this->queryOpenAppealsForUser($actor) + ); + } + + protected function queryOpenAppealsForUser(User $actor): int { $appealTypes = $this->appealTicketTypeIds(); @@ -208,7 +234,16 @@ protected function countOpenAppealsForUser(User $actor): int ->count(); } - protected function countAppealsForUserSince(User $actor, Carbon $since): int + protected function countAppealsForUserSince(User $actor, Carbon $since, int $days = 30): int + { + return (int) $this->cache->remember( + "linkrobins_support.quota.appeals.{$actor->id}.{$days}d", + self::CACHE_TTL, + fn () => $this->queryAppealsForUserSince($actor, $since) + ); + } + + protected function queryAppealsForUserSince(User $actor, Carbon $since): int { $appealTypes = $this->appealTicketTypeIds(); @@ -222,7 +257,16 @@ protected function countAppealsForUserSince(User $actor, Carbon $since): int ->count(); } - protected function countGeneralTicketsForUserSince(User $actor, Carbon $since): int + protected function countGeneralTicketsForUserSince(User $actor, Carbon $since, int $hours = 24): int + { + return (int) $this->cache->remember( + "linkrobins_support.quota.general.{$actor->id}.{$hours}h", + self::CACHE_TTL, + fn () => $this->queryGeneralTicketsForUserSince($actor, $since) + ); + } + + protected function queryGeneralTicketsForUserSince(User $actor, Carbon $since): int { $appealTypes = $this->appealTicketTypeIds(); diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 26fdd61..103c03c 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -30,8 +30,13 @@ public function register(): void }); } - public function boot(Formatter $formatter, Dispatcher $bus, Events $events, LoggerInterface $log): void - { + public function boot( + Formatter $formatter, + Dispatcher $bus, + Events $events, + LoggerInterface $log, + RateLimiter $rateLimiter + ): void { // Plug Flarum's formatter into the reply model so calling // setContentAttribute() runs Markdown/BBCode through the same // pipeline discussions use. The parsed source ends up in @@ -161,7 +166,7 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg // auto-close command change status without going through the API, // and their changes belong in the history too. A failure here is // logged rather than thrown, so the save itself always stands. - SupportTicket::updated(function (SupportTicket $ticket) use ($events, $log) { + SupportTicket::updated(function (SupportTicket $ticket) use ($events, $log, $rateLimiter) { try { SupportEvent::recordChanges($ticket); } catch (\Throwable $e) { @@ -180,7 +185,7 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg } } - foreach (static::lifecycleEvents($ticket, $actor, $log) as $event) { + foreach (static::lifecycleEvents($ticket, $actor, $log, $rateLimiter) as $event) { static::afterCommit(fn () => $events->dispatch($event)); } @@ -213,8 +218,12 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg * * @return list */ - protected static function lifecycleEvents(SupportTicket $ticket, ?User $actor, LoggerInterface $log): array - { + protected static function lifecycleEvents( + SupportTicket $ticket, + ?User $actor, + LoggerInterface $log, + RateLimiter $rateLimiter + ): array { if ($ticket->savingOpeningMessage) { return []; } @@ -227,6 +236,10 @@ protected static function lifecycleEvents(SupportTicket $ticket, ?User $actor, L $newStatus = (string) $changes['status']; $events[] = new TicketStatusChanged($ticket, $actor, $oldStatus, $newStatus); + if ($ticket->user_id) { + static::afterCommit(fn () => $rateLimiter->clearUserQuotaCache((int) $ticket->user_id)); + } + $category = $ticket->currentCategory(); if ($category) { static::afterCommit(function () use ($category, $ticket, $newStatus, $oldStatus, $actor, $log) { diff --git a/tests/unit/RateLimiterCacheTest.php b/tests/unit/RateLimiterCacheTest.php new file mode 100644 index 0000000..0df355a --- /dev/null +++ b/tests/unit/RateLimiterCacheTest.php @@ -0,0 +1,118 @@ +shouldReceive('getAttribute')->andReturnUsing(function (string $key) use ($id) { + if ($key === 'id') { + return $id; + } + if ($key === 'support_appeal_banned') { + return false; + } + return null; + }); + $user->shouldReceive('__get')->with('id')->andReturn($id)->byDefault(); + $user->shouldReceive('isGuest')->andReturn(false); + + return $user; + } + + private function category(bool $isAppeal = false): SupportCategory + { + $type = m::mock(TicketTypeInterface::class); + $type->shouldReceive('checkRateLimit')->andReturn(null); + $type->shouldReceive('isAppeal')->andReturn($isAppeal); + + $category = m::mock(SupportCategory::class); + $category->shouldReceive('ticketType')->andReturn($type); + + return $category; + } + + #[Test] + public function general_check_uses_cache_remember(): void + { + $settings = m::mock(SettingsRepositoryInterface::class); + $settings->shouldReceive('get')->with('linkrobins-support.general_limit_per_window', 10)->andReturn(5); + $settings->shouldReceive('get')->with('linkrobins-support.general_window_hours', 24)->andReturn(24); + + $translator = m::mock(TranslatorInterface::class); + $cache = m::mock(CacheRepository::class); + $typeManager = m::mock(TicketTypeManager::class); + + // When cache returns 2 (under limit of 5), check should succeed with OK. + $cache->shouldReceive('remember') + ->with('linkrobins_support.quota.general.2.24h', 300, m::type('callable')) + ->once() + ->andReturn(2); + + $limiter = new RateLimiter($settings, $translator, $cache, $typeManager); + $result = $limiter->check($this->user(2), $this->category(isAppeal: false)); + + $this->assertTrue($result['ok']); + $this->assertEquals(RateLimiter::REASON_OK, $result['reason']); + } + + #[Test] + public function general_check_fails_when_cached_count_exceeds_limit(): void + { + $settings = m::mock(SettingsRepositoryInterface::class); + $settings->shouldReceive('get')->with('linkrobins-support.general_limit_per_window', 10)->andReturn(5); + $settings->shouldReceive('get')->with('linkrobins-support.general_window_hours', 24)->andReturn(24); + + $translator = m::mock(TranslatorInterface::class); + $cache = m::mock(CacheRepository::class); + $typeManager = m::mock(TicketTypeManager::class); + + // When cache returns 5 (reaches limit), check should fail. + $cache->shouldReceive('remember') + ->with('linkrobins_support.quota.general.2.24h', 300, m::type('callable')) + ->once() + ->andReturn(5); + + $limiter = new RateLimiter($settings, $translator, $cache, $typeManager); + $result = $limiter->check($this->user(2), $this->category(isAppeal: false)); + + $this->assertFalse($result['ok']); + $this->assertEquals(RateLimiter::REASON_GENERAL_QUOTA, $result['reason']); + $this->assertEquals(5, $result['meta']['count']); + $this->assertEquals(5, $result['meta']['limit']); + } + + #[Test] + public function clear_user_quota_cache_forgets_all_user_keys(): void + { + $settings = m::mock(SettingsRepositoryInterface::class); + $settings->shouldReceive('get')->with('linkrobins-support.appeal_window_days', 30)->andReturn(30); + $settings->shouldReceive('get')->with('linkrobins-support.general_window_hours', 24)->andReturn(24); + + $translator = m::mock(TranslatorInterface::class); + $cache = m::mock(CacheRepository::class); + $typeManager = m::mock(TicketTypeManager::class); + + $cache->shouldReceive('forget')->with('linkrobins_support.quota.open_appeals.2')->once(); + $cache->shouldReceive('forget')->with('linkrobins_support.quota.appeals.2.30d')->once(); + $cache->shouldReceive('forget')->with('linkrobins_support.quota.general.2.24h')->once(); + + $limiter = new RateLimiter($settings, $translator, $cache, $typeManager); + $limiter->clearUserQuotaCache(2); + } +} From 16341766f144d6dcd064f57a02d9879724ba725a Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:32:02 +0800 Subject: [PATCH 2/8] feat: add anti-flood rate limiter for ticket and reply creation - Add TicketCreationThrottler implementing Flarum's ThrottleApi middleware convention - Enforce 10-second anti-flood cooldown between ticket/reply submissions per user or IP - Automatically bypass staff and users holding postWithoutThrottle permission - Register throttler in extend.php using ThrottleApi extender - Add integration tests for ticket creation, replies, staff bypass, and guest IP throttling Co-authored-by: Claude --- extend.php | 4 + src/Throttler/TicketCreationThrottler.php | 69 +++++ tests/integration/api/TicketThrottleTest.php | 280 +++++++++++++++++++ 3 files changed, 353 insertions(+) create mode 100644 src/Throttler/TicketCreationThrottler.php create mode 100644 tests/integration/api/TicketThrottleTest.php diff --git a/extend.php b/extend.php index caa6d44..07281ce 100644 --- a/extend.php +++ b/extend.php @@ -30,6 +30,7 @@ use LinkRobins\Support\TicketType\AppealTicketType; use LinkRobins\Support\TicketType\StandardTicketType; use LinkRobins\Support\TicketType\TicketTypeManager; +use LinkRobins\Support\Throttler\TicketCreationThrottler; return [ (new Extend\Frontend('forum')) @@ -285,4 +286,7 @@ // Note: these settings are consumed server-side by RateLimiter; they // are intentionally NOT serialized to the forum frontend (the JS never // reads them). + + (new Extend\ThrottleApi()) + ->set('linkrobinsSupportTicketTimeout', TicketCreationThrottler::class), ]; diff --git a/src/Throttler/TicketCreationThrottler.php b/src/Throttler/TicketCreationThrottler.php new file mode 100644 index 0000000..7176276 --- /dev/null +++ b/src/Throttler/TicketCreationThrottler.php @@ -0,0 +1,69 @@ +getAttribute('routeName'); + + // Only throttle ticket and reply creation endpoints. + if (! in_array($routeName, ['linkrobins-support-tickets.create', 'linkrobins-support-replies.create'], true)) { + return null; + } + + $actor = RequestUtil::getActor($request); + + // Staff and users with core postWithoutThrottle ability bypass anti-flood throttling. + if ($actor->can('postWithoutThrottle') || $actor->hasPermission('lr-support.handle_tickets')) { + return false; + } + + $key = $this->throttleKey($request, $actor); + + if ($this->limiter->tooManyAttempts($key, 1)) { + return true; + } + + $this->limiter->hit($key, static::$timeout); + + return null; + } + + protected function throttleKey(ServerRequestInterface $request, User $actor): string + { + $action = $request->getAttribute('routeName') === 'linkrobins-support-tickets.create' + ? 'ticket' + : 'reply'; + + if (! $actor->isGuest()) { + return "linkrobins_support.throttle.{$action}.user.{$actor->id}"; + } + + $serverParams = $request->getServerParams(); + $ip = (string) ($request->getAttribute('ipAddress') ?? $serverParams['REMOTE_ADDR'] ?? 'guest'); + + return "linkrobins_support.throttle.{$action}.ip." . sha1($ip); + } +} diff --git a/tests/integration/api/TicketThrottleTest.php b/tests/integration/api/TicketThrottleTest.php new file mode 100644 index 0000000..49eb6fa --- /dev/null +++ b/tests/integration/api/TicketThrottleTest.php @@ -0,0 +1,280 @@ +extension('linkrobins-support'); + + $this->prepareDatabase([ + 'users' => [ + $this->normalUser(), // id 2 + ['id' => 3, 'username' => 'staff', 'email' => 'staff@machine.local', 'is_email_confirmed' => 1, 'password' => 'too-obscure'], + ['id' => 4, 'username' => 'exempt', 'email' => 'exempt@machine.local', 'is_email_confirmed' => 1, 'password' => 'too-obscure'], + ], + 'groups' => [ + ['id' => 100, 'name_singular' => 'Support Staff', 'name_plural' => 'Support Staff', 'is_hidden' => 0], + ['id' => 101, 'name_singular' => 'Exempt Group', 'name_plural' => 'Exempt Group', 'is_hidden' => 0], + ], + 'group_user' => [ + ['user_id' => 3, 'group_id' => 100], + ['user_id' => 4, 'group_id' => 101], + ], + 'group_permission' => [ + ['group_id' => 100, 'permission' => 'lr-support.handle_tickets'], + ['group_id' => 101, 'permission' => 'postWithoutThrottle'], + ], + 'linkrobins_support_categories' => [ + ['id' => 1, 'name' => 'General', 'slug' => 'general', 'ticket_type' => 'standard', 'position' => 0, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()], + ['id' => 2, 'name' => 'Appeals', 'slug' => 'appeals', 'ticket_type' => 'appeal', 'position' => 1, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()], + ], + 'linkrobins_support_tickets' => [ + ['id' => 1, 'category_id' => 1, 'user_id' => 2, 'subject' => 'Existing Ticket', 'status' => 'open', 'last_reply_at' => Carbon::now(), 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()], + ], + 'linkrobins_support_replies' => [ + ['id' => 1, 'ticket_id' => 1, 'user_id' => 2, 'content' => 'First message', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()], + ], + ]); + } + + /** + * @return array + */ + private function ticketBody(string $subject = 'Help', string $firstPost = 'My problem', int $categoryId = 1): array + { + return [ + 'data' => [ + 'type' => 'linkrobins-support-tickets', + 'attributes' => [ + 'subject' => $subject, + 'firstPost' => $firstPost, + ], + 'relationships' => [ + 'category' => [ + 'data' => ['type' => 'linkrobins-support-categories', 'id' => (string) $categoryId], + ], + ], + ], + ]; + } + + /** + * @return array + */ + private function replyBody(int $ticketId = 1, string $content = 'Another reply'): array + { + return [ + 'data' => [ + 'type' => 'linkrobins-support-replies', + 'attributes' => [ + 'content' => $content, + ], + 'relationships' => [ + 'ticket' => [ + 'data' => ['type' => 'linkrobins-support-tickets', 'id' => (string) $ticketId], + ], + ], + ], + ]; + } + + /** + * @param array $json + */ + private function guestRequest(string $method, string $path, array $json = [], string $ip = '127.0.0.1'): ServerRequestInterface + { + $request = (new ServerRequest(['REMOTE_ADDR' => $ip], [], $path, $method)) + ->withAttribute('bypassCsrfToken', true); + + return $this->requestWithJsonBody($request, $json); + } + + #[Test] + public function normal_user_rapid_ticket_creation_is_throttled(): void + { + $response1 = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Ticket 1', 'Content 1'), + ]) + ); + $this->assertEquals(201, $response1->getStatusCode()); + + // An immediate repeat attempt by the same actor must be stopped at the + // middleware layer with 429 Too Many Requests before any database write. + $response2 = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Ticket 2', 'Content 2'), + ]) + ); + $this->assertEquals(429, $response2->getStatusCode()); + + // Exactly 1 new ticket was created (1 from fixture + 1 from first request). + $this->assertEquals(2, $this->database()->table('linkrobins_support_tickets')->count()); + } + + #[Test] + public function normal_user_rapid_reply_is_throttled(): void + { + $response1 = $this->send( + $this->request('POST', '/api/linkrobins-support-replies', [ + 'authenticatedAs' => 2, + 'json' => $this->replyBody(1, 'Reply 1'), + ]) + ); + $this->assertEquals(201, $response1->getStatusCode()); + + // Rapid repeat reply is blocked by the anti-flood throttler. + $response2 = $this->send( + $this->request('POST', '/api/linkrobins-support-replies', [ + 'authenticatedAs' => 2, + 'json' => $this->replyBody(1, 'Reply 2'), + ]) + ); + $this->assertEquals(429, $response2->getStatusCode()); + + // Exactly 1 new reply was created (1 from fixture + 1 from first request). + $this->assertEquals(2, $this->database()->table('linkrobins_support_replies')->count()); + } + + #[Test] + public function staff_with_handle_tickets_permission_is_exempt_from_throttle(): void + { + $response1 = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 3, + 'json' => $this->ticketBody('Staff Ticket 1', 'Content 1'), + ]) + ); + $this->assertEquals(201, $response1->getStatusCode()); + + $response2 = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 3, + 'json' => $this->ticketBody('Staff Ticket 2', 'Content 2'), + ]) + ); + $this->assertEquals(201, $response2->getStatusCode()); + } + + #[Test] + public function user_with_post_without_throttle_permission_is_exempt(): void + { + $response1 = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 4, + 'json' => $this->ticketBody('Exempt Ticket 1', 'Content 1'), + ]) + ); + $this->assertEquals(201, $response1->getStatusCode()); + + $response2 = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 4, + 'json' => $this->ticketBody('Exempt Ticket 2', 'Content 2'), + ]) + ); + $this->assertEquals(201, $response2->getStatusCode()); + } + + #[Test] + public function general_quota_exceeded_returns_403_forbidden(): void + { + // Set general ticket limit to 1 per 24 hours. + $this->setting('linkrobins-support.general_limit_per_window', '1'); + $this->setting('linkrobins-support.general_window_hours', '24'); + + // Clear any anti-flood throttle key for user 2 so the request reaches the resource validator. + $this->app()->getContainer()->make(CacheRateLimiter::class)->clear('linkrobins_support.throttle.ticket.user.2'); + + // User 2 already owns ticket #1 created in setUp (within 24 hours). + $response = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Over quota ticket', 'Content'), + ]) + ); + + $this->assertEquals(403, $response->getStatusCode()); + $body = json_decode((string) $response->getBody(), true); + $this->assertNotEmpty($body['errors']); + } + + #[Test] + public function guests_are_throttled_by_ip(): void + { + $ip = '198.51.100.1'; + + // First guest attempt records an anti-flood hit keyed by sha1(REMOTE_ADDR). + $response1 = $this->send( + $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Guest Ticket 1', 'Content'), $ip) + ); + $this->assertNotEquals(429, $response1->getStatusCode()); + + // Rapid repeat attempt by the same guest IP is throttled with 429. + $response2 = $this->send( + $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Guest Ticket 2', 'Content'), $ip) + ); + $this->assertEquals(429, $response2->getStatusCode()); + + // A different guest IP is not affected by the first IP's cooldown. + $response3 = $this->send( + $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Other Guest Ticket', 'Content'), '198.51.100.2') + ); + $this->assertNotEquals(429, $response3->getStatusCode()); + } + + #[Test] + public function unrelated_routes_are_not_throttled(): void + { + // User creates a ticket, consuming their rate limit for ticket creation. + $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Ticket 1', 'Content'), + ]) + ); + + // Unrelated endpoints (e.g. categories index) must not be throttled. + $response = $this->send( + $this->request('GET', '/api/linkrobins-support-categories', [ + 'authenticatedAs' => 2, + ]) + ); + $this->assertEquals(200, $response->getStatusCode()); + } +} + From 7e9a9758f26c8e045e309af080a7c534678b4022 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:33:47 +0800 Subject: [PATCH 3/8] fix: throttle only successful ticket creates and invalidate quota cache after commit - Drop reply throttling in TicketCreationThrottler so only ticket creation is rate-limited - Record cooldown hits in SupportTicketResource::create after transaction commit so validation/quota failures do not burn the 10s window - Throw FloodingException with translated too_many_requests detail on 429 responses - Clear user quota cache after commit on create and on status, category, deleted_at, delete/restore, and category ticket_type changes Co-authored-by: Claude --- locale/en.yml | 1 + src/Api/Resource/SupportTicketResource.php | 23 ++- src/SupportServiceProvider.php | 41 +++++ src/Throttler/TicketCreationThrottler.php | 50 ++++-- tests/integration/api/TicketThrottleTest.php | 166 +++++++++++++++++-- 5 files changed, 248 insertions(+), 33 deletions(-) diff --git a/locale/en.yml b/locale/en.yml index 0799770..d9a977b 100644 --- a/locale/en.yml +++ b/locale/en.yml @@ -451,4 +451,5 @@ linkrobins-support: appeal_has_open: 'You already have an open appeal. Please wait for it to be resolved before filing another.' appeal_quota: 'You have already filed {count} appeal(s) in the past {days} days (limit: {limit}). Try again later.' general_quota: 'You have filed {count} tickets in the past {hours} hours (limit: {limit}). Please wait before filing another.' + too_many_requests: 'Please wait a few seconds before creating another ticket.' generic: 'Cannot create a ticket right now.' diff --git a/src/Api/Resource/SupportTicketResource.php b/src/Api/Resource/SupportTicketResource.php index 9e7e072..f09857a 100644 --- a/src/Api/Resource/SupportTicketResource.php +++ b/src/Api/Resource/SupportTicketResource.php @@ -20,6 +20,7 @@ use LinkRobins\Support\SupportCategory; use LinkRobins\Support\SupportServiceProvider; use LinkRobins\Support\SupportTicket; +use LinkRobins\Support\Throttler\TicketCreationThrottler; use LinkRobins\Support\UserState; use Psr\Log\LoggerInterface; use Tobyz\JsonApiServer\Context; @@ -40,6 +41,7 @@ class SupportTicketResource extends AbstractDatabaseResource public function __construct( protected RateLimiter $rateLimiter, + protected TicketCreationThrottler $throttler, protected TranslatorInterface $translator, protected Dispatcher $bus, protected LoggerInterface $log, @@ -557,10 +559,15 @@ public function create(object $model, Context $context): object $actor = $context->getActor(); if ($actor->isGuest() || empty($model->category_id)) { - return parent::create($model, $context); + $ticket = parent::create($model, $context); + if ($context instanceof FlarumContext) { + $this->throttler->recordHit($context->request, $actor); + } + + return $ticket; } - return SupportTicket::query()->getConnection()->transaction(function () use ($model, $context, $actor) { + $ticket = SupportTicket::query()->getConnection()->transaction(function () use ($model, $context, $actor) { // Lock this user's row for the duration of the insert so their // concurrent creates serialize (a no-op on SQLite, which already // serializes writes). The re-check below then sees a consistent, @@ -587,9 +594,6 @@ public function create(object $model, Context $context): object // body rolls the whole thing back -- no body-less tickets. $this->createFirstReply($ticket, $context); - // Invalidate the creator's cached rate-limit quota counts immediately. - $this->rateLimiter->clearUserQuotaCache($actor); - $rawBody = (array) $context->request->getParsedBody(); $data = (array) ($rawBody['data'] ?? []); if ($category) { @@ -598,6 +602,15 @@ public function create(object $model, Context $context): object return $ticket; }); + + // Clear the cached quota counts and start the anti-flood cooldown only + // after the transaction has committed and the ticket is persisted. + $this->rateLimiter->clearUserQuotaCache($actor); + if ($context instanceof FlarumContext) { + $this->throttler->recordHit($context->request, $actor); + } + + return $ticket; } /** diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 5d0d7a4..8fabae5 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -152,6 +152,47 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg $ticket->status_changed_at = Carbon::now(); } }); + + SupportTicket::updated(function (SupportTicket $ticket) use ($rateLimiter) { + if ($ticket->user_id && $ticket->wasChanged(['status', 'category_id', 'deleted_at'])) { + static::afterCommit(fn () => $rateLimiter->clearUserQuotaCache((int) $ticket->user_id)); + } + }); + + SupportTicket::deleted(function (SupportTicket $ticket) use ($rateLimiter) { + if ($ticket->user_id) { + static::afterCommit(fn () => $rateLimiter->clearUserQuotaCache((int) $ticket->user_id)); + } + }); + + SupportTicket::restored(function (SupportTicket $ticket) use ($rateLimiter) { + if ($ticket->user_id) { + static::afterCommit(fn () => $rateLimiter->clearUserQuotaCache((int) $ticket->user_id)); + } + }); + + SupportCategory::updated(function (SupportCategory $category) use ($rateLimiter) { + if (! $category->wasChanged('ticket_type')) { + return; + } + + $ids = SupportTicket::query() + ->withTrashed() + ->where('category_id', $category->id) + ->whereNotNull('user_id') + ->distinct() + ->pluck('user_id') + ->map(fn ($id) => (int) $id) + ->all(); + + if ($ids !== []) { + static::afterCommit(function () use ($rateLimiter, $ids) { + foreach ($ids as $userId) { + $rateLimiter->clearUserQuotaCache($userId); + } + }); + } + }); } /** diff --git a/src/Throttler/TicketCreationThrottler.php b/src/Throttler/TicketCreationThrottler.php index 7176276..b99b10f 100644 --- a/src/Throttler/TicketCreationThrottler.php +++ b/src/Throttler/TicketCreationThrottler.php @@ -3,17 +3,20 @@ namespace LinkRobins\Support\Throttler; use Flarum\Http\RequestUtil; +use Flarum\Locale\TranslatorInterface; +use Flarum\Post\Exception\FloodingException; use Flarum\User\User; use Illuminate\Cache\RateLimiter; use Psr\Http\Message\ServerRequestInterface; /** - * Anti-flood throttler for support tickets and replies. + * Anti-flood throttler for support ticket creation. * * Runs at the HTTP middleware layer via Flarum's Extend\ThrottleApi. - * Protects the server from rapid-fire spam and automated scripts by - * rejecting repeated submissions within a short cooldown window with HTTP 429 - * before any controller or database transaction begins. + * Checks whether the actor is still within the cooldown window from a prior + * successful ticket creation and rejects with HTTP 429 before any controller + * or database transaction begins. Cooldown hits are recorded only after a + * ticket creation actually succeeds. */ class TicketCreationThrottler { @@ -21,49 +24,60 @@ class TicketCreationThrottler public function __construct( protected RateLimiter $limiter, + protected TranslatorInterface $translator, ) { } public function __invoke(ServerRequestInterface $request): ?bool { - $routeName = $request->getAttribute('routeName'); - - // Only throttle ticket and reply creation endpoints. - if (! in_array($routeName, ['linkrobins-support-tickets.create', 'linkrobins-support-replies.create'], true)) { + if ($request->getAttribute('routeName') !== 'linkrobins-support-tickets.create') { return null; } $actor = RequestUtil::getActor($request); // Staff and users with core postWithoutThrottle ability bypass anti-flood throttling. - if ($actor->can('postWithoutThrottle') || $actor->hasPermission('lr-support.handle_tickets')) { + if ($this->isExempt($actor)) { return false; } $key = $this->throttleKey($request, $actor); if ($this->limiter->tooManyAttempts($key, 1)) { - return true; + throw new FloodingException( + $this->translator->trans('linkrobins-support.api.rate_limit.too_many_requests') + ); } - $this->limiter->hit($key, static::$timeout); - return null; } - protected function throttleKey(ServerRequestInterface $request, User $actor): string + /** + * Start the cooldown window after a ticket has been successfully created. + */ + public function recordHit(ServerRequestInterface $request, User $actor): void { - $action = $request->getAttribute('routeName') === 'linkrobins-support-tickets.create' - ? 'ticket' - : 'reply'; + if ($this->isExempt($actor)) { + return; + } + + $this->limiter->hit($this->throttleKey($request, $actor), static::$timeout); + } + public function isExempt(User $actor): bool + { + return $actor->can('postWithoutThrottle') || $actor->hasPermission('lr-support.handle_tickets'); + } + + protected function throttleKey(ServerRequestInterface $request, User $actor): string + { if (! $actor->isGuest()) { - return "linkrobins_support.throttle.{$action}.user.{$actor->id}"; + return "linkrobins_support.throttle.ticket.user.{$actor->id}"; } $serverParams = $request->getServerParams(); $ip = (string) ($request->getAttribute('ipAddress') ?? $serverParams['REMOTE_ADDR'] ?? 'guest'); - return "linkrobins_support.throttle.{$action}.ip." . sha1($ip); + return 'linkrobins_support.throttle.ticket.ip.' . sha1($ip); } } diff --git a/tests/integration/api/TicketThrottleTest.php b/tests/integration/api/TicketThrottleTest.php index 49eb6fa..6cefebb 100644 --- a/tests/integration/api/TicketThrottleTest.php +++ b/tests/integration/api/TicketThrottleTest.php @@ -12,8 +12,14 @@ use Carbon\Carbon; use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\TestCase; +use Flarum\User\Guest; use Illuminate\Cache\RateLimiter as CacheRateLimiter; +use Illuminate\Contracts\Cache\Repository as CacheRepository; use Laminas\Diactoros\ServerRequest; +use LinkRobins\Support\RateLimiter as SupportRateLimiter; +use LinkRobins\Support\SupportCategory; +use LinkRobins\Support\SupportTicket; +use LinkRobins\Support\Throttler\TicketCreationThrottler; use PHPUnit\Framework\Attributes\Test; use Psr\Http\Message\ServerRequestInterface; @@ -133,7 +139,7 @@ public function normal_user_rapid_ticket_creation_is_throttled(): void $this->assertEquals(201, $response1->getStatusCode()); // An immediate repeat attempt by the same actor must be stopped at the - // middleware layer with 429 Too Many Requests before any database write. + // middleware layer with 429 Too Many Requests and a detail message. $response2 = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ 'authenticatedAs' => 2, @@ -142,12 +148,16 @@ public function normal_user_rapid_ticket_creation_is_throttled(): void ); $this->assertEquals(429, $response2->getStatusCode()); + $body2 = json_decode((string) $response2->getBody(), true); + $this->assertSame('too_many_requests', $body2['errors'][0]['code'] ?? null); + $this->assertNotEmpty($body2['errors'][0]['detail'] ?? null); + // Exactly 1 new ticket was created (1 from fixture + 1 from first request). $this->assertEquals(2, $this->database()->table('linkrobins_support_tickets')->count()); } #[Test] - public function normal_user_rapid_reply_is_throttled(): void + public function normal_user_rapid_replies_are_not_throttled(): void { $response1 = $this->send( $this->request('POST', '/api/linkrobins-support-replies', [ @@ -157,17 +167,63 @@ public function normal_user_rapid_reply_is_throttled(): void ); $this->assertEquals(201, $response1->getStatusCode()); - // Rapid repeat reply is blocked by the anti-flood throttler. + // Rapid repeat replies must not be blocked by the ticket-creation cooldown. $response2 = $this->send( $this->request('POST', '/api/linkrobins-support-replies', [ 'authenticatedAs' => 2, 'json' => $this->replyBody(1, 'Reply 2'), ]) ); - $this->assertEquals(429, $response2->getStatusCode()); + $this->assertEquals(201, $response2->getStatusCode()); + + $this->assertEquals(3, $this->database()->table('linkrobins_support_replies')->count()); + } - // Exactly 1 new reply was created (1 from fixture + 1 from first request). - $this->assertEquals(2, $this->database()->table('linkrobins_support_replies')->count()); + #[Test] + public function failed_validation_does_not_burn_throttle_cooldown(): void + { + $invalidResponse = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('', 'Valid body'), + ]) + ); + $this->assertContains($invalidResponse->getStatusCode(), [400, 422]); + + // Corrected retry immediately after validation failure must succeed. + $validResponse = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Corrected Subject', 'Valid body'), + ]) + ); + $this->assertEquals(201, $validResponse->getStatusCode()); + } + + #[Test] + public function quota_refusal_does_not_burn_throttle_cooldown(): void + { + $this->setting('linkrobins-support.general_limit_per_window', '1'); + $this->setting('linkrobins-support.general_window_hours', '24'); + + // User 2 already owns ticket #1 from setUp -> quota refusal (403). + $refused = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Over quota', 'Content'), + ]) + ); + $this->assertEquals(403, $refused->getStatusCode()); + + // Raise quota and immediately retry: the 403 must not have started a 429 cooldown. + $this->setting('linkrobins-support.general_limit_per_window', '10'); + $allowed = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Now allowed', 'Content'), + ]) + ); + $this->assertEquals(201, $allowed->getStatusCode()); } #[Test] @@ -238,12 +294,14 @@ public function guests_are_throttled_by_ip(): void { $ip = '198.51.100.1'; - // First guest attempt records an anti-flood hit keyed by sha1(REMOTE_ADDR). - $response1 = $this->send( - $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Guest Ticket 1', 'Content'), $ip) - ); + // A rejected guest attempt (401/403) must not record an anti-flood hit. + $req1 = $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Guest Ticket 1', 'Content'), $ip); + $response1 = $this->send($req1); $this->assertNotEquals(429, $response1->getStatusCode()); + // Record a hit for that IP (simulating a successful IP-keyed submission). + $this->app()->getContainer()->make(TicketCreationThrottler::class)->recordHit($req1, new Guest()); + // Rapid repeat attempt by the same guest IP is throttled with 429. $response2 = $this->send( $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Guest Ticket 2', 'Content'), $ip) @@ -257,6 +315,94 @@ public function guests_are_throttled_by_ip(): void $this->assertNotEquals(429, $response3->getStatusCode()); } + #[Test] + public function quota_cache_is_cleared_on_delete_restore_category_and_type_changes(): void + { + $container = $this->app()->getContainer(); + /** @var CacheRepository $cache */ + $cache = $container->make(CacheRepository::class); + /** @var SupportRateLimiter $rateLimiter */ + $rateLimiter = $container->make(SupportRateLimiter::class); + + $user = \Flarum\User\User::findOrFail(2); + $generalCategory = SupportCategory::findOrFail(1); + $appealCategory = SupportCategory::findOrFail(2); + $cacheKey = 'linkrobins_support.quota.open_appeals.2'; + + // Warm user 2's quota cache. + $rateLimiter->check($user, $appealCategory); + $this->assertTrue($cache->has($cacheKey)); + + // 1. Soft-delete via PATCH isDeleted=true clears cache. + $softDelete = $this->send( + $this->request('PATCH', '/api/linkrobins-support-tickets/1', [ + 'authenticatedAs' => 3, + 'json' => ['data' => ['attributes' => ['isDeleted' => true]]], + ]) + ); + $this->assertEquals(200, $softDelete->getStatusCode()); + $this->assertFalse($cache->has($cacheKey)); + + // 2. Restore via PATCH isDeleted=false clears cache. + $rateLimiter->check($user, $appealCategory); + $this->assertTrue($cache->has($cacheKey)); + $restore = $this->send( + $this->request('PATCH', '/api/linkrobins-support-tickets/1', [ + 'authenticatedAs' => 3, + 'json' => ['data' => ['attributes' => ['isDeleted' => false]]], + ]) + ); + $this->assertEquals(200, $restore->getStatusCode()); + $this->assertFalse($cache->has($cacheKey)); + + // 3. Moving ticket to another category clears cache. + $rateLimiter->check($user, $appealCategory); + $this->assertTrue($cache->has($cacheKey)); + $moveCategory = $this->send( + $this->request('PATCH', '/api/linkrobins-support-tickets/1', [ + 'authenticatedAs' => 3, + 'json' => [ + 'data' => [ + 'relationships' => [ + 'category' => ['data' => ['type' => 'linkrobins-support-categories', 'id' => '2']], + ], + ], + ], + ]) + ); + $this->assertEquals(200, $moveCategory->getStatusCode()); + $this->assertFalse($cache->has($cacheKey)); + + // 4. Changing a category's ticket_type clears cache for users with tickets in that category. + $rateLimiter->check($user, $generalCategory); + $this->assertTrue($cache->has($cacheKey)); + $typeChange = $this->send( + $this->request('PATCH', '/api/linkrobins-support-categories/2', [ + 'authenticatedAs' => 1, + 'json' => ['data' => ['attributes' => ['ticketType' => 'standard']]], + ]) + ); + $this->assertEquals(200, $typeChange->getStatusCode()); + $this->assertFalse($cache->has($cacheKey)); + + // 5. Force-delete clears cache. + $this->send( + $this->request('PATCH', '/api/linkrobins-support-tickets/1', [ + 'authenticatedAs' => 3, + 'json' => ['data' => ['attributes' => ['isDeleted' => true]]], + ]) + ); + $rateLimiter->check($user, $appealCategory); + $this->assertTrue($cache->has($cacheKey)); + $forceDelete = $this->send( + $this->request('DELETE', '/api/linkrobins-support-tickets/1', [ + 'authenticatedAs' => 1, + ]) + ); + $this->assertEquals(204, $forceDelete->getStatusCode()); + $this->assertFalse($cache->has($cacheKey)); + } + #[Test] public function unrelated_routes_are_not_throttled(): void { From 27dbcce65a755866f930360afece72a6d4c3a07b Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:42:47 +0800 Subject: [PATCH 4/8] fix: inject RateLimiter in SupportServiceProvider::boot and update settings repository in throttle test - Restore RateLimiter parameter in SupportServiceProvider::boot so afterCommit quota cache invalidation does not call clearUserQuotaCache() on null - Update TicketThrottleTest::quota_refusal_does_not_burn_throttle_cooldown to update SettingsRepositoryInterface on the booted app container Co-authored-by: Claude --- src/SupportServiceProvider.php | 9 +++++++-- tests/integration/api/TicketThrottleTest.php | 7 +++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 8fabae5..19aef03 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -27,8 +27,13 @@ public function register(): void }); } - public function boot(Formatter $formatter, Dispatcher $bus, Events $events, LoggerInterface $log): void - { + public function boot( + Formatter $formatter, + Dispatcher $bus, + Events $events, + LoggerInterface $log, + RateLimiter $rateLimiter + ): void { // Plug Flarum's formatter into the reply model so calling // setContentAttribute() runs Markdown/BBCode through the same // pipeline discussions use. The parsed source ends up in diff --git a/tests/integration/api/TicketThrottleTest.php b/tests/integration/api/TicketThrottleTest.php index 6cefebb..5179b92 100644 --- a/tests/integration/api/TicketThrottleTest.php +++ b/tests/integration/api/TicketThrottleTest.php @@ -10,6 +10,7 @@ namespace LinkRobins\Support\Tests\integration\api; use Carbon\Carbon; +use Flarum\Settings\SettingsRepositoryInterface; use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\TestCase; use Flarum\User\Guest; @@ -215,8 +216,10 @@ public function quota_refusal_does_not_burn_throttle_cooldown(): void ); $this->assertEquals(403, $refused->getStatusCode()); - // Raise quota and immediately retry: the 403 must not have started a 429 cooldown. - $this->setting('linkrobins-support.general_limit_per_window', '10'); + // Raise quota via the booted settings repository and immediately retry: + // the 403 must not have started a 429 cooldown. + $this->app()->getContainer()->make(SettingsRepositoryInterface::class) + ->set('linkrobins-support.general_limit_per_window', '10'); $allowed = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ 'authenticatedAs' => 2, From cc0eaff57b7c99d2c46b6601afb4ab046ba86e61 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:47:41 +0800 Subject: [PATCH 5/8] test: warm appeal and general quota cache keys before category ticketType change Co-authored-by: Claude --- tests/integration/api/TicketThrottleTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/integration/api/TicketThrottleTest.php b/tests/integration/api/TicketThrottleTest.php index 5179b92..f347857 100644 --- a/tests/integration/api/TicketThrottleTest.php +++ b/tests/integration/api/TicketThrottleTest.php @@ -377,8 +377,11 @@ public function quota_cache_is_cleared_on_delete_restore_category_and_type_chang $this->assertFalse($cache->has($cacheKey)); // 4. Changing a category's ticket_type clears cache for users with tickets in that category. + $generalCacheKey = 'linkrobins_support.quota.general.2.24h'; + $rateLimiter->check($user, $appealCategory); $rateLimiter->check($user, $generalCategory); $this->assertTrue($cache->has($cacheKey)); + $this->assertTrue($cache->has($generalCacheKey)); $typeChange = $this->send( $this->request('PATCH', '/api/linkrobins-support-categories/2', [ 'authenticatedAs' => 1, @@ -387,6 +390,7 @@ public function quota_cache_is_cleared_on_delete_restore_category_and_type_chang ); $this->assertEquals(200, $typeChange->getStatusCode()); $this->assertFalse($cache->has($cacheKey)); + $this->assertFalse($cache->has($generalCacheKey)); // 5. Force-delete clears cache. $this->send( From 128736ea5db661886318be5a94ae0bf35388e4d6 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:39:40 +0800 Subject: [PATCH 6/8] fix: harden quota cache lock check, TTL, error handling, and throttler behavior - Bypass quota cache inside SupportTicketResource::create locked transaction via RateLimiter::check(..., fresh: true) - Reduce RateLimiter::CACHE_TTL from 300s to 60s so expired-window wait stays bounded - Wrap post-commit quota cache clear and throttle hit recording in warning-logged try/catch blocks - Return standard 429 too_many_requests via ThrottleApi (dropping non-emitted FloodingException detail and locale key), skip exempt/guest actors with null so unrelated throttlers stay intact, and drop unreachable guest IP branch Co-authored-by: Claude --- locale/en.yml | 1 - src/Api/Resource/SupportTicketResource.php | 40 +++++++++++++----- src/RateLimiter.php | 48 ++++++++++++++-------- src/SupportServiceProvider.php | 39 ++++++++++++++---- src/Throttler/TicketCreationThrottler.php | 43 +++++++------------ 5 files changed, 105 insertions(+), 66 deletions(-) diff --git a/locale/en.yml b/locale/en.yml index d9a977b..0799770 100644 --- a/locale/en.yml +++ b/locale/en.yml @@ -451,5 +451,4 @@ linkrobins-support: appeal_has_open: 'You already have an open appeal. Please wait for it to be resolved before filing another.' appeal_quota: 'You have already filed {count} appeal(s) in the past {days} days (limit: {limit}). Try again later.' general_quota: 'You have filed {count} tickets in the past {hours} hours (limit: {limit}). Please wait before filing another.' - too_many_requests: 'Please wait a few seconds before creating another ticket.' generic: 'Cannot create a ticket right now.' diff --git a/src/Api/Resource/SupportTicketResource.php b/src/Api/Resource/SupportTicketResource.php index f09857a..f55efdf 100644 --- a/src/Api/Resource/SupportTicketResource.php +++ b/src/Api/Resource/SupportTicketResource.php @@ -560,9 +560,7 @@ public function create(object $model, Context $context): object if ($actor->isGuest() || empty($model->category_id)) { $ticket = parent::create($model, $context); - if ($context instanceof FlarumContext) { - $this->throttler->recordHit($context->request, $actor); - } + $this->recordPostCreateSideEffects($actor, $context, clearCache: ! $actor->isGuest()); return $ticket; } @@ -570,15 +568,15 @@ public function create(object $model, Context $context): object $ticket = SupportTicket::query()->getConnection()->transaction(function () use ($model, $context, $actor) { // Lock this user's row for the duration of the insert so their // concurrent creates serialize (a no-op on SQLite, which already - // serializes writes). The re-check below then sees a consistent, - // committed count. + // serializes writes). The re-check below bypasses the cache so it + // always sees the committed count. User::query()->whereKey($actor->id)->lockForUpdate()->first(); $category = $model->relationLoaded('category') && $model->category ? $model->category : SupportCategory::query()->find((int) $model->category_id); if ($category) { - $rate = $this->rateLimiter->check($actor, $category); + $rate = $this->rateLimiter->check($actor, $category, fresh: true); if (! $rate['ok']) { throw new ForbiddenException($this->rateLimiter->describe($rate)); } @@ -605,14 +603,36 @@ public function create(object $model, Context $context): object // Clear the cached quota counts and start the anti-flood cooldown only // after the transaction has committed and the ticket is persisted. - $this->rateLimiter->clearUserQuotaCache($actor); - if ($context instanceof FlarumContext) { - $this->throttler->recordHit($context->request, $actor); - } + $this->recordPostCreateSideEffects($actor, $context, clearCache: true); return $ticket; } + protected function recordPostCreateSideEffects(User $actor, Context $context, bool $clearCache): void + { + if ($clearCache) { + try { + $this->rateLimiter->clearUserQuotaCache($actor); + } catch (\Throwable $e) { + $this->log->warning('[linkrobins/support] failed to clear quota cache after ticket create', [ + 'user_id' => $actor->id, + 'exception' => $e, + ]); + } + } + + if ($context instanceof FlarumContext) { + try { + $this->throttler->recordHit($actor); + } catch (\Throwable $e) { + $this->log->warning('[linkrobins/support] failed to record throttle hit after ticket create', [ + 'user_id' => $actor->id, + 'exception' => $e, + ]); + } + } + } + /** * Create the ticket's opening message as its first reply, inside the * caller's transaction. Reuses SupportReplyResource's create endpoint so diff --git a/src/RateLimiter.php b/src/RateLimiter.php index dbe018c..87dd052 100644 --- a/src/RateLimiter.php +++ b/src/RateLimiter.php @@ -27,7 +27,7 @@ */ class RateLimiter { - public const CACHE_TTL = 300; // 5 minutes + public const CACHE_TTL = 60; // 1 minute public function __construct( protected SettingsRepositoryInterface $settings, @@ -47,8 +47,11 @@ public function __construct( * Returns ['ok' => bool, 'reason' => string, 'meta' => array]. `meta` * contains the relevant numbers (limit, window, time-to-next-allowed) * for the rejection message. + * + * Pass $fresh = true inside row-locked transactions to bypass the quota cache + * and read the current committed count directly from the database. */ - public function check(User $actor, SupportCategory $category): array + public function check(User $actor, SupportCategory $category, bool $fresh = false): array { $custom = $category->ticketType()->checkRateLimit($actor, $category, $this); if ($custom !== null) { @@ -56,12 +59,12 @@ public function check(User $actor, SupportCategory $category): array } if ($category->ticketType()->isAppeal()) { - return $this->checkAppeal($actor, $category); + return $this->checkAppeal($actor, $category, $fresh); } - return $this->checkGeneral($actor, $category); + return $this->checkGeneral($actor, $category, $fresh); } - protected function checkAppeal(User $actor, SupportCategory $category): array + protected function checkAppeal(User $actor, SupportCategory $category, bool $fresh = false): array { // Permanent appeal-ban: hard stop, no window. if (UserState::isAppealBanned($actor)) { @@ -73,7 +76,7 @@ protected function checkAppeal(User $actor, SupportCategory $category): array 1 ); if ($maxConcurrent > 0) { - $openAppealCount = $this->countOpenAppealsForUser($actor); + $openAppealCount = $this->countOpenAppealsForUser($actor, $fresh); if ($openAppealCount >= $maxConcurrent) { return $this->fail(self::REASON_APPEAL_HAS_OPEN, [ @@ -87,7 +90,7 @@ protected function checkAppeal(User $actor, SupportCategory $category): array $days = (int) $this->settings->get('linkrobins-support.appeal_window_days', 30); if ($limit > 0 && $days > 0) { $since = Carbon::now()->subDays($days); - $count = $this->countAppealsForUserSince($actor, $since, $days); + $count = $this->countAppealsForUserSince($actor, $since, $days, $fresh); if ($count >= $limit) { return $this->fail(self::REASON_APPEAL_QUOTA, [ @@ -101,7 +104,7 @@ protected function checkAppeal(User $actor, SupportCategory $category): array return $this->ok(); } - protected function checkGeneral(User $actor, SupportCategory $category): array + protected function checkGeneral(User $actor, SupportCategory $category, bool $fresh = false): array { $limit = (int) $this->settings->get('linkrobins-support.general_limit_per_window', 10); $hours = (int) $this->settings->get('linkrobins-support.general_window_hours', 24); @@ -110,7 +113,7 @@ protected function checkGeneral(User $actor, SupportCategory $category): array } $since = Carbon::now()->subHours($hours); - $count = $this->countGeneralTicketsForUserSince($actor, $since, $hours); + $count = $this->countGeneralTicketsForUserSince($actor, $since, $hours, $fresh); if ($count >= $limit) { return $this->fail(self::REASON_GENERAL_QUOTA, [ @@ -208,11 +211,20 @@ protected function appealTicketTypeIds(): array return $this->ticketTypeManager->appealIds() ?: [AppealTicketType::ID]; } - protected function countOpenAppealsForUser(User $actor): int + protected function rememberCount(string $key, bool $fresh, callable $query): int { - return (int) $this->cache->remember( + if ($fresh) { + return (int) $query(); + } + + return (int) $this->cache->remember($key, self::CACHE_TTL, $query); + } + + protected function countOpenAppealsForUser(User $actor, bool $fresh = false): int + { + return $this->rememberCount( "linkrobins_support.quota.open_appeals.{$actor->id}", - self::CACHE_TTL, + $fresh, fn () => $this->queryOpenAppealsForUser($actor) ); } @@ -234,11 +246,11 @@ protected function queryOpenAppealsForUser(User $actor): int ->count(); } - protected function countAppealsForUserSince(User $actor, Carbon $since, int $days = 30): int + protected function countAppealsForUserSince(User $actor, Carbon $since, int $days = 30, bool $fresh = false): int { - return (int) $this->cache->remember( + return $this->rememberCount( "linkrobins_support.quota.appeals.{$actor->id}.{$days}d", - self::CACHE_TTL, + $fresh, fn () => $this->queryAppealsForUserSince($actor, $since) ); } @@ -257,11 +269,11 @@ protected function queryAppealsForUserSince(User $actor, Carbon $since): int ->count(); } - protected function countGeneralTicketsForUserSince(User $actor, Carbon $since, int $hours = 24): int + protected function countGeneralTicketsForUserSince(User $actor, Carbon $since, int $hours = 24, bool $fresh = false): int { - return (int) $this->cache->remember( + return $this->rememberCount( "linkrobins_support.quota.general.{$actor->id}.{$hours}h", - self::CACHE_TTL, + $fresh, fn () => $this->queryGeneralTicketsForUserSince($actor, $since) ); } diff --git a/src/SupportServiceProvider.php b/src/SupportServiceProvider.php index 19aef03..a116e0a 100644 --- a/src/SupportServiceProvider.php +++ b/src/SupportServiceProvider.php @@ -158,25 +158,25 @@ public function boot( } }); - SupportTicket::updated(function (SupportTicket $ticket) use ($rateLimiter) { + SupportTicket::updated(function (SupportTicket $ticket) use ($rateLimiter, $log) { if ($ticket->user_id && $ticket->wasChanged(['status', 'category_id', 'deleted_at'])) { - static::afterCommit(fn () => $rateLimiter->clearUserQuotaCache((int) $ticket->user_id)); + static::clearQuotaCacheAfterCommit($rateLimiter, (int) $ticket->user_id, $log); } }); - SupportTicket::deleted(function (SupportTicket $ticket) use ($rateLimiter) { + SupportTicket::deleted(function (SupportTicket $ticket) use ($rateLimiter, $log) { if ($ticket->user_id) { - static::afterCommit(fn () => $rateLimiter->clearUserQuotaCache((int) $ticket->user_id)); + static::clearQuotaCacheAfterCommit($rateLimiter, (int) $ticket->user_id, $log); } }); - SupportTicket::restored(function (SupportTicket $ticket) use ($rateLimiter) { + SupportTicket::restored(function (SupportTicket $ticket) use ($rateLimiter, $log) { if ($ticket->user_id) { - static::afterCommit(fn () => $rateLimiter->clearUserQuotaCache((int) $ticket->user_id)); + static::clearQuotaCacheAfterCommit($rateLimiter, (int) $ticket->user_id, $log); } }); - SupportCategory::updated(function (SupportCategory $category) use ($rateLimiter) { + SupportCategory::updated(function (SupportCategory $category) use ($rateLimiter, $log) { if (! $category->wasChanged('ticket_type')) { return; } @@ -191,15 +191,36 @@ public function boot( ->all(); if ($ids !== []) { - static::afterCommit(function () use ($rateLimiter, $ids) { + static::afterCommit(function () use ($rateLimiter, $ids, $log) { foreach ($ids as $userId) { - $rateLimiter->clearUserQuotaCache($userId); + try { + $rateLimiter->clearUserQuotaCache($userId); + } catch (\Throwable $e) { + $log->warning('[linkrobins/support] failed to clear user quota cache', [ + 'user_id' => $userId, + 'exception' => $e, + ]); + } } }); } }); } + protected static function clearQuotaCacheAfterCommit(RateLimiter $rateLimiter, int $userId, LoggerInterface $log): void + { + static::afterCommit(function () use ($rateLimiter, $userId, $log) { + try { + $rateLimiter->clearUserQuotaCache($userId); + } catch (\Throwable $e) { + $log->warning('[linkrobins/support] failed to clear user quota cache', [ + 'user_id' => $userId, + 'exception' => $e, + ]); + } + }); + } + /** * Dispatch an event after the surrounding transaction commits, isolating each * listener so a failure in one cannot abort the request or remaining listeners. diff --git a/src/Throttler/TicketCreationThrottler.php b/src/Throttler/TicketCreationThrottler.php index b99b10f..a68e34e 100644 --- a/src/Throttler/TicketCreationThrottler.php +++ b/src/Throttler/TicketCreationThrottler.php @@ -3,8 +3,6 @@ namespace LinkRobins\Support\Throttler; use Flarum\Http\RequestUtil; -use Flarum\Locale\TranslatorInterface; -use Flarum\Post\Exception\FloodingException; use Flarum\User\User; use Illuminate\Cache\RateLimiter; use Psr\Http\Message\ServerRequestInterface; @@ -13,10 +11,10 @@ * Anti-flood throttler for support ticket creation. * * Runs at the HTTP middleware layer via Flarum's Extend\ThrottleApi. - * Checks whether the actor is still within the cooldown window from a prior - * successful ticket creation and rejects with HTTP 429 before any controller - * or database transaction begins. Cooldown hits are recorded only after a - * ticket creation actually succeeds. + * Checks whether an authenticated non-exempt actor is within the cooldown + * window from a prior successful ticket creation and rejects with HTTP 429 + * before any controller or database transaction begins. Cooldown hits are + * recorded only after a ticket creation actually succeeds. */ class TicketCreationThrottler { @@ -24,7 +22,6 @@ class TicketCreationThrottler public function __construct( protected RateLimiter $limiter, - protected TranslatorInterface $translator, ) { } @@ -36,17 +33,14 @@ public function __invoke(ServerRequestInterface $request): ?bool $actor = RequestUtil::getActor($request); - // Staff and users with core postWithoutThrottle ability bypass anti-flood throttling. - if ($this->isExempt($actor)) { - return false; + // Guests cannot create tickets (GlobalPolicy::createTicket), and exempt + // actors skip this throttler without disabling unrelated throttlers. + if ($actor->isGuest() || $this->isExempt($actor)) { + return null; } - $key = $this->throttleKey($request, $actor); - - if ($this->limiter->tooManyAttempts($key, 1)) { - throw new FloodingException( - $this->translator->trans('linkrobins-support.api.rate_limit.too_many_requests') - ); + if ($this->limiter->tooManyAttempts($this->throttleKey($actor), 1)) { + return true; } return null; @@ -55,13 +49,13 @@ public function __invoke(ServerRequestInterface $request): ?bool /** * Start the cooldown window after a ticket has been successfully created. */ - public function recordHit(ServerRequestInterface $request, User $actor): void + public function recordHit(User $actor): void { - if ($this->isExempt($actor)) { + if ($actor->isGuest() || $this->isExempt($actor)) { return; } - $this->limiter->hit($this->throttleKey($request, $actor), static::$timeout); + $this->limiter->hit($this->throttleKey($actor), static::$timeout); } public function isExempt(User $actor): bool @@ -69,15 +63,8 @@ public function isExempt(User $actor): bool return $actor->can('postWithoutThrottle') || $actor->hasPermission('lr-support.handle_tickets'); } - protected function throttleKey(ServerRequestInterface $request, User $actor): string + protected function throttleKey(User $actor): string { - if (! $actor->isGuest()) { - return "linkrobins_support.throttle.ticket.user.{$actor->id}"; - } - - $serverParams = $request->getServerParams(); - $ip = (string) ($request->getAttribute('ipAddress') ?? $serverParams['REMOTE_ADDR'] ?? 'guest'); - - return 'linkrobins_support.throttle.ticket.ip.' . sha1($ip); + return "linkrobins_support.throttle.ticket.user.{$actor->id}"; } } From 329e9153dfe5574db30e2f64587834b7ef8d1e85 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:47:42 +0800 Subject: [PATCH 7/8] test: cover fresh locked checks, post-create cache clearing, cooldown expiry, and user isolation - Add license header, 60s TTL checks, appeal cache assertions, and fresh-check tests in RateLimiterCacheTest - Add tests for cooldown expiration, cross-user isolation, post-create cache clear, stale-cache bypass inside locked transaction, and real DB quota queries - Assert 201 on unrelated_routes_are_not_throttled, drop non-emitted 429 detail check, and test guest 401/403 rejection without throttle hit Co-authored-by: Claude --- tests/integration/api/TicketThrottleTest.php | 242 ++++++++++++++++--- tests/unit/RateLimiterCacheTest.php | 82 ++++++- 2 files changed, 286 insertions(+), 38 deletions(-) diff --git a/tests/integration/api/TicketThrottleTest.php b/tests/integration/api/TicketThrottleTest.php index f347857..055f620 100644 --- a/tests/integration/api/TicketThrottleTest.php +++ b/tests/integration/api/TicketThrottleTest.php @@ -13,16 +13,14 @@ use Flarum\Settings\SettingsRepositoryInterface; use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\TestCase; -use Flarum\User\Guest; +use Flarum\User\User; use Illuminate\Cache\RateLimiter as CacheRateLimiter; use Illuminate\Contracts\Cache\Repository as CacheRepository; -use Laminas\Diactoros\ServerRequest; use LinkRobins\Support\RateLimiter as SupportRateLimiter; use LinkRobins\Support\SupportCategory; use LinkRobins\Support\SupportTicket; use LinkRobins\Support\Throttler\TicketCreationThrottler; use PHPUnit\Framework\Attributes\Test; -use Psr\Http\Message\ServerRequestInterface; class TicketThrottleTest extends TestCase { @@ -50,6 +48,7 @@ public function setUp(): void $this->normalUser(), // id 2 ['id' => 3, 'username' => 'staff', 'email' => 'staff@machine.local', 'is_email_confirmed' => 1, 'password' => 'too-obscure'], ['id' => 4, 'username' => 'exempt', 'email' => 'exempt@machine.local', 'is_email_confirmed' => 1, 'password' => 'too-obscure'], + ['id' => 5, 'username' => 'other', 'email' => 'other@machine.local', 'is_email_confirmed' => 1, 'password' => 'too-obscure'], ], 'groups' => [ ['id' => 100, 'name_singular' => 'Support Staff', 'name_plural' => 'Support Staff', 'is_hidden' => 0], @@ -117,17 +116,6 @@ private function replyBody(int $ticketId = 1, string $content = 'Another reply') ]; } - /** - * @param array $json - */ - private function guestRequest(string $method, string $path, array $json = [], string $ip = '127.0.0.1'): ServerRequestInterface - { - $request = (new ServerRequest(['REMOTE_ADDR' => $ip], [], $path, $method)) - ->withAttribute('bypassCsrfToken', true); - - return $this->requestWithJsonBody($request, $json); - } - #[Test] public function normal_user_rapid_ticket_creation_is_throttled(): void { @@ -140,7 +128,7 @@ public function normal_user_rapid_ticket_creation_is_throttled(): void $this->assertEquals(201, $response1->getStatusCode()); // An immediate repeat attempt by the same actor must be stopped at the - // middleware layer with 429 Too Many Requests and a detail message. + // middleware layer with 429 too_many_requests before any database write. $response2 = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ 'authenticatedAs' => 2, @@ -151,12 +139,76 @@ public function normal_user_rapid_ticket_creation_is_throttled(): void $body2 = json_decode((string) $response2->getBody(), true); $this->assertSame('too_many_requests', $body2['errors'][0]['code'] ?? null); - $this->assertNotEmpty($body2['errors'][0]['detail'] ?? null); // Exactly 1 new ticket was created (1 from fixture + 1 from first request). $this->assertEquals(2, $this->database()->table('linkrobins_support_tickets')->count()); } + #[Test] + public function throttle_cooldown_expires_after_timeout(): void + { + $originalTimeout = TicketCreationThrottler::$timeout; + TicketCreationThrottler::$timeout = 1; + + try { + $first = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Ticket 1', 'Content 1'), + ]) + ); + $this->assertEquals(201, $first->getStatusCode()); + + $blocked = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Blocked Retry', 'Content'), + ]) + ); + $this->assertEquals(429, $blocked->getStatusCode()); + + sleep(2); + + $afterCooldown = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('After Cooldown', 'Content 2'), + ]) + ); + $this->assertEquals(201, $afterCooldown->getStatusCode()); + } finally { + TicketCreationThrottler::$timeout = $originalTimeout; + } + } + + #[Test] + public function one_users_cooldown_does_not_affect_another_user(): void + { + $user2First = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('User 2 Ticket', 'Content'), + ]) + ); + $this->assertEquals(201, $user2First->getStatusCode()); + + $user2Blocked = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('User 2 Retry', 'Content'), + ]) + ); + $this->assertEquals(429, $user2Blocked->getStatusCode()); + + $user5Allowed = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 5, + 'json' => $this->ticketBody('User 5 Ticket', 'Content'), + ]) + ); + $this->assertEquals(201, $user5Allowed->getStatusCode()); + } + #[Test] public function normal_user_rapid_replies_are_not_throttled(): void { @@ -293,29 +345,21 @@ public function general_quota_exceeded_returns_403_forbidden(): void } #[Test] - public function guests_are_throttled_by_ip(): void + public function guests_are_rejected_without_triggering_throttle(): void { - $ip = '198.51.100.1'; - - // A rejected guest attempt (401/403) must not record an anti-flood hit. - $req1 = $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Guest Ticket 1', 'Content'), $ip); - $response1 = $this->send($req1); - $this->assertNotEquals(429, $response1->getStatusCode()); - - // Record a hit for that IP (simulating a successful IP-keyed submission). - $this->app()->getContainer()->make(TicketCreationThrottler::class)->recordHit($req1, new Guest()); - - // Rapid repeat attempt by the same guest IP is throttled with 429. - $response2 = $this->send( - $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Guest Ticket 2', 'Content'), $ip) + $response1 = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'json' => $this->ticketBody('Guest Ticket 1', 'Content'), + ]) ); - $this->assertEquals(429, $response2->getStatusCode()); + $this->assertContains($response1->getStatusCode(), [401, 403]); - // A different guest IP is not affected by the first IP's cooldown. - $response3 = $this->send( - $this->guestRequest('POST', '/api/linkrobins-support-tickets', $this->ticketBody('Other Guest Ticket', 'Content'), '198.51.100.2') + $response2 = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'json' => $this->ticketBody('Guest Ticket 2', 'Content'), + ]) ); - $this->assertNotEquals(429, $response3->getStatusCode()); + $this->assertContains($response2->getStatusCode(), [401, 403]); } #[Test] @@ -410,16 +454,142 @@ public function quota_cache_is_cleared_on_delete_restore_category_and_type_chang $this->assertFalse($cache->has($cacheKey)); } + #[Test] + public function quota_cache_is_cleared_after_successful_ticket_create(): void + { + $this->setting('linkrobins-support.general_limit_per_window', '2'); + $this->setting('linkrobins-support.general_window_hours', '24'); + + $container = $this->app()->getContainer(); + /** @var CacheRepository $cache */ + $cache = $container->make(CacheRepository::class); + /** @var SupportRateLimiter $rateLimiter */ + $rateLimiter = $container->make(SupportRateLimiter::class); + + $user2 = User::findOrFail(2); + $user5 = User::findOrFail(5); + $generalCategory = SupportCategory::findOrFail(1); + $appealCategory = SupportCategory::findOrFail(2); + + $generalKey = 'linkrobins_support.quota.general.2.24h'; + $openAppealsKey = 'linkrobins_support.quota.open_appeals.5'; + $windowAppealsKey = 'linkrobins_support.quota.appeals.5.30d'; + + // Warm user 2 general quota cache (1 < limit 2). + $beforeGeneral = $rateLimiter->check($user2, $generalCategory); + $this->assertTrue($beforeGeneral['ok']); + $this->assertTrue($cache->has($generalKey)); + + $generalCreate = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('User 2 Second Ticket', 'Content', 1), + ]) + ); + $this->assertEquals(201, $generalCreate->getStatusCode()); + $this->assertFalse($cache->has($generalKey)); + + $afterGeneral = $rateLimiter->check($user2, $generalCategory); + $this->assertFalse($afterGeneral['ok']); + $this->assertEquals(SupportRateLimiter::REASON_GENERAL_QUOTA, $afterGeneral['reason']); + $this->assertEquals(2, $afterGeneral['meta']['count']); + + // Warm user 5 appeal quota caches and verify appeal creation clears both. + $beforeAppeal = $rateLimiter->check($user5, $appealCategory); + $this->assertTrue($beforeAppeal['ok']); + $this->assertTrue($cache->has($openAppealsKey)); + $this->assertTrue($cache->has($windowAppealsKey)); + + $appealCreate = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 5, + 'json' => $this->ticketBody('User 5 Appeal', 'Appeal body', 2), + ]) + ); + $this->assertEquals(201, $appealCreate->getStatusCode()); + $this->assertFalse($cache->has($openAppealsKey)); + $this->assertFalse($cache->has($windowAppealsKey)); + + $afterAppeal = $rateLimiter->check($user5, $appealCategory); + $this->assertFalse($afterAppeal['ok']); + $this->assertEquals(SupportRateLimiter::REASON_APPEAL_HAS_OPEN, $afterAppeal['reason']); + } + + #[Test] + public function locked_transaction_recheck_ignores_stale_cached_quota(): void + { + $this->setting('linkrobins-support.general_limit_per_window', '1'); + $this->setting('linkrobins-support.general_window_hours', '24'); + + $container = $this->app()->getContainer(); + /** @var CacheRepository $cache */ + $cache = $container->make(CacheRepository::class); + + // Seed a stale cached count of 0 so creating() passes the fast path, + // forcing the row-locked check in create() (fresh: true) to catch the + // existing committed ticket #1 for user 2. + $cache->put('linkrobins_support.quota.general.2.24h', 0, 60); + + $response = $this->send( + $this->request('POST', '/api/linkrobins-support-tickets', [ + 'authenticatedAs' => 2, + 'json' => $this->ticketBody('Bypass Attempt', 'Content', 1), + ]) + ); + $this->assertEquals(403, $response->getStatusCode()); + $this->assertEquals(1, $this->database()->table('linkrobins_support_tickets')->where('user_id', 2)->count()); + } + + #[Test] + public function quota_cache_stays_accurate_against_real_database_counts(): void + { + $this->setting('linkrobins-support.appeal_max_concurrent_open', '2'); + $this->setting('linkrobins-support.appeal_limit_per_window', '3'); + $this->setting('linkrobins-support.appeal_window_days', '30'); + $this->setting('linkrobins-support.general_limit_per_window', '1'); + $this->setting('linkrobins-support.general_window_hours', '24'); + + $now = Carbon::now(); + $this->database()->table('linkrobins_support_tickets')->insert([ + ['category_id' => 2, 'user_id' => 5, 'subject' => 'Open Appeal', 'status' => 'open', 'last_reply_at' => $now, 'created_at' => $now, 'updated_at' => $now, 'deleted_at' => null], + ['category_id' => 2, 'user_id' => 5, 'subject' => 'Resolved Appeal', 'status' => 'resolved', 'last_reply_at' => $now, 'created_at' => $now, 'updated_at' => $now, 'deleted_at' => null], + ['category_id' => 2, 'user_id' => 5, 'subject' => 'Trashed Appeal', 'status' => 'open', 'last_reply_at' => $now, 'created_at' => $now, 'updated_at' => $now, 'deleted_at' => $now], + ['category_id' => 2, 'user_id' => 5, 'subject' => 'Expired Appeal', 'status' => 'resolved', 'last_reply_at' => $now->copy()->subDays(31), 'created_at' => $now->copy()->subDays(31), 'updated_at' => $now->copy()->subDays(31), 'deleted_at' => null], + ['category_id' => 1, 'user_id' => 5, 'subject' => 'Recent General', 'status' => 'open', 'last_reply_at' => $now, 'created_at' => $now, 'updated_at' => $now, 'deleted_at' => null], + ]); + + $container = $this->app()->getContainer(); + /** @var SupportRateLimiter $rateLimiter */ + $rateLimiter = $container->make(SupportRateLimiter::class); + + $user5 = User::findOrFail(5); + $generalCategory = SupportCategory::findOrFail(1); + $appealCategory = SupportCategory::findOrFail(2); + + // Open appeal count = 1 (< 2), while 30d window count = 3 (includes resolved + trashed, excludes 31d-old). + $appealCheck = $rateLimiter->check($user5, $appealCategory); + $this->assertFalse($appealCheck['ok']); + $this->assertEquals(SupportRateLimiter::REASON_APPEAL_QUOTA, $appealCheck['reason']); + $this->assertEquals(3, $appealCheck['meta']['count']); + + // General 24h count = 1. + $generalCheck = $rateLimiter->check($user5, $generalCategory); + $this->assertFalse($generalCheck['ok']); + $this->assertEquals(SupportRateLimiter::REASON_GENERAL_QUOTA, $generalCheck['reason']); + $this->assertEquals(1, $generalCheck['meta']['count']); + } + #[Test] public function unrelated_routes_are_not_throttled(): void { // User creates a ticket, consuming their rate limit for ticket creation. - $this->send( + $create = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ 'authenticatedAs' => 2, 'json' => $this->ticketBody('Ticket 1', 'Content'), ]) ); + $this->assertEquals(201, $create->getStatusCode()); // Unrelated endpoints (e.g. categories index) must not be throttled. $response = $this->send( diff --git a/tests/unit/RateLimiterCacheTest.php b/tests/unit/RateLimiterCacheTest.php index 0df355a..37215cc 100644 --- a/tests/unit/RateLimiterCacheTest.php +++ b/tests/unit/RateLimiterCacheTest.php @@ -1,5 +1,12 @@ shouldReceive('remember') - ->with('linkrobins_support.quota.general.2.24h', 300, m::type('callable')) + ->with('linkrobins_support.quota.general.2.24h', RateLimiter::CACHE_TTL, m::type('callable')) ->once() ->andReturn(2); @@ -84,7 +91,7 @@ public function general_check_fails_when_cached_count_exceeds_limit(): void // When cache returns 5 (reaches limit), check should fail. $cache->shouldReceive('remember') - ->with('linkrobins_support.quota.general.2.24h', 300, m::type('callable')) + ->with('linkrobins_support.quota.general.2.24h', RateLimiter::CACHE_TTL, m::type('callable')) ->once() ->andReturn(5); @@ -97,6 +104,77 @@ public function general_check_fails_when_cached_count_exceeds_limit(): void $this->assertEquals(5, $result['meta']['limit']); } + #[Test] + public function appeal_check_uses_cache_remember_for_open_and_window_counts(): void + { + $settings = m::mock(SettingsRepositoryInterface::class); + $settings->shouldReceive('get')->with('linkrobins-support.appeal_max_concurrent_open', 1)->andReturn(2); + $settings->shouldReceive('get')->with('linkrobins-support.appeal_limit_per_window', 3)->andReturn(3); + $settings->shouldReceive('get')->with('linkrobins-support.appeal_window_days', 30)->andReturn(30); + + $translator = m::mock(TranslatorInterface::class); + $cache = m::mock(CacheRepository::class); + $typeManager = m::mock(TicketTypeManager::class); + + $cache->shouldReceive('remember') + ->with('linkrobins_support.quota.open_appeals.2', RateLimiter::CACHE_TTL, m::type('callable')) + ->once() + ->andReturn(1); + $cache->shouldReceive('remember') + ->with('linkrobins_support.quota.appeals.2.30d', RateLimiter::CACHE_TTL, m::type('callable')) + ->once() + ->andReturn(2); + + $limiter = new RateLimiter($settings, $translator, $cache, $typeManager); + $result = $limiter->check($this->user(2), $this->category(isAppeal: true)); + + $this->assertTrue($result['ok']); + $this->assertEquals(RateLimiter::REASON_OK, $result['reason']); + } + + #[Test] + public function fresh_check_bypasses_cache_remember(): void + { + $settings = m::mock(SettingsRepositoryInterface::class); + $settings->shouldReceive('get')->with('linkrobins-support.general_limit_per_window', 10)->andReturn(2); + $settings->shouldReceive('get')->with('linkrobins-support.general_window_hours', 24)->andReturn(24); + $settings->shouldReceive('get')->with('linkrobins-support.appeal_max_concurrent_open', 1)->andReturn(2); + $settings->shouldReceive('get')->with('linkrobins-support.appeal_limit_per_window', 3)->andReturn(3); + $settings->shouldReceive('get')->with('linkrobins-support.appeal_window_days', 30)->andReturn(30); + + $translator = m::mock(TranslatorInterface::class); + $cache = m::mock(CacheRepository::class); + $cache->shouldNotReceive('remember'); + $typeManager = m::mock(TicketTypeManager::class); + + $limiter = new class($settings, $translator, $cache, $typeManager) extends RateLimiter { + protected function queryGeneralTicketsForUserSince(User $actor, Carbon $since): int + { + return 2; + } + + protected function queryOpenAppealsForUser(User $actor): int + { + return 1; + } + + protected function queryAppealsForUserSince(User $actor, Carbon $since): int + { + return 3; + } + }; + + $general = $limiter->check($this->user(2), $this->category(isAppeal: false), fresh: true); + $this->assertFalse($general['ok']); + $this->assertEquals(RateLimiter::REASON_GENERAL_QUOTA, $general['reason']); + $this->assertEquals(2, $general['meta']['count']); + + $appeal = $limiter->check($this->user(2), $this->category(isAppeal: true), fresh: true); + $this->assertFalse($appeal['ok']); + $this->assertEquals(RateLimiter::REASON_APPEAL_QUOTA, $appeal['reason']); + $this->assertEquals(3, $appeal['meta']['count']); + } + #[Test] public function clear_user_quota_cache_forgets_all_user_keys(): void { From 8248768143fe476b20758cbb92b482e49daebb13 Mon Sep 17 00:00:00 2001 From: huoxin <23447157+huoxin233@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:29:00 +0800 Subject: [PATCH 8/8] fix: type rememberCount Closure for PHPStan and bypass CSRF in guest throttle test - Type RateLimiter::rememberCount callback as Closure(): int so PHPStan resolves Cache::remember TCacheValue - Pass bypassCsrfToken on unauthenticated guest POSTs in TicketThrottleTest so auth/policy returns 401/403 instead of 400 Co-authored-by: Claude --- src/RateLimiter.php | 7 +++++-- tests/integration/api/TicketThrottleTest.php | 4 ++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/RateLimiter.php b/src/RateLimiter.php index 87dd052..da907aa 100644 --- a/src/RateLimiter.php +++ b/src/RateLimiter.php @@ -211,13 +211,16 @@ protected function appealTicketTypeIds(): array return $this->ticketTypeManager->appealIds() ?: [AppealTicketType::ID]; } - protected function rememberCount(string $key, bool $fresh, callable $query): int + /** + * @param \Closure(): int $query + */ + protected function rememberCount(string $key, bool $fresh, \Closure $query): int { if ($fresh) { return (int) $query(); } - return (int) $this->cache->remember($key, self::CACHE_TTL, $query); + return $this->cache->remember($key, self::CACHE_TTL, fn (): int => (int) $query()); } protected function countOpenAppealsForUser(User $actor, bool $fresh = false): int diff --git a/tests/integration/api/TicketThrottleTest.php b/tests/integration/api/TicketThrottleTest.php index 055f620..46d064d 100644 --- a/tests/integration/api/TicketThrottleTest.php +++ b/tests/integration/api/TicketThrottleTest.php @@ -350,14 +350,14 @@ public function guests_are_rejected_without_triggering_throttle(): void $response1 = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ 'json' => $this->ticketBody('Guest Ticket 1', 'Content'), - ]) + ])->withAttribute('bypassCsrfToken', true) ); $this->assertContains($response1->getStatusCode(), [401, 403]); $response2 = $this->send( $this->request('POST', '/api/linkrobins-support-tickets', [ 'json' => $this->ticketBody('Guest Ticket 2', 'Content'), - ]) + ])->withAttribute('bypassCsrfToken', true) ); $this->assertContains($response2->getStatusCode(), [401, 403]); }