- New SecurityHeadersMiddleware (outermost): CSP with a per-request script nonce, framing (SAMEORIGIN, embeds via frame-ancestors), nosniff, Referrer- and Permissions-Policy. JSON, files and error pages are covered now, not only rendered HTML; headers set by controllers still win. - The inline theme script carries the nonce; flash messages are dismissed via data-dismiss instead of inline onclick handlers, and the flash elements share one template. - reCAPTCHA sources are only allowed when it is enabled. - The embed CSRF exception and framing use the same isEmbed() check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
61 lines
1.7 KiB
PHP
61 lines
1.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Controller;
|
|
|
|
use App\Service\ThrottleService;
|
|
use Cake\Controller\Controller;
|
|
use Cake\Core\Configure;
|
|
use Cake\Http\Response;
|
|
|
|
/**
|
|
* Base controller of PlenarIO. Security headers (CSP, framing, nosniff) are set for every
|
|
* response by \App\Middleware\SecurityHeadersMiddleware.
|
|
*/
|
|
class AppController extends Controller
|
|
{
|
|
/**
|
|
* @return void
|
|
*/
|
|
public function initialize(): void
|
|
{
|
|
parent::initialize();
|
|
|
|
$this->loadComponent('Flash');
|
|
}
|
|
|
|
/**
|
|
* Registers a hit of the client IP in a throttle bucket (see ThrottleService).
|
|
*
|
|
* @param string $bucket Throttle bucket
|
|
* @param string $configKey Configure key holding the limit (0 = unlimited)
|
|
* @param int $windowSeconds Length of the window
|
|
* @return bool Whether the request is still allowed
|
|
*/
|
|
protected function throttle(string $bucket, string $configKey, int $windowSeconds = ThrottleService::WINDOW_SECONDS): bool
|
|
{
|
|
return (new ThrottleService())->attempt(
|
|
$bucket,
|
|
(string)$this->request->clientIp(),
|
|
(int)Configure::read($configKey, 0),
|
|
$windowSeconds,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Returns a JSON response without going through the view layer.
|
|
*
|
|
* @param array<string, mixed> $data Payload
|
|
* @param int $status HTTP status
|
|
* @return \Cake\Http\Response
|
|
*/
|
|
protected function json(array $data, int $status = 200): Response
|
|
{
|
|
return $this->response
|
|
->withStatus($status)
|
|
->withType('application/json')
|
|
->withHeader('Cache-Control', 'no-store')
|
|
->withStringBody((string)json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
|
}
|
|
}
|