feat: #3615766 Let other origins use a placement: per-placement CORS, an origin-bound embed token and its access check

Stacked on !33 (merged); review only the last commit(s) until !33 (merged) merges. The branch starts at the tip of 3615768-placement-render-endpoint (4896f2c2), so the diff shows !33 (merged)'s 2 commits too. This MR's own change is 59845e2.

MR 1 of 2 for #3615766 (closed): points 1 to 3 of the issue (CORS, embed token, route access). Rate limiting is MR 2, so this doesn't close the issue.

What this adds

  • CORS for the embed paths only. EmbedCorsMiddleware handles /ai-answers/question, /ai-answers/feedback, /ai-answers/widget/placement/{uuid} and .../{uuid}/token. It answers OPTIONS with a 204, echoes Access-Control-Allow-Origin only for an origin a placement allows, always sends Vary: Origin, and never sends Access-Control-Allow-Credentials. Core's cors.config is untouched.
  • Embed token. EmbedToken signs <expires>.<hmac>, an HMAC-SHA256 over placement UUID + origin + expiry, keyed with the private key and hash salt like core's CSRF tokens. Valid for 30 minutes. Nothing is stored.
  • Token endpoint. POST /ai-answers/widget/placement/{uuid}/token returns {token, expires} with Cache-Control: no-store, private, only when Origin is on the placement's allowlist (403 otherwise, 404 for an unknown or disabled placement). The cached widget payload only gains urls.token. No token goes in it.
  • Access check. _ai_answers_endpoint_access replaces _permission on the question and feedback routes. Without X-AI-Answers-Token it is the use ai answers permission, as before. With it, the body must name an enabled placement (and no agent), Origin must be on its allowlist, and the token must match placement + origin and not be expired. No permission needed. _csrf_request_header_token stays on both routes.
  • Docs. placements.md gets "Embedding on another site": the client contract for #3615769 (closed), the token, the CORS rules, what the origin checks do and don't stop, and bearer-by-id conversations. The known-gaps entry now covers only the rate limits. README and architecture.md point to it.

Decisions to review

  1. A middleware, not the event subscriber the issue describes. The widget response is a CacheableJsonResponse, so the internal page cache stores it and serves hits without running the kernel. A response subscriber would store the first origin's header and never run on later hits. The middleware sits at priority 220, above page_cache (200) and below core's cors (250), and adds the headers after the cache has stored the response. Since it runs before modules load, it reads placements as raw config, not entities.
  2. The token comes from a separate POST route, not the widget payload or a GET. The payload is cached and must stay per-visitor-free, as !33 (merged) says. POST means no cache on the way keeps a token, and browsers always send Origin on POST.
  3. Question and feedback CORS accepts any enabled placement's origin. A preflight has no body, so it can't name the placement. The token then decides whether the request gets in. Those responses, including the 403, carry Access-Control-Allow-Origin for such an origin, so the widget can read the 403 and fetch a new token instead of getting a network error. The widget and token paths name their placement, so only its own allowlist counts there.
  4. The X-AI-Answers-Token header picks the path. A request with it is checked only as an embed, so a bad token is refused even for a user with the permission. Keeping core's CSRF requirement means a token is no way around CSRF: a request with a session cookie still needs X-CSRF-Token. Cross-origin embeds send no cookies, so they're anonymous and core's check passes them.
  5. 30 minute lifetime, stateless. The allowlist and status are checked again on every request, so removing an origin or disabling the placement takes effect at once, without waiting for expiry or storing tokens.
  6. Exact origin match. No normalising: AiAnswersOriginConstraint already stores origins as a browser sends them.
  7. A refused preflight gets a 204 with no CORS headers, not a 403. The browser stops either way, and it tells the caller nothing.
  8. One optional leading path segment is accepted, for a language prefix (/fr/ai-answers/question). The middleware runs before path processing, so it can't ask the router.
  9. The access check's 403 is core's HTML 403 page, as today. The routes have no _format, and the widget only needs the status.

Left for MR 2

  • The shared flood limiter in PlacementResolver::checkQuestion(), checkFeedback() and PlacementWidgetController::token() (each has a note), default limits in ai_answers.settings, 429 with Retry-After, and the widget's message.
  • MR 2 also needs Access-Control-Expose-Headers: Retry-After in EmbedCorsMiddleware, or the widget can't read it cross-origin.

Testing

  • EmbedTokenTest (Kernel, 4): binding to placement and origin, a signed expiry, tampered and malformed tokens, another private key, expiry to the second, and the token endpoint (200, 403 without or with a wrong Origin, 404, 405 for GET, no token in the widget payload).
  • EmbedCorsTest (Kernel, 4): allowed, other-placement, disabled-placement, unknown and missing origins on the widget path, exact matching, preflight on all 5 paths, other paths left alone, and a stale header on a cached response replaced per origin.
  • EmbedEndpointAccessTest (Kernel, 4): an anonymous visitor asks, follows up, rates and streams with a token. Refused: no token, another allowed origin, no Origin, unlisted origin, another placement's token, tampered, empty, agent, both, no body, expired, origin removed, placement disabled. A user with the permission and a bad token is refused, and without the header the permission path still works.
  • AiAnswersEndpointsTest::testEmbedToken (Functional): the real flow over HTTP (token, then feedback, then preflight), then the on-site CSRF path with a session, a token sent with a session cookie but no CSRF header (403), and a bad token with permission and CSRF (403).
  • Locally on 11.4 / PHP 8.4, the full module suite: 242 tests, 233 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 is clean on the changed files, and ESLint on the changed YAML.
AI disclosure

Used AI to help with research, writing and code (reading the access and caching paths, writing the middleware, token, access check 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