Loading
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.
EmbedCorsMiddlewarehandles/ai-answers/question,/ai-answers/feedback,/ai-answers/widget/placement/{uuid}and.../{uuid}/token. It answersOPTIONSwith a 204, echoesAccess-Control-Allow-Originonly for an origin a placement allows, always sendsVary: Origin, and never sendsAccess-Control-Allow-Credentials. Core'scors.configis untouched. - Embed token.
EmbedTokensigns<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}/tokenreturns{token, expires}withCache-Control: no-store, private, only whenOriginis on the placement's allowlist (403 otherwise, 404 for an unknown or disabled placement). The cached widget payload only gainsurls.token. No token goes in it. - Access check.
_ai_answers_endpoint_accessreplaces_permissionon the question and feedback routes. WithoutX-AI-Answers-Tokenit is theuse ai answerspermission, as before. With it, the body must name an enabledplacement(and noagent),Originmust be on its allowlist, and the token must match placement + origin and not be expired. No permission needed._csrf_request_header_tokenstays on both routes. - Docs.
placements.mdgets "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 andarchitecture.mdpoint to it.
Decisions to review
- 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, abovepage_cache(200) and below core'scors(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. - 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
Originon POST. - 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-Originfor 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. - The
X-AI-Answers-Tokenheader 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 needsX-CSRF-Token. Cross-origin embeds send no cookies, so they're anonymous and core's check passes them. - 30 minute lifetime, stateless. The allowlist and
statusare checked again on every request, so removing an origin or disabling the placement takes effect at once, without waiting for expiry or storing tokens. - Exact origin match. No normalising:
AiAnswersOriginConstraintalready stores origins as a browser sends them. - A refused preflight gets a 204 with no CORS headers, not a 403. The browser stops either way, and it tells the caller nothing.
- 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. - 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
floodlimiter inPlacementResolver::checkQuestion(),checkFeedback()andPlacementWidgetController::token()(each has a note), default limits inai_answers.settings, 429 withRetry-After, and the widget's message. - MR 2 also needs
Access-Control-Expose-Headers: Retry-AfterinEmbedCorsMiddleware, 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 wrongOrigin, 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, noOrigin, 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)