Skip to content

perf: cache ticket quotas and add anti-flood rate limiting for creation endpoints - #69

Open
huoxin233 wants to merge 6 commits into
linkrobins:mainfrom
huoxin233:perf/cache-rate-limiting
Open

huoxin233 wants to merge 6 commits into
linkrobins:mainfrom
huoxin233:perf/cache-rate-limiting

Conversation

@huoxin233

Copy link
Copy Markdown
Contributor

Summary

This PR introduces native caching for ticket and appeal quotas to eliminate repetitive COUNT(*) queries on ticket submission, and implements an HTTP-level anti-flood throttler via Flarum's ThrottleApi extender to prevent rapid-fire ticket and reply spam.


Key Changes

1. Accelerated Quota Rate Limiting via Cache (RateLimiter)

  • Native Cache Integration: Injected Illuminate\Contracts\Cache\Repository into RateLimiter to store rolling count checks (general quota window, appeal window, open appeals count) with a 5-minute TTL (300s).
  • Cache Invalidation: Added clearUserQuotaCache() to automatically evict a user's cached quota keys:
    • During ticket creation in SupportTicketResource::creating().
    • On ticket lifecycle changes and status transitions via SupportTicket::updated in SupportServiceProvider.
  • Unit Tests: Added tests/unit/RateLimiterCacheTest.php testing cache hit, miss, quota limit evaluations, and key invalidation.

2. Anti-Flood Throttler (TicketCreationThrottler)

  • Middleware-Layer Flood Protection: Implemented TicketCreationThrottler registered in extend.php via (new Extend\ThrottleApi)->set('linkrobinsSupportTicketTimeout', TicketCreationThrottler::class).
  • 10-Second Cooldown: Rejects rapid-fire repeat attempts with 429 Too Many Requests before any controller logic or database write begins.
  • Action Isolation: Differentiates cache keys by route (linkrobins_support.throttle.ticket.* vs linkrobins_support.throttle.reply.*) so opening a ticket does not lock a user out of follow-up replies.
  • Guest Protection: Throttles unauthenticated guests by remote IP (sha1(ipAddress)).
  • Staff Exemption: Automatically bypasses users holding the lr-support.handle_tickets permission or Flarum core's postWithoutThrottle permission.

3. Full HTTP Integration Tests (TicketThrottleTest)

  • Added tests/integration/api/TicketThrottleTest.php extending TestCase:
    • normal_user_rapid_ticket_creation_is_throttled: Verifies first ticket returns 201 and immediate second ticket returns 429 with zero database writes.
    • normal_user_rapid_reply_is_throttled: Verifies repeat replies are blocked with 429.
    • guests_are_throttled_by_ip: Verifies guest IP cooldown and IP isolation.
    • unrelated_routes_are_not_throttled: Confirms non-creation routes (e.g. categories index) remain unthrottled.
    • staff_with_handle_tickets_permission_is_exempt_from_throttle & user_with_post_without_throttle_permission_is_exempt: Verifies bypass permissions.
    • general_quota_exceeded_returns_403_forbidden: Verifies business quota boundaries (403 Forbidden with localized error messages) distinct from anti-flood rate limits (429).
    • Includes allowedRepeatedQueries() for N+1 query regression monitoring.

huoxin233 and others added 2 commits November 8, 2026 02:31
- 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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>

@karl-bullock karl-bullock left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! The quota cache and the throttle both work (I ran them on a test site: staff are exempt, quotas still apply, and the 429 shows a clear message in the UI). A few changes before merging:

  1. Only successful submissions should start the cooldown. TicketCreationThrottler calls hit() before the controller runs, so a request that fails validation (400/422, e.g. an empty subject) or a quota refusal (403) still burns the 10 s window. On the test site: an empty subject → 400, then the corrected ticket right after → 429 with no explanation. Please count a hit only after the create succeeds.
  2. Please drop the reply throttle and keep it for new tickets only. One reply per 10 s gets in the way of a normal back-and-forth with staff, and ticket creation is where flooding actually hurts (the description also only mentions creation endpoints).
  3. Clear the quota cache after commit, and on the other paths that change counts. In SupportTicketResource::create (~line 586) the cache is cleared inside the transaction, before commit, so a concurrent check can re-cache the old count. Please clear it after commit, and also on soft-delete / restore / force-delete and when a ticket's category or type changes.
  4. The 429 response body has no message ({"errors":[{"status":"429","code":"too_many_requests"}]}); the UI text comes from the client. A detail with a short message would help API clients. Optional.

