Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,8 @@ src/Pages/
ルート直下に `error.psx` を置くと、ルートレイアウト内にエラーレスポンスが
レンダリングされます。未マッチルート(404)、ページへの未対応メソッド(405)、
すべての `$ctx->abort()` ステータス、`#[Auth]` / `$ctx->requireAuth()` の
`401` / `403`、未捕捉例外(500)が対象です。
`401` / `403`、CSRF トークンや署名の検証で拒否したフォームアクションの `403`、
未捕捉例外(500)が対象です。
エラーの描画中にルートレイアウト自身が認証ガードで失敗したり abort した場合は
レイアウトなしで `error.psx` を描画し、`error.psx` も同様に失敗した場合はデフォルト
表示になります。どの場合もステータスは変わりません。ステータスとメッセージが
Expand Down Expand Up @@ -1230,9 +1231,11 @@ public function save(array $form): void
}
```

CSRF トークンが無効な場合は `403` が返ります。トークンを `_rosanna_action` の
hidden input に自分で書かないでください。`_rosanna_csrf` が入るのは `action` に
トークンを持つ form だけなので、その形の form は必ず `403` になります。
CSRF トークンが無効な場合は `403` が返ります。`$ctx->abort(403)` と同じ経路
(`error.psx`、無ければ組み込みの表示)で応答し、ページ自体は描画しません。
トークンを `_rosanna_action` の hidden input に自分で書かないでください。
`_rosanna_csrf` が入るのは `action` にトークンを持つ form だけなので、その形の
form は必ず `403` になります。

クラス型のページには `PageContext` が無いので、リダイレクトは
`RedirectException`(`$ctx->redirect()` が投げる例外)を投げて行います。ルータが
Expand Down
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,8 @@ src/Pages/
A root `error.psx` renders error responses inside the root layout — an
unmatched route (404), an unsupported method on a page (405), every
`$ctx->abort()` status, the `401` / `403` from `#[Auth]` /
`$ctx->requireAuth()`, and an uncaught exception (500). If the root layout itself
`$ctx->requireAuth()`, the `403` of a form action refused for its CSRF token or
signature, and an uncaught exception (500). If the root layout itself
fails an auth guard or aborts while rendering the error, `error.psx` renders
without it; if `error.psx` fails the same way, the default document is used. The
status is unchanged either way. It receives the status and message, so one
Expand Down Expand Up @@ -1223,10 +1224,11 @@ public function save(array $form): void
}
```

Invalid CSRF tokens return a `403`. Don't write the token into a
`_rosanna_action` hidden input yourself: only a form whose `action` holds the
token gets the `_rosanna_csrf` field, so such a form is always refused with
`403`.
Invalid CSRF tokens return a `403`, rendered through the same error path as
`$ctx->abort(403)` (`error.psx`, or the built-in page) — the page itself is
not rendered. Don't write the token into a `_rosanna_action` hidden input
yourself: only a form whose `action` holds the token gets the `_rosanna_csrf`
field, so such a form is always refused with `403`.

A class-style page has no `PageContext`, so redirect by throwing
`RedirectException` (what `$ctx->redirect()` throws). The router turns it
Expand Down
11 changes: 5 additions & 6 deletions src/Router/Component/FunctionPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Polidog\Relayer\Router\Document\Script;
use Polidog\Relayer\Router\Form\CsrfToken;
use Polidog\Relayer\Router\Form\FormAction;
use Polidog\Relayer\Router\HttpException;
use Polidog\Rosanna\Runtime\Element;

final class FunctionPage
Expand Down Expand Up @@ -108,18 +109,16 @@ public function dispatchActionFromRequest(): void

$csrf = $request->post(self::FORM_CSRF_FIELD);
if (null === $csrf || !CsrfToken::validate($csrf)) {
\http_response_code(403);

return;
// Answer like `$ctx->abort(403)`: the router renders error.psx
// (or the built-in page) instead of the page with fresh tokens.
throw new HttpException(403);
}

// Verified decode: the name and the bound args below come only from
// a token this server signed, so a client cannot rewrite them.
$payload = FormAction::decode($token);
if (null === $payload || ($payload['page'] ?? null) !== $this->pageId) {
\http_response_code(403);

return;
throw new HttpException(403);
}

$name = $payload['name'] ?? null;
Expand Down
9 changes: 5 additions & 4 deletions src/Router/Component/PageComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Polidog\Relayer\Router\Document\Script;
use Polidog\Relayer\Router\Form\CsrfToken;
use Polidog\Relayer\Router\Form\FormAction;
use Polidog\Relayer\Router\HttpException;
use Polidog\Rosanna\Runtime\Renderable;
use ReflectionMethod;

Expand Down Expand Up @@ -83,9 +84,9 @@ public function dispatchActionFromRequest(): void

$csrf = $request->post(self::FORM_CSRF_FIELD);
if (null === $csrf || !CsrfToken::validate($csrf)) {
\http_response_code(403);

return;
// Answer like `$ctx->abort(403)`: the router renders error.psx
// (or the built-in page) instead of the page with fresh tokens.
throw new HttpException(403);
}

// Verified decode: only a token this server minted via action() for
Expand All @@ -96,7 +97,7 @@ public function dispatchActionFromRequest(): void
if (null === $payload) {
if (FormAction::isToken($token)) {
// Forged or tampered token: refuse, like a bad CSRF token.
\http_response_code(403);
throw new HttpException(403);
}

return;
Expand Down
232 changes: 232 additions & 0 deletions tests/Router/ActionForbiddenErrorPageTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
<?php

declare(strict_types=1);

namespace Polidog\Relayer\Tests\Router;

use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use PHPUnit\Framework\TestCase;
use Polidog\Relayer\Router\AppRouter;
use Polidog\Relayer\Router\Form\FormAction;
use Polidog\Relayer\Tests\Fixtures\FormActionTokens;

/**
* A form action refused for a bad CSRF field or a token whose signature does
* not verify answers like `$ctx->abort(403)`: `error.psx` (or the built-in
* document) with a 403, not the page rendered again with fresh tokens (#132).
*
* CsrfToken and the token signing key live in the session, so each test runs
* in its own process; the GET and the POST share it.
*/
final class ActionForbiddenErrorPageTest extends TestCase
{
private const FUNCTION_PAGE = <<<'PHP'
<?php
declare(strict_types=1);
use Polidog\Relayer\Router\Component\PageContext;
use Polidog\Rosanna\Runtime\Element;
return function (PageContext $ctx): Closure {
$save = $ctx->action('save', static function (): void {
$GLOBALS['action_ran'] = true;
}, ['id' => 1]);

return static fn (): Element => new Element('form', ['action' => $save], ['normal page body']);
};
PHP;

private const CLASS_PAGE = <<<'PHP'
<?php
declare(strict_types=1);
namespace App\ActionForbidden;
use Polidog\Relayer\Router\Component\PageComponent;
use Polidog\Rosanna\Runtime\Element;
final class FormPage extends PageComponent
{
public function render(): Element
{
return new Element('form', ['action' => $this->action([$this, 'save'], ['id' => 1])], ['normal page body']);
}

public function save(array $formData, int $id): void
{
$GLOBALS['action_ran'] = true;
}
}
PHP;

private const ERROR_PAGE = <<<'PHP'
<?php
declare(strict_types=1);
namespace App\ActionForbidden;
use Polidog\Relayer\Router\Component\ErrorPageComponent;
use Polidog\Rosanna\Runtime\Element;
final class ErrorPage extends ErrorPageComponent
{
public function render(): Element
{
return new Element('h1', [], ['custom error ' . $this->getStatusCode() . ': ' . $this->getMessage()]);
}
}
PHP;

private string $workDir;

protected function setUp(): void
{
$this->workDir = \sys_get_temp_dir() . '/relayer-action-forbidden-' . \bin2hex(\random_bytes(6));
\mkdir($this->workDir, 0o777, true);
$_POST = [];
unset($GLOBALS['action_ran']);
}

protected function tearDown(): void
{
foreach (\glob($this->workDir . '/*') ?: [] as $file) {
\unlink($file);
}
\rmdir($this->workDir);
$_POST = [];
unset($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $GLOBALS['action_ran']);
}

#[RunInSeparateProcess]
public function testFunctionPageBadCsrfRendersTheErrorPage(): void
{
$this->writePage(self::FUNCTION_PAGE);
$this->writeErrorPage();

$fields = $this->submission($this->request('GET'));
$html = $this->request('POST', ['_rosanna_csrf' => 'forged'] + $fields);

$this->assertErrorPage($html);
}

#[RunInSeparateProcess]
public function testFunctionPageTamperedTokenRendersTheErrorPage(): void
{
$this->writePage(self::FUNCTION_PAGE);
$this->writeErrorPage();

$fields = $this->submission($this->request('GET'));
$fields['_rosanna_action'] = FormActionTokens::withPayload($fields['_rosanna_action'], [
'page' => '/',
'name' => 'save',
'args' => ['id' => 999],
]);
$html = $this->request('POST', $fields);

$this->assertErrorPage($html);
}

#[RunInSeparateProcess]
public function testClassPageBadCsrfRendersTheErrorPage(): void
{
$this->writePage(self::CLASS_PAGE);
$this->writeErrorPage();

$fields = $this->submission($this->request('GET'));
$html = $this->request('POST', ['_rosanna_csrf' => 'forged'] + $fields);

$this->assertErrorPage($html);
}

#[RunInSeparateProcess]
public function testClassPageTamperedTokenRendersTheErrorPage(): void
{
$this->writePage(self::CLASS_PAGE);
$this->writeErrorPage();

$fields = $this->submission($this->request('GET'));
$fields['_rosanna_action'] = FormActionTokens::withPayload($fields['_rosanna_action'], [
'class' => 'App\ActionForbidden\FormPage',
'method' => 'save',
'args' => ['id' => 999],
]);
$html = $this->request('POST', $fields);

$this->assertErrorPage($html);
}

#[RunInSeparateProcess]
public function testWithoutErrorPageTheBuiltInDocumentIsRendered(): void
{
$this->writePage(self::FUNCTION_PAGE);

$fields = $this->submission($this->request('GET'));
$html = $this->request('POST', ['_rosanna_csrf' => 'forged'] + $fields);

self::assertSame(403, \http_response_code());
self::assertStringContainsString('Forbidden', $html);
self::assertStringNotContainsString('normal page body', $html);
self::assertStringNotContainsString('_rosanna_csrf', $html);
self::assertArrayNotHasKey('action_ran', $GLOBALS);
}

private function assertErrorPage(string $html): void
{
self::assertSame(403, \http_response_code());
self::assertStringContainsString('custom error 403: Forbidden', $html);
self::assertStringNotContainsString('normal page body', $html);
self::assertStringNotContainsString('_rosanna_csrf', $html);
self::assertArrayNotHasKey('action_ran', $GLOBALS);
}

private function writePage(string $source): void
{
\file_put_contents($this->workDir . '/page.php', $source);
}

private function writeErrorPage(): void
{
\file_put_contents($this->workDir . '/error.php', self::ERROR_PAGE);
}

/**
* @param array<string, string> $post
*/
private function request(string $method, array $post = []): string
{
$_SERVER['REQUEST_METHOD'] = $method;
$_SERVER['REQUEST_URI'] = '/';
$_POST = $post;

\http_response_code(200);
\ob_start();

try {
AppRouter::create($this->workDir)->run();
} finally {
$html = (string) \ob_get_clean();
}

return $html;
}

/**
* The hidden action and CSRF fields of the rendered form.
*
* @return array{_rosanna_action: string, _rosanna_csrf: string}
*/
private function submission(string $html): array
{
\preg_match_all('#<input type="hidden" name="(_rosanna_\w+)" value="([^"]*)"#', $html, $fields, \PREG_SET_ORDER);

$action = null;
$csrf = null;
foreach ($fields as [, $field, $value]) {
$value = \html_entity_decode($value, \ENT_QUOTES | \ENT_HTML5);

if ('_rosanna_csrf' === $field) {
$csrf = $value;
} elseif (null !== FormAction::peek($value)) {
$action = $value;
}
}

if (null === $action || null === $csrf) {
self::fail('No action form in: ' . $html);
}

return ['_rosanna_action' => $action, '_rosanna_csrf' => $csrf];
}
}
Loading
Loading