Hacktoberfest 2026:メンテナが10月に向けて印を付けた、オープンで初心者向けの issue。 Hacktoberfest の issue を見る

Static caching: `/!/csrf` and `/!/nocache` race on first visit, page token and session cookie come from different sessions, form POST returns 419

オープン
#15,643 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
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 の本文から書いたものです。

説明

caching nocache
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
  1. Enable full static caching and warm the cache for a page that has a form and a {{ nocache }} region.
  2. Open that page in a fresh browser (no cookies for the site).
  3. 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:

  1. 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.
  2. 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.
  3. Serve the token from the same request. Drop the separate /!/csrf call 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時間
マージ済み PR(30日)
118

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

statamic/cms のほかの issue

statamic/cms の issue をすべて見る

似ている issue

PHP の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。