Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions extend.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,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'))
Expand Down Expand Up @@ -296,4 +297,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),
];
46 changes: 41 additions & 5 deletions src/Api/Resource/SupportTicketResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -557,21 +559,24 @@ 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);
$this->recordPostCreateSideEffects($actor, $context, clearCache: ! $actor->isGuest());

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,
// 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));
}
Expand All @@ -595,6 +600,37 @@ 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->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,
]);
}
}
}

/**
Expand Down
87 changes: 73 additions & 14 deletions src/RateLimiter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -26,9 +27,13 @@
*/
class RateLimiter
{
public const CACHE_TTL = 60; // 1 minute

public function __construct(
protected SettingsRepositoryInterface $settings,
protected TranslatorInterface $translator,
protected CacheRepository $cache,
protected TicketTypeManager $ticketTypeManager,
) {
}

Expand All @@ -42,21 +47,24 @@ 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) {
return $custom;
}

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)) {
Expand All @@ -68,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, [
Expand All @@ -82,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);
$count = $this->countAppealsForUserSince($actor, $since, $days, $fresh);

if ($count >= $limit) {
return $this->fail(self::REASON_APPEAL_QUOTA, [
Expand All @@ -96,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);
Expand All @@ -105,7 +113,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, $fresh);

if ($count >= $limit) {
return $this->fail(self::REASON_GENERAL_QUOTA, [
Expand Down Expand Up @@ -167,6 +175,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)
Expand All @@ -185,13 +208,31 @@ public function describe(array $result): string
*/
protected function appealTicketTypeIds(): array
{
/** @var TicketTypeManager $manager */
$manager = resolve(TicketTypeManager::class);
return $this->ticketTypeManager->appealIds() ?: [AppealTicketType::ID];
}

/**
* @param \Closure(): int $query
*/
protected function rememberCount(string $key, bool $fresh, \Closure $query): int
{
if ($fresh) {
return (int) $query();
}

return $manager->appealIds() ?: [AppealTicketType::ID];
return $this->cache->remember($key, self::CACHE_TTL, fn (): int => (int) $query());
}

protected function countOpenAppealsForUser(User $actor): int
protected function countOpenAppealsForUser(User $actor, bool $fresh = false): int
{
return $this->rememberCount(
"linkrobins_support.quota.open_appeals.{$actor->id}",
$fresh,
fn () => $this->queryOpenAppealsForUser($actor)
);
}

protected function queryOpenAppealsForUser(User $actor): int
{
$appealTypes = $this->appealTicketTypeIds();

Expand All @@ -208,7 +249,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, bool $fresh = false): int
{
return $this->rememberCount(
"linkrobins_support.quota.appeals.{$actor->id}.{$days}d",
$fresh,
fn () => $this->queryAppealsForUserSince($actor, $since)
);
}

protected function queryAppealsForUserSince(User $actor, Carbon $since): int
{
$appealTypes = $this->appealTicketTypeIds();

Expand All @@ -222,7 +272,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, bool $fresh = false): int
{
return $this->rememberCount(
"linkrobins_support.quota.general.{$actor->id}.{$hours}h",
$fresh,
fn () => $this->queryGeneralTicketsForUserSince($actor, $since)
);
}

protected function queryGeneralTicketsForUserSince(User $actor, Carbon $since): int
{
$appealTypes = $this->appealTicketTypeIds();

Expand Down
71 changes: 69 additions & 2 deletions src/SupportServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -152,6 +157,68 @@ public function boot(Formatter $formatter, Dispatcher $bus, Events $events, Logg
$ticket->status_changed_at = Carbon::now();
}
});

SupportTicket::updated(function (SupportTicket $ticket) use ($rateLimiter, $log) {
if ($ticket->user_id && $ticket->wasChanged(['status', 'category_id', 'deleted_at'])) {
static::clearQuotaCacheAfterCommit($rateLimiter, (int) $ticket->user_id, $log);
}
});

SupportTicket::deleted(function (SupportTicket $ticket) use ($rateLimiter, $log) {
if ($ticket->user_id) {
static::clearQuotaCacheAfterCommit($rateLimiter, (int) $ticket->user_id, $log);
}
});

SupportTicket::restored(function (SupportTicket $ticket) use ($rateLimiter, $log) {
if ($ticket->user_id) {
static::clearQuotaCacheAfterCommit($rateLimiter, (int) $ticket->user_id, $log);
}
});

SupportCategory::updated(function (SupportCategory $category) use ($rateLimiter, $log) {
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, $log) {
foreach ($ids as $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,
]);
}
});
}

/**
Expand Down
Loading
Loading