Static caching: `/!/csrf` and `/!/nocache` race on first visit, page token and session cookie come from different sessions, form POST returns 419
维护者通常 1 天内回复
还没有人认领这个 Issue。
评估
- 难度
- 3/5
- 预计耗时
- 1-2 天
- 新手友好度
- 42/100
- Issue 类型
- 缺陷
- 描述清晰度
- 描述清楚
- 活跃度
- 活跃
- 技术栈
- javascript, laravel, php
调研方向
Start with src/StaticCaching/Replacers/CsrfTokenReplacer.php (lines 78-84) and NoCacheReplacer.php (line 97), then the inline scripts generated in src/StaticCaching/Cachers/FileCacher.php (getCsrfTokenJs and getNocacheJs). Reproduce with the Playwright snippet in the issue, comparing the token source and cookie source on a fresh context. Done when both endpoints return the same session, or the token and cookie come from the same response, and a form POST on a first visit is accepted.
由索引模型根据 Issue 内容生成。
描述
Bug description
The form POST returns 419 Page Expired. A visitor who already has a session cookie (from any earlier non cached request) is not affected, which makes the bug look intermittent.
Measured in headless Chromium, 4 out of 4 fresh profiles: input[name=_token] held the token from the /!/csrf response, the cookie jar held the *_session cookie from the /!/nocache response. The two values belong to different sessions, so the token can never validate.
Expected: The form POST is accepted, Laravel validates the _token against the session referenced by the session cookie.
How to reproduce
- Enable full static caching and warm the cache for a page that has a form and a
{{ nocache }}region. - Open that page in a fresh browser (no cookies for the site).
- Submit the form right away.
Logs
No server log entry. In the browser: POST /!/forms/<handle> returns 419 although it carries a valid looking X-CSRF-Token. The /!/csrf and /!/nocache responses each set a different *_session cookie.
Environment
Environment
Laravel Version: 12.69.3
PHP Version: 8.4
Statamic
Version: 6.35.1 PRO
Static Caching: full (production)
Statamic Addons
studio1902/statamic-peak-tools: 9.0.3
studio1902/statamic-peak-seo: 11.2.0
studio1902/statamic-peak-commands: 10.6.0
ademti-software/form-protection: 1.1.0
Frontend
laravel-precognition 2.0.0, laravel-precognition-alpine 2.0.0
Installation
Starter Kit using via CLI
Additional details
On a cached page two inline scripts run, each firing a POST immediately on execution, with no ordering between them.
src/StaticCaching/Replacers/CsrfTokenReplacer.php injects the csrf script at the top of <head>:
// lines 78-84
$insertBefore = collect([
Str::position($contents, '<link'),
Str::position($contents, '<script'),
Str::position($contents, '</head>'),
])->filter()->min();
$contents = Str::substrReplace($contents, $cacher->getCsrfScript(), $insertBefore, 0);
src/StaticCaching/Replacers/NoCacheReplacer.php injects the nocache script before </body>:
// line 97
$contents = str_replace('</body>', $cacher->getNocacheScript().'</body>', $contents);
Both scripts are IIFEs that call fetch() synchronously on execution. From src/StaticCaching/Cachers/FileCacher.php:
// getCsrfTokenJs(), lines 255-263
(function() {
fetch('/!/csrf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
.then((response) => response.json())
.then((data) => {
for (const input of document.querySelectorAll('input[value="$csrfPlaceholder"]')) {
input.value = data.csrf;
}
// getNocacheJs(), lines 328-339
var map = createMap();
fetch('{$nocacheUrl}', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: window.location.href.split('#')[0],
sections: Object.keys(map)
})
})
.then((response) => response.json())
.then((data) => {
The nocache script never touches _token inputs, although its controller also returns the token (src/StaticCaching/NoCache/NoCacheController.php, line 34: 'csrf' => csrf_token(),). The csrf controller returns only the token (src/StaticCaching/NoCache/CsrfTokenController.php, lines 9-11).
Both routes run inside the web middleware group with the session middleware, only CSRF verification is removed (routes/web.php, lines 105-111). For a first-time visitor neither request carries a session cookie, so Laravel starts a separate session for each. Each response ends with its own Set-Cookie: <app>_session=..., and the browser keeps whichever arrives last. The nocache response renders the regions and is larger, so in practice it lands last. The page then holds:
input[name=_token]: token of session A (from/!/csrf)- cookie jar: session B (from
/!/nocache)
VerifyCsrfToken compares the posted token against session B and rejects it.
On the second page load the cookie exists, both requests reuse session B and everything lines up, which is why the bug only hits the first page a visitor loads. It also only shows when the page has both a form and a nocache region, otherwise only one script is injected.
Playwright snippet showing the mismatch without submitting
import { chromium } from 'playwright';
const url = 'https://example.test/page-with-form-and-nocache';
const browser = await chromium.launch();
const context = await browser.newContext(); // fresh cookie jar
const page = await context.newPage();
const seen = {};
page.on('response', async (res) => {
const path = new URL(res.url()).pathname;
if (path === '/!/csrf' || path === '/!/nocache') {
const body = await res.json();
const setCookie = res.headers()['set-cookie'] ?? '';
seen[path] = {
csrf: body.csrf,
sessionCookie: (setCookie.match(/[a-z0-9_]+_session=([^;]+)/i) ?? [])[1],
};
}
});
await page.goto(url, { waitUntil: 'networkidle' });
const pageToken = await page.$eval('input[name=_token]', (el) => el.value);
const jarCookie = (await context.cookies(url)).find((c) => c.name.endsWith('_session'))?.value;
console.log({ seen, pageToken, jarCookie });
console.log('token source:', Object.entries(seen).find(([, v]) => v.csrf === pageToken)?.[0]);
console.log('cookie source:', Object.entries(seen).find(([, v]) => v.sessionCookie === jarCookie)?.[0]);
await browser.close();
Typical output on a fresh context: token source: /!/csrf, cookie source: /!/nocache. The two csrf values differ.
Proposed fix
Any one of these removes the race, listed from least to most invasive:
- Make the nocache script also update the token from its own response. It already receives
data.csrf; applying the same replacement loop the csrf script uses (input[value="STATAMIC_CSRF_TOKEN"],meta[content=...],script[data-csrf=...], plus the Livewire hooks) would make the last response win for both token and cookie. Downside: if the csrf response arrives last, the inputs still get the csrf token while the cookie is nocache's, so this only helps when nocache lands last, which is the common case but not guaranteed. Better: have the nocache script set the token only when the csrf one has not yet replaced it, and vice versa, with the later one overwriting. Since the cookie is also last-wins, consistently last-wins on both sides fixes it. - Chain the requests. When both scripts are present, let the nocache script wait for
statamic:csrf.replaced(the event the csrf script already dispatches, FileCacher.php line 291) before calling/!/nocache. The second request then carries the cookie from the first and both responses share one session. Costs one round trip of latency on nocache regions. - Serve the token from the same request. Drop the separate
/!/csrfcall when a nocache script is present and let the nocache response handle token replacement. Largest change, but one request and no ordering concerns.
Option 1 with a consistent last-wins rule is the smallest change. Option 2 is the most robust without restructuring the endpoints.
A reproduction can be verified with the Playwright snippet above: after the fix, token source and cookie source must name the same endpoint, or the csrf values in both responses must be equal.
- 主要语言
- PHP
- 星标
- 4.9k
- 派生
- 647
- 平均合并
- 1 天 18 小时
- 30 天内合并 PR
- 118
环境准备
这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
statamic/cms 的其他 Issue
-
fieldtypes ui
难度 2/5 1-3 小时 新手友好度 76/100
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 74/100
维护者通常 1 天内回复
-
accessibility
难度 2/5 1-3 小时 新手友好度 74/100
维护者通常 1 天内回复
-
[7.x] Reintroduce parser error for mixed pipe/shorthand modifier syntax可能已有人在做 关联的 PR 仍在进行中或已合并。 未关闭antlers
难度 2/5 1-3 小时 新手友好度 66/100
维护者通常 1 天内回复
-
难度 3/5 半天 新手友好度 62/100
维护者通常 1 天内回复
相似的 Issue
-
难度 2/5 1-3 小时 新手友好度 78/100
-
Featured image not passed to checks in the Tasks column or publish blocks可能已有人在做 @roborourke 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 78/100
humanmade/publication-checklist#100 ·
维护者通常 1 天内回复
-
bug customer-reported
难度 2/5 1-3 小时 新手友好度 62/100
MagnaCapax/PMSS#1072 ·
维护者通常 5 天内回复
-
bug
难度 2/5 1-3 小时 新手友好度 62/100
hestiacp/hestiacp#5800 · 1 条评论 ·
维护者通常 1 天内回复
-
难度 2/5 半天 新手友好度 68/100
components-web-app/docs#244 ·