feat: #3615766 Rate limit placements with a shared flood limiter: per IP and per placement, defaults in ai_answers.settings, 429 with Retry-After

Stacked on !33 (merged) and #3615766 (closed) MR 1 (!35 (merged)); review only the last commit(s) until those merge. The branch starts at the tip of 3615766-cors-embed-token (59845e27, !35 (merged)), which starts at !33 (merged)'s tip (4896f2c2). This MR's own change is 2831f5b.

MR 2 of 2. Closes #3615766 (closed).

Point 4 of the issue: the placement endpoints are now rate limited. MR 1 opened them to anonymous visitors on allowed origins, and its origin and token checks don't stop scripts. This does.

What this adds

  • RateLimiter (ai_answers.rate_limiter) on core's flood. Named checks for a placement's questions, feedback and tokens, plus a generic hit() that #3615774 (closed) reuses for on-site questions. A request counts against all its buckets or none: a request refused by one bucket isn't counted in the other.
  • Where it runs. In PlacementResolver::checkQuestion() and checkFeedback(), after the placement checks, so both access paths are covered and a refused request isn't counted. In PlacementWidgetController::token(), after the origin check. These are the spots MR 1 marked.
  • What it counts. Questions per IP + placement (20 per 10 min) and per placement (300 per hour), both overridable on the placement, null = default. Feedback per IP + placement (60 per 10 min) and tokens per IP + placement (120 per 10 min), site defaults only.
  • 429. JSON {error, retry_after} with Retry-After and Cache-Control: no-store, private, before any stream opens, also on the SSE path. error is translated.
  • CORS. EmbedCorsMiddleware adds Access-Control-Expose-Headers: Retry-After to allowed non-preflight responses. Without it the widget can't read the header cross-origin.
  • Defaults in a new ai_answers.settings (FullyValidatable schema) under rate_limits, with a post update for existing sites.
  • Docs. placements.md gets "Rate limits": what is counted, defaults, how to change them, proxies, recommended limits, and "Handling a 429", the contract for the widget JS in #3615769 (closed). The known-gaps entry for placement limits is gone; a smaller one for on-site questions points to #3615774 (closed).

Decisions to review

  1. Fixed windows, not flood's sliding one. Flood counts events in the last window seconds and can't say when the oldest leaves, so Retry-After could only be the whole window (an hour for per_placement). The window's start goes in the flood identifier instead, so each window has its own counter and Retry-After is exact. The cost: a burst across a boundary can pass up to 2x count.
  2. The placement's rate_limits apply to questions only. Feedback and tokens cost no LLM call, so they get looser site defaults and no per-placement field. The form already says "Requests", which reads as questions there.
  3. Fail closed on bad config. A missing or invalid default falls back to RateLimiter::DEFAULTS, never to "no limit".
  4. Check, then register. 2 queries, not atomic, so parallel bursts can pass a few over. Documented. Flood has no atomic increment.
  5. No settings form. None exists in the module yet; the defaults are set by config import or Drush, documented with an example. Happy to add one in a follow-up.
  6. Post update added although the issue says 1.1.x needs no update path. Dev sites run 1.1.x, and it does nothing when the config is there.
  7. The token endpoint is limited per IP, as MR 1 planned. It costs no LLM call, but it's the first step a script takes.

For #3615769 (closed) (widget JS)

On a 429 from any of the 3 POSTs: show a short message (error, or one built from retry_after), keep the question in the input, don't retry or fetch a new token before Retry-After, keep the conversation_id. On a 429 from the token endpoint, wait and try once more. Details in docs/placements.md#handling-a-429.

Testing

  • RateLimiterTest (Kernel, 7), on a clock the test moves: a window fills, refuses to the second, and has room again when it ends; all-or-nothing across buckets; the longest wait wins; defaults from config, built-in and on bad config; per IP vs per placement, placement override vs default, null = default; feedback and token limits separate from questions; the 429 body; the post update.
  • EmbedRateLimitTest (Kernel, 4), over HTTP: 429 + Retry-After + Access-Control-Allow-Origin + Expose-Headers on question (JSON and SSE), feedback and token; another IP has its own count; refused requests (bad token, unlisted origin) don't count; the on-site path with a placement is limited too.
  • EmbedCorsTest: Expose-Headers on allowed responses only, not on preflights, and a stale one from the page cache replaced.
  • Locally on 11.4 / PHP 8.4, the full module suite with ai_answers_log: 253 tests, 244 pass. The 9 that fail are the FunctionalJavascript tests, because this site has no WebDriver, so the pipeline is the first run for those. PHPCS (Drupal, DrupalPractice) has 0 errors; its 2 warnings are already on 1.1.x, in a file this MR doesn't touch. PHPStan is clean. CSpell and ESLint are clean on the changed files.
AI disclosure

Used AI to help with research, writing and code (reading the flood service and MR 1's seams, writing the limiter, its wiring and tests, drafting this description). The reasoning and positions are my own, and I reviewed everything before posting. (Drupal.org AI policy)

Merge request reports

Loading
Loading