Also, this conflicts with #68 in SupportServiceProvider.php (this branch still calls recordChanges, which #68 removes). I plan to merge #68 first, so please rebase onto main once that lands.

Thanks again!

@huoxin233
huoxin233 marked this pull request as draft November 8, 2026 15:51
huoxin233 and others added 2 commits November 18, 2026 23:28
…he 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 <noreply@anthropic.com>
@huoxin233

Copy link
Copy Markdown
Contributor Author

All fixed!

@huoxin233
huoxin233 marked this pull request as ready for review November 18, 2026 15:39
huoxin233 and others added 2 commits November 18, 2026 23:42
…ttings 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 <noreply@anthropic.com>
…Type change

Co-authored-by: Claude <noreply@anthropic.com>
@karl-bullock

Copy link
Copy Markdown
Member

Thanks, I rechecked the head at cc0eaff.

1-3 are done and I am satisfied with how: the hit lands in SupportTicketResource.php:564/:610, the quota 403 is thrown inside the transaction so it rolls back without burning the window, the reply throttle is gone (one route check in TicketCreationThrottler.php:33), and the cache is cleared after commit and on the status, type, deleted and force-delete paths. The tests for the failed-validation and quota-refusal cases are the right shape.

Item 4 does not work as written, and the test hides it. FloodingException's message never reaches the response: JsonApiFormatter only emits detail from HandledError::withDetails(), and a known-type HandledError has no details. The assertion at TicketThrottleTest.php:154 passes because the test site is installed with debugMode(true), where detail is the exception string with a stack trace — it would pass on the old code too. Either register an error handler for a FloodingException subclass that returns withDetails([['detail' => $message]]) and assert the exact string, or drop the message and the locale key and say the item is declined.

One regression comes with the cache. SupportTicketResource.php:547-555 documents the row lock as making the check and insert atomic, but the check at :581 now reads RateLimiter::check(), which goes through cache->remember() (RateLimiter.php:262-267). Two requests can still get one extra ticket through: B can cache the pre-insert count in creating() and write it after A's clearUserQuotaCache(), or read it in the gap before A's after-commit clear. Please keep the cache on the creating() fast path and read the count uncached inside the transaction.

Smaller ones:

  • The 300s TTL can keep a user blocked up to five minutes after their window would have admitted them, since nothing invalidates when tickets age out. 30-60s keeps the saving without the odd wait.
  • clearUserQuotaCache() and recordHit() run after commit with no try/catch, so a full storage/cache turns a committed ticket into a 500 with no cooldown, and the retry files a duplicate. The same warning-log treatment as SupportServiceProvider.php:133-135 would cover it.
  • The guest/IP branch (TicketCreationThrottler.php:78-81) is unreachable: guests cannot create tickets (GlobalPolicy.php:31-37). Drop it, or keep it with a comment saying it is defensive.
  • Returning false at :41 disables every throttler on the request (ThrottleApi.php:38-40), not just this one. null does the same job here.
  • Tests: there is no coverage of the cache being cleared after a successful create (the path item 3 is about), of the cooldown expiring, or of one user's cooldown not affecting another. :417-430 never asserts the first create returned 201. RateLimiterCacheTest only checks the remember/forget arguments, so the query closures never run — fine as a key guard, but it is not testing the counts, and it is missing the license header.
  • The description still advertises reply throttling and the per-route throttle.ticket.*/throttle.reply.* keys, and says the cache is cleared in creating(). It does not match the diff.

The cache and the throttle are per-server: Flarum binds the cache to the file store, so with more than one app server each node keeps its own stale count and cooldown. Fine for a single host, but worth one line in the PR.

Thanks!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants